pdf.combined.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163
  1. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  3. /* Copyright 2012 Mozilla Foundation
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*jshint globalstrict: false */
  18. /* globals PDFJS */
  19. // Initializing PDFJS global object (if still undefined)
  20. if (typeof PDFJS === 'undefined') {
  21. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  22. }
  23. PDFJS.version = '1.1.546';
  24. PDFJS.build = 'b3a9a0d';
  25. (function pdfjsWrapper() {
  26. // Use strict in our context only - users might not want it
  27. 'use strict';
  28. var globalScope = (typeof window === 'undefined') ? this : window;
  29. var isWorker = (typeof window === 'undefined');
  30. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  31. var TextRenderingMode = {
  32. FILL: 0,
  33. STROKE: 1,
  34. FILL_STROKE: 2,
  35. INVISIBLE: 3,
  36. FILL_ADD_TO_PATH: 4,
  37. STROKE_ADD_TO_PATH: 5,
  38. FILL_STROKE_ADD_TO_PATH: 6,
  39. ADD_TO_PATH: 7,
  40. FILL_STROKE_MASK: 3,
  41. ADD_TO_PATH_FLAG: 4
  42. };
  43. var ImageKind = {
  44. GRAYSCALE_1BPP: 1,
  45. RGB_24BPP: 2,
  46. RGBA_32BPP: 3
  47. };
  48. var AnnotationType = {
  49. WIDGET: 1,
  50. TEXT: 2,
  51. LINK: 3
  52. };
  53. var AnnotationBorderStyleType = {
  54. SOLID: 1,
  55. DASHED: 2,
  56. BEVELED: 3,
  57. INSET: 4,
  58. UNDERLINE: 5
  59. };
  60. var StreamType = {
  61. UNKNOWN: 0,
  62. FLATE: 1,
  63. LZW: 2,
  64. DCT: 3,
  65. JPX: 4,
  66. JBIG: 5,
  67. A85: 6,
  68. AHX: 7,
  69. CCF: 8,
  70. RL: 9
  71. };
  72. var FontType = {
  73. UNKNOWN: 0,
  74. TYPE1: 1,
  75. TYPE1C: 2,
  76. CIDFONTTYPE0: 3,
  77. CIDFONTTYPE0C: 4,
  78. TRUETYPE: 5,
  79. CIDFONTTYPE2: 6,
  80. TYPE3: 7,
  81. OPENTYPE: 8,
  82. TYPE0: 9,
  83. MMTYPE1: 10
  84. };
  85. // The global PDFJS object exposes the API
  86. // In production, it will be declared outside a global wrapper
  87. // In development, it will be declared here
  88. if (!globalScope.PDFJS) {
  89. globalScope.PDFJS = {};
  90. }
  91. globalScope.PDFJS.pdfBug = false;
  92. PDFJS.VERBOSITY_LEVELS = {
  93. errors: 0,
  94. warnings: 1,
  95. infos: 5
  96. };
  97. // All the possible operations for an operator list.
  98. var OPS = PDFJS.OPS = {
  99. // Intentionally start from 1 so it is easy to spot bad operators that will be
  100. // 0's.
  101. dependency: 1,
  102. setLineWidth: 2,
  103. setLineCap: 3,
  104. setLineJoin: 4,
  105. setMiterLimit: 5,
  106. setDash: 6,
  107. setRenderingIntent: 7,
  108. setFlatness: 8,
  109. setGState: 9,
  110. save: 10,
  111. restore: 11,
  112. transform: 12,
  113. moveTo: 13,
  114. lineTo: 14,
  115. curveTo: 15,
  116. curveTo2: 16,
  117. curveTo3: 17,
  118. closePath: 18,
  119. rectangle: 19,
  120. stroke: 20,
  121. closeStroke: 21,
  122. fill: 22,
  123. eoFill: 23,
  124. fillStroke: 24,
  125. eoFillStroke: 25,
  126. closeFillStroke: 26,
  127. closeEOFillStroke: 27,
  128. endPath: 28,
  129. clip: 29,
  130. eoClip: 30,
  131. beginText: 31,
  132. endText: 32,
  133. setCharSpacing: 33,
  134. setWordSpacing: 34,
  135. setHScale: 35,
  136. setLeading: 36,
  137. setFont: 37,
  138. setTextRenderingMode: 38,
  139. setTextRise: 39,
  140. moveText: 40,
  141. setLeadingMoveText: 41,
  142. setTextMatrix: 42,
  143. nextLine: 43,
  144. showText: 44,
  145. showSpacedText: 45,
  146. nextLineShowText: 46,
  147. nextLineSetSpacingShowText: 47,
  148. setCharWidth: 48,
  149. setCharWidthAndBounds: 49,
  150. setStrokeColorSpace: 50,
  151. setFillColorSpace: 51,
  152. setStrokeColor: 52,
  153. setStrokeColorN: 53,
  154. setFillColor: 54,
  155. setFillColorN: 55,
  156. setStrokeGray: 56,
  157. setFillGray: 57,
  158. setStrokeRGBColor: 58,
  159. setFillRGBColor: 59,
  160. setStrokeCMYKColor: 60,
  161. setFillCMYKColor: 61,
  162. shadingFill: 62,
  163. beginInlineImage: 63,
  164. beginImageData: 64,
  165. endInlineImage: 65,
  166. paintXObject: 66,
  167. markPoint: 67,
  168. markPointProps: 68,
  169. beginMarkedContent: 69,
  170. beginMarkedContentProps: 70,
  171. endMarkedContent: 71,
  172. beginCompat: 72,
  173. endCompat: 73,
  174. paintFormXObjectBegin: 74,
  175. paintFormXObjectEnd: 75,
  176. beginGroup: 76,
  177. endGroup: 77,
  178. beginAnnotations: 78,
  179. endAnnotations: 79,
  180. beginAnnotation: 80,
  181. endAnnotation: 81,
  182. paintJpegXObject: 82,
  183. paintImageMaskXObject: 83,
  184. paintImageMaskXObjectGroup: 84,
  185. paintImageXObject: 85,
  186. paintInlineImageXObject: 86,
  187. paintInlineImageXObjectGroup: 87,
  188. paintImageXObjectRepeat: 88,
  189. paintImageMaskXObjectRepeat: 89,
  190. paintSolidColorImageMask: 90,
  191. constructPath: 91
  192. };
  193. // A notice for devs. These are good for things that are helpful to devs, such
  194. // as warning that Workers were disabled, which is important to devs but not
  195. // end users.
  196. function info(msg) {
  197. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
  198. console.log('Info: ' + msg);
  199. }
  200. }
  201. // Non-fatal warnings.
  202. function warn(msg) {
  203. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
  204. console.log('Warning: ' + msg);
  205. }
  206. }
  207. // Fatal errors that should trigger the fallback UI and halt execution by
  208. // throwing an exception.
  209. function error(msg) {
  210. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) {
  211. console.log('Error: ' + msg);
  212. console.log(backtrace());
  213. }
  214. UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
  215. throw new Error(msg);
  216. }
  217. function backtrace() {
  218. try {
  219. throw new Error();
  220. } catch (e) {
  221. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  222. }
  223. }
  224. function assert(cond, msg) {
  225. if (!cond) {
  226. error(msg);
  227. }
  228. }
  229. var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
  230. unknown: 'unknown',
  231. forms: 'forms',
  232. javaScript: 'javaScript',
  233. smask: 'smask',
  234. shadingPattern: 'shadingPattern',
  235. font: 'font'
  236. };
  237. var UnsupportedManager = PDFJS.UnsupportedManager =
  238. (function UnsupportedManagerClosure() {
  239. var listeners = [];
  240. return {
  241. listen: function (cb) {
  242. listeners.push(cb);
  243. },
  244. notify: function (featureId) {
  245. warn('Unsupported feature "' + featureId + '"');
  246. for (var i = 0, ii = listeners.length; i < ii; i++) {
  247. listeners[i](featureId);
  248. }
  249. }
  250. };
  251. })();
  252. // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
  253. // absolute URL, it will be returned as is.
  254. function combineUrl(baseUrl, url) {
  255. if (!url) {
  256. return baseUrl;
  257. }
  258. if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
  259. return url;
  260. }
  261. var i;
  262. if (url.charAt(0) === '/') {
  263. // absolute path
  264. i = baseUrl.indexOf('://');
  265. if (url.charAt(1) === '/') {
  266. ++i;
  267. } else {
  268. i = baseUrl.indexOf('/', i + 3);
  269. }
  270. return baseUrl.substring(0, i) + url;
  271. } else {
  272. // relative path
  273. var pathLength = baseUrl.length;
  274. i = baseUrl.lastIndexOf('#');
  275. pathLength = i >= 0 ? i : pathLength;
  276. i = baseUrl.lastIndexOf('?', pathLength);
  277. pathLength = i >= 0 ? i : pathLength;
  278. var prefixLength = baseUrl.lastIndexOf('/', pathLength);
  279. return baseUrl.substring(0, prefixLength + 1) + url;
  280. }
  281. }
  282. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  283. function isValidUrl(url, allowRelative) {
  284. if (!url) {
  285. return false;
  286. }
  287. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  288. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  289. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  290. if (!protocol) {
  291. return allowRelative;
  292. }
  293. protocol = protocol[0].toLowerCase();
  294. switch (protocol) {
  295. case 'http':
  296. case 'https':
  297. case 'ftp':
  298. case 'mailto':
  299. case 'tel':
  300. return true;
  301. default:
  302. return false;
  303. }
  304. }
  305. PDFJS.isValidUrl = isValidUrl;
  306. function shadow(obj, prop, value) {
  307. Object.defineProperty(obj, prop, { value: value,
  308. enumerable: true,
  309. configurable: true,
  310. writable: false });
  311. return value;
  312. }
  313. PDFJS.shadow = shadow;
  314. var LinkTarget = PDFJS.LinkTarget = {
  315. NONE: 0, // Default value.
  316. SELF: 1,
  317. BLANK: 2,
  318. PARENT: 3,
  319. TOP: 4,
  320. };
  321. var LinkTargetStringMap = [
  322. '',
  323. '_self',
  324. '_blank',
  325. '_parent',
  326. '_top'
  327. ];
  328. function isExternalLinkTargetSet() {
  329. switch (PDFJS.externalLinkTarget) {
  330. case LinkTarget.NONE:
  331. return false;
  332. case LinkTarget.SELF:
  333. case LinkTarget.BLANK:
  334. case LinkTarget.PARENT:
  335. case LinkTarget.TOP:
  336. return true;
  337. }
  338. warn('PDFJS.externalLinkTarget is invalid: ' + PDFJS.externalLinkTarget);
  339. // Reset the external link target, to suppress further warnings.
  340. PDFJS.externalLinkTarget = LinkTarget.NONE;
  341. return false;
  342. }
  343. PDFJS.isExternalLinkTargetSet = isExternalLinkTargetSet;
  344. var PasswordResponses = PDFJS.PasswordResponses = {
  345. NEED_PASSWORD: 1,
  346. INCORRECT_PASSWORD: 2
  347. };
  348. var PasswordException = (function PasswordExceptionClosure() {
  349. function PasswordException(msg, code) {
  350. this.name = 'PasswordException';
  351. this.message = msg;
  352. this.code = code;
  353. }
  354. PasswordException.prototype = new Error();
  355. PasswordException.constructor = PasswordException;
  356. return PasswordException;
  357. })();
  358. PDFJS.PasswordException = PasswordException;
  359. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  360. function UnknownErrorException(msg, details) {
  361. this.name = 'UnknownErrorException';
  362. this.message = msg;
  363. this.details = details;
  364. }
  365. UnknownErrorException.prototype = new Error();
  366. UnknownErrorException.constructor = UnknownErrorException;
  367. return UnknownErrorException;
  368. })();
  369. PDFJS.UnknownErrorException = UnknownErrorException;
  370. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  371. function InvalidPDFException(msg) {
  372. this.name = 'InvalidPDFException';
  373. this.message = msg;
  374. }
  375. InvalidPDFException.prototype = new Error();
  376. InvalidPDFException.constructor = InvalidPDFException;
  377. return InvalidPDFException;
  378. })();
  379. PDFJS.InvalidPDFException = InvalidPDFException;
  380. var MissingPDFException = (function MissingPDFExceptionClosure() {
  381. function MissingPDFException(msg) {
  382. this.name = 'MissingPDFException';
  383. this.message = msg;
  384. }
  385. MissingPDFException.prototype = new Error();
  386. MissingPDFException.constructor = MissingPDFException;
  387. return MissingPDFException;
  388. })();
  389. PDFJS.MissingPDFException = MissingPDFException;
  390. var UnexpectedResponseException =
  391. (function UnexpectedResponseExceptionClosure() {
  392. function UnexpectedResponseException(msg, status) {
  393. this.name = 'UnexpectedResponseException';
  394. this.message = msg;
  395. this.status = status;
  396. }
  397. UnexpectedResponseException.prototype = new Error();
  398. UnexpectedResponseException.constructor = UnexpectedResponseException;
  399. return UnexpectedResponseException;
  400. })();
  401. PDFJS.UnexpectedResponseException = UnexpectedResponseException;
  402. var NotImplementedException = (function NotImplementedExceptionClosure() {
  403. function NotImplementedException(msg) {
  404. this.message = msg;
  405. }
  406. NotImplementedException.prototype = new Error();
  407. NotImplementedException.prototype.name = 'NotImplementedException';
  408. NotImplementedException.constructor = NotImplementedException;
  409. return NotImplementedException;
  410. })();
  411. var MissingDataException = (function MissingDataExceptionClosure() {
  412. function MissingDataException(begin, end) {
  413. this.begin = begin;
  414. this.end = end;
  415. this.message = 'Missing data [' + begin + ', ' + end + ')';
  416. }
  417. MissingDataException.prototype = new Error();
  418. MissingDataException.prototype.name = 'MissingDataException';
  419. MissingDataException.constructor = MissingDataException;
  420. return MissingDataException;
  421. })();
  422. var XRefParseException = (function XRefParseExceptionClosure() {
  423. function XRefParseException(msg) {
  424. this.message = msg;
  425. }
  426. XRefParseException.prototype = new Error();
  427. XRefParseException.prototype.name = 'XRefParseException';
  428. XRefParseException.constructor = XRefParseException;
  429. return XRefParseException;
  430. })();
  431. function bytesToString(bytes) {
  432. assert(bytes !== null && typeof bytes === 'object' &&
  433. bytes.length !== undefined, 'Invalid argument for bytesToString');
  434. var length = bytes.length;
  435. var MAX_ARGUMENT_COUNT = 8192;
  436. if (length < MAX_ARGUMENT_COUNT) {
  437. return String.fromCharCode.apply(null, bytes);
  438. }
  439. var strBuf = [];
  440. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  441. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  442. var chunk = bytes.subarray(i, chunkEnd);
  443. strBuf.push(String.fromCharCode.apply(null, chunk));
  444. }
  445. return strBuf.join('');
  446. }
  447. function stringToBytes(str) {
  448. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  449. var length = str.length;
  450. var bytes = new Uint8Array(length);
  451. for (var i = 0; i < length; ++i) {
  452. bytes[i] = str.charCodeAt(i) & 0xFF;
  453. }
  454. return bytes;
  455. }
  456. function string32(value) {
  457. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  458. (value >> 8) & 0xff, value & 0xff);
  459. }
  460. function log2(x) {
  461. var n = 1, i = 0;
  462. while (x > n) {
  463. n <<= 1;
  464. i++;
  465. }
  466. return i;
  467. }
  468. function readInt8(data, start) {
  469. return (data[start] << 24) >> 24;
  470. }
  471. function readUint16(data, offset) {
  472. return (data[offset] << 8) | data[offset + 1];
  473. }
  474. function readUint32(data, offset) {
  475. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  476. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  477. }
  478. // Lazy test the endianness of the platform
  479. // NOTE: This will be 'true' for simulated TypedArrays
  480. function isLittleEndian() {
  481. var buffer8 = new Uint8Array(2);
  482. buffer8[0] = 1;
  483. var buffer16 = new Uint16Array(buffer8.buffer);
  484. return (buffer16[0] === 1);
  485. }
  486. Object.defineProperty(PDFJS, 'isLittleEndian', {
  487. configurable: true,
  488. get: function PDFJS_isLittleEndian() {
  489. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  490. }
  491. });
  492. // Lazy test if the userAgent support CanvasTypedArrays
  493. function hasCanvasTypedArrays() {
  494. var canvas = document.createElement('canvas');
  495. canvas.width = canvas.height = 1;
  496. var ctx = canvas.getContext('2d');
  497. var imageData = ctx.createImageData(1, 1);
  498. return (typeof imageData.data.buffer !== 'undefined');
  499. }
  500. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  501. configurable: true,
  502. get: function PDFJS_hasCanvasTypedArrays() {
  503. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  504. }
  505. });
  506. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  507. function Uint32ArrayView(buffer, length) {
  508. this.buffer = buffer;
  509. this.byteLength = buffer.length;
  510. this.length = length === undefined ? (this.byteLength >> 2) : length;
  511. ensureUint32ArrayViewProps(this.length);
  512. }
  513. Uint32ArrayView.prototype = Object.create(null);
  514. var uint32ArrayViewSetters = 0;
  515. function createUint32ArrayProp(index) {
  516. return {
  517. get: function () {
  518. var buffer = this.buffer, offset = index << 2;
  519. return (buffer[offset] | (buffer[offset + 1] << 8) |
  520. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  521. },
  522. set: function (value) {
  523. var buffer = this.buffer, offset = index << 2;
  524. buffer[offset] = value & 255;
  525. buffer[offset + 1] = (value >> 8) & 255;
  526. buffer[offset + 2] = (value >> 16) & 255;
  527. buffer[offset + 3] = (value >>> 24) & 255;
  528. }
  529. };
  530. }
  531. function ensureUint32ArrayViewProps(length) {
  532. while (uint32ArrayViewSetters < length) {
  533. Object.defineProperty(Uint32ArrayView.prototype,
  534. uint32ArrayViewSetters,
  535. createUint32ArrayProp(uint32ArrayViewSetters));
  536. uint32ArrayViewSetters++;
  537. }
  538. }
  539. return Uint32ArrayView;
  540. })();
  541. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  542. var Util = PDFJS.Util = (function UtilClosure() {
  543. function Util() {}
  544. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  545. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  546. // creating many intermediate strings.
  547. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  548. rgbBuf[1] = r;
  549. rgbBuf[3] = g;
  550. rgbBuf[5] = b;
  551. return rgbBuf.join('');
  552. };
  553. // Concatenates two transformation matrices together and returns the result.
  554. Util.transform = function Util_transform(m1, m2) {
  555. return [
  556. m1[0] * m2[0] + m1[2] * m2[1],
  557. m1[1] * m2[0] + m1[3] * m2[1],
  558. m1[0] * m2[2] + m1[2] * m2[3],
  559. m1[1] * m2[2] + m1[3] * m2[3],
  560. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  561. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  562. ];
  563. };
  564. // For 2d affine transforms
  565. Util.applyTransform = function Util_applyTransform(p, m) {
  566. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  567. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  568. return [xt, yt];
  569. };
  570. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  571. var d = m[0] * m[3] - m[1] * m[2];
  572. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  573. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  574. return [xt, yt];
  575. };
  576. // Applies the transform to the rectangle and finds the minimum axially
  577. // aligned bounding box.
  578. Util.getAxialAlignedBoundingBox =
  579. function Util_getAxialAlignedBoundingBox(r, m) {
  580. var p1 = Util.applyTransform(r, m);
  581. var p2 = Util.applyTransform(r.slice(2, 4), m);
  582. var p3 = Util.applyTransform([r[0], r[3]], m);
  583. var p4 = Util.applyTransform([r[2], r[1]], m);
  584. return [
  585. Math.min(p1[0], p2[0], p3[0], p4[0]),
  586. Math.min(p1[1], p2[1], p3[1], p4[1]),
  587. Math.max(p1[0], p2[0], p3[0], p4[0]),
  588. Math.max(p1[1], p2[1], p3[1], p4[1])
  589. ];
  590. };
  591. Util.inverseTransform = function Util_inverseTransform(m) {
  592. var d = m[0] * m[3] - m[1] * m[2];
  593. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  594. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  595. };
  596. // Apply a generic 3d matrix M on a 3-vector v:
  597. // | a b c | | X |
  598. // | d e f | x | Y |
  599. // | g h i | | Z |
  600. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  601. // with v as [X,Y,Z]
  602. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  603. return [
  604. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  605. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  606. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  607. ];
  608. };
  609. // This calculation uses Singular Value Decomposition.
  610. // The SVD can be represented with formula A = USV. We are interested in the
  611. // matrix S here because it represents the scale values.
  612. Util.singularValueDecompose2dScale =
  613. function Util_singularValueDecompose2dScale(m) {
  614. var transpose = [m[0], m[2], m[1], m[3]];
  615. // Multiply matrix m with its transpose.
  616. var a = m[0] * transpose[0] + m[1] * transpose[2];
  617. var b = m[0] * transpose[1] + m[1] * transpose[3];
  618. var c = m[2] * transpose[0] + m[3] * transpose[2];
  619. var d = m[2] * transpose[1] + m[3] * transpose[3];
  620. // Solve the second degree polynomial to get roots.
  621. var first = (a + d) / 2;
  622. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  623. var sx = first + second || 1;
  624. var sy = first - second || 1;
  625. // Scale values are the square roots of the eigenvalues.
  626. return [Math.sqrt(sx), Math.sqrt(sy)];
  627. };
  628. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  629. // For coordinate systems whose origin lies in the bottom-left, this
  630. // means normalization to (BL,TR) ordering. For systems with origin in the
  631. // top-left, this means (TL,BR) ordering.
  632. Util.normalizeRect = function Util_normalizeRect(rect) {
  633. var r = rect.slice(0); // clone rect
  634. if (rect[0] > rect[2]) {
  635. r[0] = rect[2];
  636. r[2] = rect[0];
  637. }
  638. if (rect[1] > rect[3]) {
  639. r[1] = rect[3];
  640. r[3] = rect[1];
  641. }
  642. return r;
  643. };
  644. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  645. // intersection of rect1 and rect2. If no intersection, returns 'false'
  646. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  647. Util.intersect = function Util_intersect(rect1, rect2) {
  648. function compare(a, b) {
  649. return a - b;
  650. }
  651. // Order points along the axes
  652. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  653. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  654. result = [];
  655. rect1 = Util.normalizeRect(rect1);
  656. rect2 = Util.normalizeRect(rect2);
  657. // X: first and second points belong to different rectangles?
  658. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  659. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  660. // Intersection must be between second and third points
  661. result[0] = orderedX[1];
  662. result[2] = orderedX[2];
  663. } else {
  664. return false;
  665. }
  666. // Y: first and second points belong to different rectangles?
  667. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  668. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  669. // Intersection must be between second and third points
  670. result[1] = orderedY[1];
  671. result[3] = orderedY[2];
  672. } else {
  673. return false;
  674. }
  675. return result;
  676. };
  677. Util.sign = function Util_sign(num) {
  678. return num < 0 ? -1 : 1;
  679. };
  680. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  681. Array.prototype.push.apply(arr1, arr2);
  682. };
  683. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  684. Array.prototype.unshift.apply(arr1, arr2);
  685. };
  686. Util.extendObj = function extendObj(obj1, obj2) {
  687. for (var key in obj2) {
  688. obj1[key] = obj2[key];
  689. }
  690. };
  691. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  692. name) {
  693. while (dict && !dict.has(name)) {
  694. dict = dict.get('Parent');
  695. }
  696. if (!dict) {
  697. return null;
  698. }
  699. return dict.get(name);
  700. };
  701. Util.inherit = function Util_inherit(sub, base, prototype) {
  702. sub.prototype = Object.create(base.prototype);
  703. sub.prototype.constructor = sub;
  704. for (var prop in prototype) {
  705. sub.prototype[prop] = prototype[prop];
  706. }
  707. };
  708. Util.loadScript = function Util_loadScript(src, callback) {
  709. var script = document.createElement('script');
  710. var loaded = false;
  711. script.setAttribute('src', src);
  712. if (callback) {
  713. script.onload = function() {
  714. if (!loaded) {
  715. callback();
  716. }
  717. loaded = true;
  718. };
  719. }
  720. document.getElementsByTagName('head')[0].appendChild(script);
  721. };
  722. return Util;
  723. })();
  724. /**
  725. * PDF page viewport created based on scale, rotation and offset.
  726. * @class
  727. * @alias PDFJS.PageViewport
  728. */
  729. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  730. /**
  731. * @constructor
  732. * @private
  733. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  734. * @param scale {number} scale of the viewport.
  735. * @param rotation {number} rotations of the viewport in degrees.
  736. * @param offsetX {number} offset X
  737. * @param offsetY {number} offset Y
  738. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  739. */
  740. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  741. this.viewBox = viewBox;
  742. this.scale = scale;
  743. this.rotation = rotation;
  744. this.offsetX = offsetX;
  745. this.offsetY = offsetY;
  746. // creating transform to convert pdf coordinate system to the normal
  747. // canvas like coordinates taking in account scale and rotation
  748. var centerX = (viewBox[2] + viewBox[0]) / 2;
  749. var centerY = (viewBox[3] + viewBox[1]) / 2;
  750. var rotateA, rotateB, rotateC, rotateD;
  751. rotation = rotation % 360;
  752. rotation = rotation < 0 ? rotation + 360 : rotation;
  753. switch (rotation) {
  754. case 180:
  755. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  756. break;
  757. case 90:
  758. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  759. break;
  760. case 270:
  761. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  762. break;
  763. //case 0:
  764. default:
  765. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  766. break;
  767. }
  768. if (dontFlip) {
  769. rotateC = -rotateC; rotateD = -rotateD;
  770. }
  771. var offsetCanvasX, offsetCanvasY;
  772. var width, height;
  773. if (rotateA === 0) {
  774. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  775. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  776. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  777. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  778. } else {
  779. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  780. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  781. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  782. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  783. }
  784. // creating transform for the following operations:
  785. // translate(-centerX, -centerY), rotate and flip vertically,
  786. // scale, and translate(offsetCanvasX, offsetCanvasY)
  787. this.transform = [
  788. rotateA * scale,
  789. rotateB * scale,
  790. rotateC * scale,
  791. rotateD * scale,
  792. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  793. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  794. ];
  795. this.width = width;
  796. this.height = height;
  797. this.fontScale = scale;
  798. }
  799. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  800. /**
  801. * Clones viewport with additional properties.
  802. * @param args {Object} (optional) If specified, may contain the 'scale' or
  803. * 'rotation' properties to override the corresponding properties in
  804. * the cloned viewport.
  805. * @returns {PDFJS.PageViewport} Cloned viewport.
  806. */
  807. clone: function PageViewPort_clone(args) {
  808. args = args || {};
  809. var scale = 'scale' in args ? args.scale : this.scale;
  810. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  811. return new PageViewport(this.viewBox.slice(), scale, rotation,
  812. this.offsetX, this.offsetY, args.dontFlip);
  813. },
  814. /**
  815. * Converts PDF point to the viewport coordinates. For examples, useful for
  816. * converting PDF location into canvas pixel coordinates.
  817. * @param x {number} X coordinate.
  818. * @param y {number} Y coordinate.
  819. * @returns {Object} Object that contains 'x' and 'y' properties of the
  820. * point in the viewport coordinate space.
  821. * @see {@link convertToPdfPoint}
  822. * @see {@link convertToViewportRectangle}
  823. */
  824. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  825. return Util.applyTransform([x, y], this.transform);
  826. },
  827. /**
  828. * Converts PDF rectangle to the viewport coordinates.
  829. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  830. * @returns {Array} Contains corresponding coordinates of the rectangle
  831. * in the viewport coordinate space.
  832. * @see {@link convertToViewportPoint}
  833. */
  834. convertToViewportRectangle:
  835. function PageViewport_convertToViewportRectangle(rect) {
  836. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  837. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  838. return [tl[0], tl[1], br[0], br[1]];
  839. },
  840. /**
  841. * Converts viewport coordinates to the PDF location. For examples, useful
  842. * for converting canvas pixel location into PDF one.
  843. * @param x {number} X coordinate.
  844. * @param y {number} Y coordinate.
  845. * @returns {Object} Object that contains 'x' and 'y' properties of the
  846. * point in the PDF coordinate space.
  847. * @see {@link convertToViewportPoint}
  848. */
  849. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  850. return Util.applyInverseTransform([x, y], this.transform);
  851. }
  852. };
  853. return PageViewport;
  854. })();
  855. var PDFStringTranslateTable = [
  856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  857. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  862. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  863. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  864. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  865. ];
  866. function stringToPDFString(str) {
  867. var i, n = str.length, strBuf = [];
  868. if (str[0] === '\xFE' && str[1] === '\xFF') {
  869. // UTF16BE BOM
  870. for (i = 2; i < n; i += 2) {
  871. strBuf.push(String.fromCharCode(
  872. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  873. }
  874. } else {
  875. for (i = 0; i < n; ++i) {
  876. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  877. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  878. }
  879. }
  880. return strBuf.join('');
  881. }
  882. function stringToUTF8String(str) {
  883. return decodeURIComponent(escape(str));
  884. }
  885. function utf8StringToString(str) {
  886. return unescape(encodeURIComponent(str));
  887. }
  888. function isEmptyObj(obj) {
  889. for (var key in obj) {
  890. return false;
  891. }
  892. return true;
  893. }
  894. function isBool(v) {
  895. return typeof v === 'boolean';
  896. }
  897. function isInt(v) {
  898. return typeof v === 'number' && ((v | 0) === v);
  899. }
  900. function isNum(v) {
  901. return typeof v === 'number';
  902. }
  903. function isString(v) {
  904. return typeof v === 'string';
  905. }
  906. function isName(v) {
  907. return v instanceof Name;
  908. }
  909. function isCmd(v, cmd) {
  910. return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
  911. }
  912. function isDict(v, type) {
  913. if (!(v instanceof Dict)) {
  914. return false;
  915. }
  916. if (!type) {
  917. return true;
  918. }
  919. var dictType = v.get('Type');
  920. return isName(dictType) && dictType.name === type;
  921. }
  922. function isArray(v) {
  923. return v instanceof Array;
  924. }
  925. function isStream(v) {
  926. return typeof v === 'object' && v !== null && v.getBytes !== undefined;
  927. }
  928. function isArrayBuffer(v) {
  929. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  930. }
  931. function isRef(v) {
  932. return v instanceof Ref;
  933. }
  934. /**
  935. * Promise Capability object.
  936. *
  937. * @typedef {Object} PromiseCapability
  938. * @property {Promise} promise - A promise object.
  939. * @property {function} resolve - Fullfills the promise.
  940. * @property {function} reject - Rejects the promise.
  941. */
  942. /**
  943. * Creates a promise capability object.
  944. * @alias PDFJS.createPromiseCapability
  945. *
  946. * @return {PromiseCapability} A capability object contains:
  947. * - a Promise, resolve and reject methods.
  948. */
  949. function createPromiseCapability() {
  950. var capability = {};
  951. capability.promise = new Promise(function (resolve, reject) {
  952. capability.resolve = resolve;
  953. capability.reject = reject;
  954. });
  955. return capability;
  956. }
  957. PDFJS.createPromiseCapability = createPromiseCapability;
  958. /**
  959. * Polyfill for Promises:
  960. * The following promise implementation tries to generally implement the
  961. * Promise/A+ spec. Some notable differences from other promise libaries are:
  962. * - There currently isn't a seperate deferred and promise object.
  963. * - Unhandled rejections eventually show an error if they aren't handled.
  964. *
  965. * Based off of the work in:
  966. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  967. */
  968. (function PromiseClosure() {
  969. if (globalScope.Promise) {
  970. // Promises existing in the DOM/Worker, checking presence of all/resolve
  971. if (typeof globalScope.Promise.all !== 'function') {
  972. globalScope.Promise.all = function (iterable) {
  973. var count = 0, results = [], resolve, reject;
  974. var promise = new globalScope.Promise(function (resolve_, reject_) {
  975. resolve = resolve_;
  976. reject = reject_;
  977. });
  978. iterable.forEach(function (p, i) {
  979. count++;
  980. p.then(function (result) {
  981. results[i] = result;
  982. count--;
  983. if (count === 0) {
  984. resolve(results);
  985. }
  986. }, reject);
  987. });
  988. if (count === 0) {
  989. resolve(results);
  990. }
  991. return promise;
  992. };
  993. }
  994. if (typeof globalScope.Promise.resolve !== 'function') {
  995. globalScope.Promise.resolve = function (value) {
  996. return new globalScope.Promise(function (resolve) { resolve(value); });
  997. };
  998. }
  999. if (typeof globalScope.Promise.reject !== 'function') {
  1000. globalScope.Promise.reject = function (reason) {
  1001. return new globalScope.Promise(function (resolve, reject) {
  1002. reject(reason);
  1003. });
  1004. };
  1005. }
  1006. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1007. globalScope.Promise.prototype.catch = function (onReject) {
  1008. return globalScope.Promise.prototype.then(undefined, onReject);
  1009. };
  1010. }
  1011. return;
  1012. }
  1013. var STATUS_PENDING = 0;
  1014. var STATUS_RESOLVED = 1;
  1015. var STATUS_REJECTED = 2;
  1016. // In an attempt to avoid silent exceptions, unhandled rejections are
  1017. // tracked and if they aren't handled in a certain amount of time an
  1018. // error is logged.
  1019. var REJECTION_TIMEOUT = 500;
  1020. var HandlerManager = {
  1021. handlers: [],
  1022. running: false,
  1023. unhandledRejections: [],
  1024. pendingRejectionCheck: false,
  1025. scheduleHandlers: function scheduleHandlers(promise) {
  1026. if (promise._status === STATUS_PENDING) {
  1027. return;
  1028. }
  1029. this.handlers = this.handlers.concat(promise._handlers);
  1030. promise._handlers = [];
  1031. if (this.running) {
  1032. return;
  1033. }
  1034. this.running = true;
  1035. setTimeout(this.runHandlers.bind(this), 0);
  1036. },
  1037. runHandlers: function runHandlers() {
  1038. var RUN_TIMEOUT = 1; // ms
  1039. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1040. while (this.handlers.length > 0) {
  1041. var handler = this.handlers.shift();
  1042. var nextStatus = handler.thisPromise._status;
  1043. var nextValue = handler.thisPromise._value;
  1044. try {
  1045. if (nextStatus === STATUS_RESOLVED) {
  1046. if (typeof handler.onResolve === 'function') {
  1047. nextValue = handler.onResolve(nextValue);
  1048. }
  1049. } else if (typeof handler.onReject === 'function') {
  1050. nextValue = handler.onReject(nextValue);
  1051. nextStatus = STATUS_RESOLVED;
  1052. if (handler.thisPromise._unhandledRejection) {
  1053. this.removeUnhandeledRejection(handler.thisPromise);
  1054. }
  1055. }
  1056. } catch (ex) {
  1057. nextStatus = STATUS_REJECTED;
  1058. nextValue = ex;
  1059. }
  1060. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1061. if (Date.now() >= timeoutAt) {
  1062. break;
  1063. }
  1064. }
  1065. if (this.handlers.length > 0) {
  1066. setTimeout(this.runHandlers.bind(this), 0);
  1067. return;
  1068. }
  1069. this.running = false;
  1070. },
  1071. addUnhandledRejection: function addUnhandledRejection(promise) {
  1072. this.unhandledRejections.push({
  1073. promise: promise,
  1074. time: Date.now()
  1075. });
  1076. this.scheduleRejectionCheck();
  1077. },
  1078. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1079. promise._unhandledRejection = false;
  1080. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1081. if (this.unhandledRejections[i].promise === promise) {
  1082. this.unhandledRejections.splice(i);
  1083. i--;
  1084. }
  1085. }
  1086. },
  1087. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1088. if (this.pendingRejectionCheck) {
  1089. return;
  1090. }
  1091. this.pendingRejectionCheck = true;
  1092. setTimeout(function rejectionCheck() {
  1093. this.pendingRejectionCheck = false;
  1094. var now = Date.now();
  1095. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1096. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1097. var unhandled = this.unhandledRejections[i].promise._value;
  1098. var msg = 'Unhandled rejection: ' + unhandled;
  1099. if (unhandled.stack) {
  1100. msg += '\n' + unhandled.stack;
  1101. }
  1102. warn(msg);
  1103. this.unhandledRejections.splice(i);
  1104. i--;
  1105. }
  1106. }
  1107. if (this.unhandledRejections.length) {
  1108. this.scheduleRejectionCheck();
  1109. }
  1110. }.bind(this), REJECTION_TIMEOUT);
  1111. }
  1112. };
  1113. function Promise(resolver) {
  1114. this._status = STATUS_PENDING;
  1115. this._handlers = [];
  1116. try {
  1117. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1118. } catch (e) {
  1119. this._reject(e);
  1120. }
  1121. }
  1122. /**
  1123. * Builds a promise that is resolved when all the passed in promises are
  1124. * resolved.
  1125. * @param {array} array of data and/or promises to wait for.
  1126. * @return {Promise} New dependant promise.
  1127. */
  1128. Promise.all = function Promise_all(promises) {
  1129. var resolveAll, rejectAll;
  1130. var deferred = new Promise(function (resolve, reject) {
  1131. resolveAll = resolve;
  1132. rejectAll = reject;
  1133. });
  1134. var unresolved = promises.length;
  1135. var results = [];
  1136. if (unresolved === 0) {
  1137. resolveAll(results);
  1138. return deferred;
  1139. }
  1140. function reject(reason) {
  1141. if (deferred._status === STATUS_REJECTED) {
  1142. return;
  1143. }
  1144. results = [];
  1145. rejectAll(reason);
  1146. }
  1147. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1148. var promise = promises[i];
  1149. var resolve = (function(i) {
  1150. return function(value) {
  1151. if (deferred._status === STATUS_REJECTED) {
  1152. return;
  1153. }
  1154. results[i] = value;
  1155. unresolved--;
  1156. if (unresolved === 0) {
  1157. resolveAll(results);
  1158. }
  1159. };
  1160. })(i);
  1161. if (Promise.isPromise(promise)) {
  1162. promise.then(resolve, reject);
  1163. } else {
  1164. resolve(promise);
  1165. }
  1166. }
  1167. return deferred;
  1168. };
  1169. /**
  1170. * Checks if the value is likely a promise (has a 'then' function).
  1171. * @return {boolean} true if value is thenable
  1172. */
  1173. Promise.isPromise = function Promise_isPromise(value) {
  1174. return value && typeof value.then === 'function';
  1175. };
  1176. /**
  1177. * Creates resolved promise
  1178. * @param value resolve value
  1179. * @returns {Promise}
  1180. */
  1181. Promise.resolve = function Promise_resolve(value) {
  1182. return new Promise(function (resolve) { resolve(value); });
  1183. };
  1184. /**
  1185. * Creates rejected promise
  1186. * @param reason rejection value
  1187. * @returns {Promise}
  1188. */
  1189. Promise.reject = function Promise_reject(reason) {
  1190. return new Promise(function (resolve, reject) { reject(reason); });
  1191. };
  1192. Promise.prototype = {
  1193. _status: null,
  1194. _value: null,
  1195. _handlers: null,
  1196. _unhandledRejection: null,
  1197. _updateStatus: function Promise__updateStatus(status, value) {
  1198. if (this._status === STATUS_RESOLVED ||
  1199. this._status === STATUS_REJECTED) {
  1200. return;
  1201. }
  1202. if (status === STATUS_RESOLVED &&
  1203. Promise.isPromise(value)) {
  1204. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1205. this._updateStatus.bind(this, STATUS_REJECTED));
  1206. return;
  1207. }
  1208. this._status = status;
  1209. this._value = value;
  1210. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1211. this._unhandledRejection = true;
  1212. HandlerManager.addUnhandledRejection(this);
  1213. }
  1214. HandlerManager.scheduleHandlers(this);
  1215. },
  1216. _resolve: function Promise_resolve(value) {
  1217. this._updateStatus(STATUS_RESOLVED, value);
  1218. },
  1219. _reject: function Promise_reject(reason) {
  1220. this._updateStatus(STATUS_REJECTED, reason);
  1221. },
  1222. then: function Promise_then(onResolve, onReject) {
  1223. var nextPromise = new Promise(function (resolve, reject) {
  1224. this.resolve = resolve;
  1225. this.reject = reject;
  1226. });
  1227. this._handlers.push({
  1228. thisPromise: this,
  1229. onResolve: onResolve,
  1230. onReject: onReject,
  1231. nextPromise: nextPromise
  1232. });
  1233. HandlerManager.scheduleHandlers(this);
  1234. return nextPromise;
  1235. },
  1236. catch: function Promise_catch(onReject) {
  1237. return this.then(undefined, onReject);
  1238. }
  1239. };
  1240. globalScope.Promise = Promise;
  1241. })();
  1242. var StatTimer = (function StatTimerClosure() {
  1243. function rpad(str, pad, length) {
  1244. while (str.length < length) {
  1245. str += pad;
  1246. }
  1247. return str;
  1248. }
  1249. function StatTimer() {
  1250. this.started = {};
  1251. this.times = [];
  1252. this.enabled = true;
  1253. }
  1254. StatTimer.prototype = {
  1255. time: function StatTimer_time(name) {
  1256. if (!this.enabled) {
  1257. return;
  1258. }
  1259. if (name in this.started) {
  1260. warn('Timer is already running for ' + name);
  1261. }
  1262. this.started[name] = Date.now();
  1263. },
  1264. timeEnd: function StatTimer_timeEnd(name) {
  1265. if (!this.enabled) {
  1266. return;
  1267. }
  1268. if (!(name in this.started)) {
  1269. warn('Timer has not been started for ' + name);
  1270. }
  1271. this.times.push({
  1272. 'name': name,
  1273. 'start': this.started[name],
  1274. 'end': Date.now()
  1275. });
  1276. // Remove timer from started so it can be called again.
  1277. delete this.started[name];
  1278. },
  1279. toString: function StatTimer_toString() {
  1280. var i, ii;
  1281. var times = this.times;
  1282. var out = '';
  1283. // Find the longest name for padding purposes.
  1284. var longest = 0;
  1285. for (i = 0, ii = times.length; i < ii; ++i) {
  1286. var name = times[i]['name'];
  1287. if (name.length > longest) {
  1288. longest = name.length;
  1289. }
  1290. }
  1291. for (i = 0, ii = times.length; i < ii; ++i) {
  1292. var span = times[i];
  1293. var duration = span.end - span.start;
  1294. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1295. }
  1296. return out;
  1297. }
  1298. };
  1299. return StatTimer;
  1300. })();
  1301. PDFJS.createBlob = function createBlob(data, contentType) {
  1302. if (typeof Blob !== 'undefined') {
  1303. return new Blob([data], { type: contentType });
  1304. }
  1305. // Blob builder is deprecated in FF14 and removed in FF18.
  1306. var bb = new MozBlobBuilder();
  1307. bb.append(data);
  1308. return bb.getBlob(contentType);
  1309. };
  1310. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1311. // Blob/createObjectURL is not available, falling back to data schema.
  1312. var digits =
  1313. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1314. return function createObjectURL(data, contentType) {
  1315. if (!PDFJS.disableCreateObjectURL &&
  1316. typeof URL !== 'undefined' && URL.createObjectURL) {
  1317. var blob = PDFJS.createBlob(data, contentType);
  1318. return URL.createObjectURL(blob);
  1319. }
  1320. var buffer = 'data:' + contentType + ';base64,';
  1321. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1322. var b1 = data[i] & 0xFF;
  1323. var b2 = data[i + 1] & 0xFF;
  1324. var b3 = data[i + 2] & 0xFF;
  1325. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1326. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1327. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1328. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1329. }
  1330. return buffer;
  1331. };
  1332. })();
  1333. function MessageHandler(name, comObj) {
  1334. this.name = name;
  1335. this.comObj = comObj;
  1336. this.callbackIndex = 1;
  1337. this.postMessageTransfers = true;
  1338. var callbacksCapabilities = this.callbacksCapabilities = {};
  1339. var ah = this.actionHandler = {};
  1340. ah['console_log'] = [function ahConsoleLog(data) {
  1341. console.log.apply(console, data);
  1342. }];
  1343. ah['console_error'] = [function ahConsoleError(data) {
  1344. console.error.apply(console, data);
  1345. }];
  1346. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1347. UnsupportedManager.notify(data);
  1348. }];
  1349. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1350. var data = event.data;
  1351. if (data.isReply) {
  1352. var callbackId = data.callbackId;
  1353. if (data.callbackId in callbacksCapabilities) {
  1354. var callback = callbacksCapabilities[callbackId];
  1355. delete callbacksCapabilities[callbackId];
  1356. if ('error' in data) {
  1357. callback.reject(data.error);
  1358. } else {
  1359. callback.resolve(data.data);
  1360. }
  1361. } else {
  1362. error('Cannot resolve callback ' + callbackId);
  1363. }
  1364. } else if (data.action in ah) {
  1365. var action = ah[data.action];
  1366. if (data.callbackId) {
  1367. Promise.resolve().then(function () {
  1368. return action[0].call(action[1], data.data);
  1369. }).then(function (result) {
  1370. comObj.postMessage({
  1371. isReply: true,
  1372. callbackId: data.callbackId,
  1373. data: result
  1374. });
  1375. }, function (reason) {
  1376. if (reason instanceof Error) {
  1377. // Serialize error to avoid "DataCloneError"
  1378. reason = reason + '';
  1379. }
  1380. comObj.postMessage({
  1381. isReply: true,
  1382. callbackId: data.callbackId,
  1383. error: reason
  1384. });
  1385. });
  1386. } else {
  1387. action[0].call(action[1], data.data);
  1388. }
  1389. } else {
  1390. error('Unknown action from worker: ' + data.action);
  1391. }
  1392. };
  1393. }
  1394. MessageHandler.prototype = {
  1395. on: function messageHandlerOn(actionName, handler, scope) {
  1396. var ah = this.actionHandler;
  1397. if (ah[actionName]) {
  1398. error('There is already an actionName called "' + actionName + '"');
  1399. }
  1400. ah[actionName] = [handler, scope];
  1401. },
  1402. /**
  1403. * Sends a message to the comObj to invoke the action with the supplied data.
  1404. * @param {String} actionName Action to call.
  1405. * @param {JSON} data JSON data to send.
  1406. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1407. */
  1408. send: function messageHandlerSend(actionName, data, transfers) {
  1409. var message = {
  1410. action: actionName,
  1411. data: data
  1412. };
  1413. this.postMessage(message, transfers);
  1414. },
  1415. /**
  1416. * Sends a message to the comObj to invoke the action with the supplied data.
  1417. * Expects that other side will callback with the response.
  1418. * @param {String} actionName Action to call.
  1419. * @param {JSON} data JSON data to send.
  1420. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1421. * @returns {Promise} Promise to be resolved with response data.
  1422. */
  1423. sendWithPromise:
  1424. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1425. var callbackId = this.callbackIndex++;
  1426. var message = {
  1427. action: actionName,
  1428. data: data,
  1429. callbackId: callbackId
  1430. };
  1431. var capability = createPromiseCapability();
  1432. this.callbacksCapabilities[callbackId] = capability;
  1433. try {
  1434. this.postMessage(message, transfers);
  1435. } catch (e) {
  1436. capability.reject(e);
  1437. }
  1438. return capability.promise;
  1439. },
  1440. /**
  1441. * Sends raw message to the comObj.
  1442. * @private
  1443. * @param message {Object} Raw message.
  1444. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1445. */
  1446. postMessage: function (message, transfers) {
  1447. if (transfers && this.postMessageTransfers) {
  1448. this.comObj.postMessage(message, transfers);
  1449. } else {
  1450. this.comObj.postMessage(message);
  1451. }
  1452. }
  1453. };
  1454. function loadJpegStream(id, imageUrl, objs) {
  1455. var img = new Image();
  1456. img.onload = (function loadJpegStream_onloadClosure() {
  1457. objs.resolve(id, img);
  1458. });
  1459. img.onerror = (function loadJpegStream_onerrorClosure() {
  1460. objs.resolve(id, null);
  1461. warn('Error during JPEG image loading');
  1462. });
  1463. img.src = imageUrl;
  1464. }
  1465. /**
  1466. * The maximum allowed image size in total pixels e.g. width * height. Images
  1467. * above this value will not be drawn. Use -1 for no limit.
  1468. * @var {number}
  1469. */
  1470. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  1471. -1 : PDFJS.maxImageSize);
  1472. /**
  1473. * The url of where the predefined Adobe CMaps are located. Include trailing
  1474. * slash.
  1475. * @var {string}
  1476. */
  1477. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  1478. /**
  1479. * Specifies if CMaps are binary packed.
  1480. * @var {boolean}
  1481. */
  1482. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  1483. /**
  1484. * By default fonts are converted to OpenType fonts and loaded via font face
  1485. * rules. If disabled, the font will be rendered using a built in font renderer
  1486. * that constructs the glyphs with primitive path commands.
  1487. * @var {boolean}
  1488. */
  1489. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  1490. false : PDFJS.disableFontFace);
  1491. /**
  1492. * Path for image resources, mainly for annotation icons. Include trailing
  1493. * slash.
  1494. * @var {string}
  1495. */
  1496. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  1497. '' : PDFJS.imageResourcesPath);
  1498. /**
  1499. * Disable the web worker and run all code on the main thread. This will happen
  1500. * automatically if the browser doesn't support workers or sending typed arrays
  1501. * to workers.
  1502. * @var {boolean}
  1503. */
  1504. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  1505. false : PDFJS.disableWorker);
  1506. /**
  1507. * Path and filename of the worker file. Required when the worker is enabled in
  1508. * development mode. If unspecified in the production build, the worker will be
  1509. * loaded based on the location of the pdf.js file.
  1510. * @var {string}
  1511. */
  1512. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  1513. /**
  1514. * Disable range request loading of PDF files. When enabled and if the server
  1515. * supports partial content requests then the PDF will be fetched in chunks.
  1516. * Enabled (false) by default.
  1517. * @var {boolean}
  1518. */
  1519. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  1520. false : PDFJS.disableRange);
  1521. /**
  1522. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  1523. * in chunks. This default behavior can be disabled.
  1524. * @var {boolean}
  1525. */
  1526. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  1527. false : PDFJS.disableStream);
  1528. /**
  1529. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  1530. * will automatically keep fetching more data even if it isn't needed to display
  1531. * the current page. This default behavior can be disabled.
  1532. *
  1533. * NOTE: It is also necessary to disable streaming, see above,
  1534. * in order for disabling of pre-fetching to work correctly.
  1535. * @var {boolean}
  1536. */
  1537. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  1538. false : PDFJS.disableAutoFetch);
  1539. /**
  1540. * Enables special hooks for debugging PDF.js.
  1541. * @var {boolean}
  1542. */
  1543. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  1544. /**
  1545. * Enables transfer usage in postMessage for ArrayBuffers.
  1546. * @var {boolean}
  1547. */
  1548. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  1549. true : PDFJS.postMessageTransfers);
  1550. /**
  1551. * Disables URL.createObjectURL usage.
  1552. * @var {boolean}
  1553. */
  1554. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  1555. false : PDFJS.disableCreateObjectURL);
  1556. /**
  1557. * Disables WebGL usage.
  1558. * @var {boolean}
  1559. */
  1560. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  1561. true : PDFJS.disableWebGL);
  1562. /**
  1563. * Disables fullscreen support, and by extension Presentation Mode,
  1564. * in browsers which support the fullscreen API.
  1565. * @var {boolean}
  1566. */
  1567. PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?
  1568. false : PDFJS.disableFullscreen);
  1569. /**
  1570. * Enables CSS only zooming.
  1571. * @var {boolean}
  1572. */
  1573. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  1574. false : PDFJS.useOnlyCssZoom);
  1575. /**
  1576. * Controls the logging level.
  1577. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  1578. * - errors
  1579. * - warnings [default]
  1580. * - infos
  1581. * @var {number}
  1582. */
  1583. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  1584. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  1585. /**
  1586. * The maximum supported canvas size in total pixels e.g. width * height.
  1587. * The default value is 4096 * 4096. Use -1 for no limit.
  1588. * @var {number}
  1589. */
  1590. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  1591. 16777216 : PDFJS.maxCanvasPixels);
  1592. /**
  1593. * (Deprecated) Opens external links in a new window if enabled.
  1594. * The default behavior opens external links in the PDF.js window.
  1595. * @var {boolean}
  1596. */
  1597. PDFJS.openExternalLinksInNewWindow = (
  1598. PDFJS.openExternalLinksInNewWindow === undefined ?
  1599. false : PDFJS.openExternalLinksInNewWindow);
  1600. /**
  1601. * Specifies the |target| attribute for external links.
  1602. * The constants from PDFJS.LinkTarget should be used:
  1603. * - NONE [default]
  1604. * - SELF
  1605. * - BLANK
  1606. * - PARENT
  1607. * - TOP
  1608. * @var {number}
  1609. */
  1610. PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?
  1611. PDFJS.LinkTarget.NONE : PDFJS.externalLinkTarget);
  1612. /**
  1613. * Determines if we can eval strings as JS. Primarily used to improve
  1614. * performance for font rendering.
  1615. * @var {boolean}
  1616. */
  1617. PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?
  1618. true : PDFJS.isEvalSupported);
  1619. /**
  1620. * Document initialization / loading parameters object.
  1621. *
  1622. * @typedef {Object} DocumentInitParameters
  1623. * @property {string} url - The URL of the PDF.
  1624. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  1625. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  1626. * use atob() to convert it to a binary string first.
  1627. * @property {Object} httpHeaders - Basic authentication headers.
  1628. * @property {boolean} withCredentials - Indicates whether or not cross-site
  1629. * Access-Control requests should be made using credentials such as cookies
  1630. * or authorization headers. The default is false.
  1631. * @property {string} password - For decrypting password-protected PDFs.
  1632. * @property {TypedArray} initialData - A typed array with the first portion or
  1633. * all of the pdf data. Used by the extension since some data is already
  1634. * loaded before the switch to range requests.
  1635. * @property {number} length - The PDF file length. It's used for progress
  1636. * reports and range requests operations.
  1637. * @property {PDFDataRangeTransport} range
  1638. */
  1639. /**
  1640. * @typedef {Object} PDFDocumentStats
  1641. * @property {Array} streamTypes - Used stream types in the document (an item
  1642. * is set to true if specific stream ID was used in the document).
  1643. * @property {Array} fontTypes - Used font type in the document (an item is set
  1644. * to true if specific font ID was used in the document).
  1645. */
  1646. /**
  1647. * This is the main entry point for loading a PDF and interacting with it.
  1648. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  1649. * is used, which means it must follow the same origin rules that any XHR does
  1650. * e.g. No cross domain requests without CORS.
  1651. *
  1652. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  1653. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  1654. * already populated with data or parameter object.
  1655. *
  1656. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  1657. * if you want to manually serve range requests for data in the PDF.
  1658. *
  1659. * @param {function} passwordCallback (deprecated) It is used to request a
  1660. * password if wrong or no password was provided. The callback receives two
  1661. * parameters: function that needs to be called with new password and reason
  1662. * (see {PasswordResponses}).
  1663. *
  1664. * @param {function} progressCallback (deprecated) It is used to be able to
  1665. * monitor the loading progress of the PDF file (necessary to implement e.g.
  1666. * a loading bar). The callback receives an {Object} with the properties:
  1667. * {number} loaded and {number} total.
  1668. *
  1669. * @return {PDFDocumentLoadingTask}
  1670. */
  1671. PDFJS.getDocument = function getDocument(src,
  1672. pdfDataRangeTransport,
  1673. passwordCallback,
  1674. progressCallback) {
  1675. var task = new PDFDocumentLoadingTask();
  1676. // Support of the obsolete arguments (for compatibility with API v1.0)
  1677. if (pdfDataRangeTransport) {
  1678. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  1679. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  1680. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  1681. pdfDataRangeTransport.length = src.length;
  1682. pdfDataRangeTransport.initialData = src.initialData;
  1683. }
  1684. src = Object.create(src);
  1685. src.range = pdfDataRangeTransport;
  1686. }
  1687. task.onPassword = passwordCallback || null;
  1688. task.onProgress = progressCallback || null;
  1689. var workerInitializedCapability, transport;
  1690. var source;
  1691. if (typeof src === 'string') {
  1692. source = { url: src };
  1693. } else if (isArrayBuffer(src)) {
  1694. source = { data: src };
  1695. } else if (src instanceof PDFDataRangeTransport) {
  1696. source = { range: src };
  1697. } else {
  1698. if (typeof src !== 'object') {
  1699. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  1700. 'string or a parameter object');
  1701. }
  1702. if (!src.url && !src.data && !src.range) {
  1703. error('Invalid parameter object: need either .data, .range or .url');
  1704. }
  1705. source = src;
  1706. }
  1707. var params = {};
  1708. for (var key in source) {
  1709. if (key === 'url' && typeof window !== 'undefined') {
  1710. // The full path is required in the 'url' field.
  1711. params[key] = combineUrl(window.location.href, source[key]);
  1712. continue;
  1713. } else if (key === 'range') {
  1714. continue;
  1715. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  1716. // Converting string or array-like data to Uint8Array.
  1717. var pdfBytes = source[key];
  1718. if (typeof pdfBytes === 'string') {
  1719. params[key] = stringToBytes(pdfBytes);
  1720. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  1721. !isNaN(pdfBytes.length)) {
  1722. params[key] = new Uint8Array(pdfBytes);
  1723. } else if (isArrayBuffer(pdfBytes)) {
  1724. params[key] = new Uint8Array(pdfBytes);
  1725. } else {
  1726. error('Invalid PDF binary data: either typed array, string or ' +
  1727. 'array-like object is expected in the data property.');
  1728. }
  1729. continue;
  1730. }
  1731. params[key] = source[key];
  1732. }
  1733. workerInitializedCapability = createPromiseCapability();
  1734. transport = new WorkerTransport(workerInitializedCapability, source.range);
  1735. workerInitializedCapability.promise.then(function transportInitialized() {
  1736. transport.fetchDocument(task, params);
  1737. });
  1738. return task;
  1739. };
  1740. /**
  1741. * PDF document loading operation.
  1742. * @class
  1743. */
  1744. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  1745. /** @constructs PDFDocumentLoadingTask */
  1746. function PDFDocumentLoadingTask() {
  1747. this._capability = createPromiseCapability();
  1748. /**
  1749. * Callback to request a password if wrong or no password was provided.
  1750. * The callback receives two parameters: function that needs to be called
  1751. * with new password and reason (see {PasswordResponses}).
  1752. */
  1753. this.onPassword = null;
  1754. /**
  1755. * Callback to be able to monitor the loading progress of the PDF file
  1756. * (necessary to implement e.g. a loading bar). The callback receives
  1757. * an {Object} with the properties: {number} loaded and {number} total.
  1758. */
  1759. this.onProgress = null;
  1760. }
  1761. PDFDocumentLoadingTask.prototype =
  1762. /** @lends PDFDocumentLoadingTask.prototype */ {
  1763. /**
  1764. * @return {Promise}
  1765. */
  1766. get promise() {
  1767. return this._capability.promise;
  1768. },
  1769. // TODO add cancel or abort method
  1770. /**
  1771. * Registers callbacks to indicate the document loading completion.
  1772. *
  1773. * @param {function} onFulfilled The callback for the loading completion.
  1774. * @param {function} onRejected The callback for the loading failure.
  1775. * @return {Promise} A promise that is resolved after the onFulfilled or
  1776. * onRejected callback.
  1777. */
  1778. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  1779. return this.promise.then.apply(this.promise, arguments);
  1780. }
  1781. };
  1782. return PDFDocumentLoadingTask;
  1783. })();
  1784. /**
  1785. * Abstract class to support range requests file loading.
  1786. * @class
  1787. */
  1788. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  1789. /**
  1790. * @constructs PDFDataRangeTransport
  1791. * @param {number} length
  1792. * @param {Uint8Array} initialData
  1793. */
  1794. function PDFDataRangeTransport(length, initialData) {
  1795. this.length = length;
  1796. this.initialData = initialData;
  1797. this._rangeListeners = [];
  1798. this._progressListeners = [];
  1799. this._progressiveReadListeners = [];
  1800. this._readyCapability = createPromiseCapability();
  1801. }
  1802. PDFDataRangeTransport.prototype =
  1803. /** @lends PDFDataRangeTransport.prototype */ {
  1804. addRangeListener:
  1805. function PDFDataRangeTransport_addRangeListener(listener) {
  1806. this._rangeListeners.push(listener);
  1807. },
  1808. addProgressListener:
  1809. function PDFDataRangeTransport_addProgressListener(listener) {
  1810. this._progressListeners.push(listener);
  1811. },
  1812. addProgressiveReadListener:
  1813. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  1814. this._progressiveReadListeners.push(listener);
  1815. },
  1816. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  1817. var listeners = this._rangeListeners;
  1818. for (var i = 0, n = listeners.length; i < n; ++i) {
  1819. listeners[i](begin, chunk);
  1820. }
  1821. },
  1822. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  1823. this._readyCapability.promise.then(function () {
  1824. var listeners = this._progressListeners;
  1825. for (var i = 0, n = listeners.length; i < n; ++i) {
  1826. listeners[i](loaded);
  1827. }
  1828. }.bind(this));
  1829. },
  1830. onDataProgressiveRead:
  1831. function PDFDataRangeTransport_onDataProgress(chunk) {
  1832. this._readyCapability.promise.then(function () {
  1833. var listeners = this._progressiveReadListeners;
  1834. for (var i = 0, n = listeners.length; i < n; ++i) {
  1835. listeners[i](chunk);
  1836. }
  1837. }.bind(this));
  1838. },
  1839. transportReady: function PDFDataRangeTransport_transportReady() {
  1840. this._readyCapability.resolve();
  1841. },
  1842. requestDataRange:
  1843. function PDFDataRangeTransport_requestDataRange(begin, end) {
  1844. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  1845. }
  1846. };
  1847. return PDFDataRangeTransport;
  1848. })();
  1849. PDFJS.PDFDataRangeTransport = PDFDataRangeTransport;
  1850. /**
  1851. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  1852. * properties that can be read synchronously.
  1853. * @class
  1854. */
  1855. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  1856. function PDFDocumentProxy(pdfInfo, transport) {
  1857. this.pdfInfo = pdfInfo;
  1858. this.transport = transport;
  1859. }
  1860. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  1861. /**
  1862. * @return {number} Total number of pages the PDF contains.
  1863. */
  1864. get numPages() {
  1865. return this.pdfInfo.numPages;
  1866. },
  1867. /**
  1868. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  1869. * unique.
  1870. */
  1871. get fingerprint() {
  1872. return this.pdfInfo.fingerprint;
  1873. },
  1874. /**
  1875. * @param {number} pageNumber The page number to get. The first page is 1.
  1876. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  1877. * object.
  1878. */
  1879. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  1880. return this.transport.getPage(pageNumber);
  1881. },
  1882. /**
  1883. * @param {{num: number, gen: number}} ref The page reference. Must have
  1884. * the 'num' and 'gen' properties.
  1885. * @return {Promise} A promise that is resolved with the page index that is
  1886. * associated with the reference.
  1887. */
  1888. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  1889. return this.transport.getPageIndex(ref);
  1890. },
  1891. /**
  1892. * @return {Promise} A promise that is resolved with a lookup table for
  1893. * mapping named destinations to reference numbers.
  1894. *
  1895. * This can be slow for large documents: use getDestination instead
  1896. */
  1897. getDestinations: function PDFDocumentProxy_getDestinations() {
  1898. return this.transport.getDestinations();
  1899. },
  1900. /**
  1901. * @param {string} id The named destination to get.
  1902. * @return {Promise} A promise that is resolved with all information
  1903. * of the given named destination.
  1904. */
  1905. getDestination: function PDFDocumentProxy_getDestination(id) {
  1906. return this.transport.getDestination(id);
  1907. },
  1908. /**
  1909. * @return {Promise} A promise that is resolved with a lookup table for
  1910. * mapping named attachments to their content.
  1911. */
  1912. getAttachments: function PDFDocumentProxy_getAttachments() {
  1913. return this.transport.getAttachments();
  1914. },
  1915. /**
  1916. * @return {Promise} A promise that is resolved with an array of all the
  1917. * JavaScript strings in the name tree.
  1918. */
  1919. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  1920. return this.transport.getJavaScript();
  1921. },
  1922. /**
  1923. * @return {Promise} A promise that is resolved with an {Array} that is a
  1924. * tree outline (if it has one) of the PDF. The tree is in the format of:
  1925. * [
  1926. * {
  1927. * title: string,
  1928. * bold: boolean,
  1929. * italic: boolean,
  1930. * color: rgb array,
  1931. * dest: dest obj,
  1932. * items: array of more items like this
  1933. * },
  1934. * ...
  1935. * ].
  1936. */
  1937. getOutline: function PDFDocumentProxy_getOutline() {
  1938. return this.transport.getOutline();
  1939. },
  1940. /**
  1941. * @return {Promise} A promise that is resolved with an {Object} that has
  1942. * info and metadata properties. Info is an {Object} filled with anything
  1943. * available in the information dictionary and similarly metadata is a
  1944. * {Metadata} object with information from the metadata section of the PDF.
  1945. */
  1946. getMetadata: function PDFDocumentProxy_getMetadata() {
  1947. return this.transport.getMetadata();
  1948. },
  1949. /**
  1950. * @return {Promise} A promise that is resolved with a TypedArray that has
  1951. * the raw data from the PDF.
  1952. */
  1953. getData: function PDFDocumentProxy_getData() {
  1954. return this.transport.getData();
  1955. },
  1956. /**
  1957. * @return {Promise} A promise that is resolved when the document's data
  1958. * is loaded. It is resolved with an {Object} that contains the length
  1959. * property that indicates size of the PDF data in bytes.
  1960. */
  1961. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  1962. return this.transport.downloadInfoCapability.promise;
  1963. },
  1964. /**
  1965. * @return {Promise} A promise this is resolved with current stats about
  1966. * document structures (see {@link PDFDocumentStats}).
  1967. */
  1968. getStats: function PDFDocumentProxy_getStats() {
  1969. return this.transport.getStats();
  1970. },
  1971. /**
  1972. * Cleans up resources allocated by the document, e.g. created @font-face.
  1973. */
  1974. cleanup: function PDFDocumentProxy_cleanup() {
  1975. this.transport.startCleanup();
  1976. },
  1977. /**
  1978. * Destroys current document instance and terminates worker.
  1979. */
  1980. destroy: function PDFDocumentProxy_destroy() {
  1981. this.transport.destroy();
  1982. }
  1983. };
  1984. return PDFDocumentProxy;
  1985. })();
  1986. /**
  1987. * Page text content.
  1988. *
  1989. * @typedef {Object} TextContent
  1990. * @property {array} items - array of {@link TextItem}
  1991. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  1992. * name.
  1993. */
  1994. /**
  1995. * Page text content part.
  1996. *
  1997. * @typedef {Object} TextItem
  1998. * @property {string} str - text content.
  1999. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  2000. * @property {array} transform - transformation matrix.
  2001. * @property {number} width - width in device space.
  2002. * @property {number} height - height in device space.
  2003. * @property {string} fontName - font name used by pdf.js for converted font.
  2004. */
  2005. /**
  2006. * Text style.
  2007. *
  2008. * @typedef {Object} TextStyle
  2009. * @property {number} ascent - font ascent.
  2010. * @property {number} descent - font descent.
  2011. * @property {boolean} vertical - text is in vertical mode.
  2012. * @property {string} fontFamily - possible font family
  2013. */
  2014. /**
  2015. * Page render parameters.
  2016. *
  2017. * @typedef {Object} RenderParameters
  2018. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  2019. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  2020. * calling of PDFPage.getViewport method.
  2021. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  2022. * (default value is 'display').
  2023. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  2024. * endLayout and appendImage functions.
  2025. * @property {function} continueCallback - (deprecated) A function that will be
  2026. * called each time the rendering is paused. To continue
  2027. * rendering call the function that is the first argument
  2028. * to the callback.
  2029. */
  2030. /**
  2031. * PDF page operator list.
  2032. *
  2033. * @typedef {Object} PDFOperatorList
  2034. * @property {Array} fnArray - Array containing the operator functions.
  2035. * @property {Array} argsArray - Array containing the arguments of the
  2036. * functions.
  2037. */
  2038. /**
  2039. * Proxy to a PDFPage in the worker thread.
  2040. * @class
  2041. */
  2042. var PDFPageProxy = (function PDFPageProxyClosure() {
  2043. function PDFPageProxy(pageIndex, pageInfo, transport) {
  2044. this.pageIndex = pageIndex;
  2045. this.pageInfo = pageInfo;
  2046. this.transport = transport;
  2047. this.stats = new StatTimer();
  2048. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  2049. this.commonObjs = transport.commonObjs;
  2050. this.objs = new PDFObjects();
  2051. this.cleanupAfterRender = false;
  2052. this.pendingDestroy = false;
  2053. this.intentStates = {};
  2054. }
  2055. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  2056. /**
  2057. * @return {number} Page number of the page. First page is 1.
  2058. */
  2059. get pageNumber() {
  2060. return this.pageIndex + 1;
  2061. },
  2062. /**
  2063. * @return {number} The number of degrees the page is rotated clockwise.
  2064. */
  2065. get rotate() {
  2066. return this.pageInfo.rotate;
  2067. },
  2068. /**
  2069. * @return {Object} The reference that points to this page. It has 'num' and
  2070. * 'gen' properties.
  2071. */
  2072. get ref() {
  2073. return this.pageInfo.ref;
  2074. },
  2075. /**
  2076. * @return {Array} An array of the visible portion of the PDF page in the
  2077. * user space units - [x1, y1, x2, y2].
  2078. */
  2079. get view() {
  2080. return this.pageInfo.view;
  2081. },
  2082. /**
  2083. * @param {number} scale The desired scale of the viewport.
  2084. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  2085. * defaults to the page rotation.
  2086. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  2087. * along with transforms required for rendering.
  2088. */
  2089. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  2090. if (arguments.length < 2) {
  2091. rotate = this.rotate;
  2092. }
  2093. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  2094. },
  2095. /**
  2096. * @return {Promise} A promise that is resolved with an {Array} of the
  2097. * annotation objects.
  2098. */
  2099. getAnnotations: function PDFPageProxy_getAnnotations() {
  2100. if (!this.annotationsPromise) {
  2101. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex);
  2102. }
  2103. return this.annotationsPromise;
  2104. },
  2105. /**
  2106. * Begins the process of rendering a page to the desired context.
  2107. * @param {RenderParameters} params Page render parameters.
  2108. * @return {RenderTask} An object that contains the promise, which
  2109. * is resolved when the page finishes rendering.
  2110. */
  2111. render: function PDFPageProxy_render(params) {
  2112. var stats = this.stats;
  2113. stats.time('Overall');
  2114. // If there was a pending destroy cancel it so no cleanup happens during
  2115. // this call to render.
  2116. this.pendingDestroy = false;
  2117. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  2118. if (!this.intentStates[renderingIntent]) {
  2119. this.intentStates[renderingIntent] = {};
  2120. }
  2121. var intentState = this.intentStates[renderingIntent];
  2122. // If there's no displayReadyCapability yet, then the operatorList
  2123. // was never requested before. Make the request and create the promise.
  2124. if (!intentState.displayReadyCapability) {
  2125. intentState.receivingOperatorList = true;
  2126. intentState.displayReadyCapability = createPromiseCapability();
  2127. intentState.operatorList = {
  2128. fnArray: [],
  2129. argsArray: [],
  2130. lastChunk: false
  2131. };
  2132. this.stats.time('Page Request');
  2133. this.transport.messageHandler.send('RenderPageRequest', {
  2134. pageIndex: this.pageNumber - 1,
  2135. intent: renderingIntent
  2136. });
  2137. }
  2138. var internalRenderTask = new InternalRenderTask(complete, params,
  2139. this.objs,
  2140. this.commonObjs,
  2141. intentState.operatorList,
  2142. this.pageNumber);
  2143. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  2144. if (!intentState.renderTasks) {
  2145. intentState.renderTasks = [];
  2146. }
  2147. intentState.renderTasks.push(internalRenderTask);
  2148. var renderTask = internalRenderTask.task;
  2149. // Obsolete parameter support
  2150. if (params.continueCallback) {
  2151. renderTask.onContinue = params.continueCallback;
  2152. }
  2153. var self = this;
  2154. intentState.displayReadyCapability.promise.then(
  2155. function pageDisplayReadyPromise(transparency) {
  2156. if (self.pendingDestroy) {
  2157. complete();
  2158. return;
  2159. }
  2160. stats.time('Rendering');
  2161. internalRenderTask.initalizeGraphics(transparency);
  2162. internalRenderTask.operatorListChanged();
  2163. },
  2164. function pageDisplayReadPromiseError(reason) {
  2165. complete(reason);
  2166. }
  2167. );
  2168. function complete(error) {
  2169. var i = intentState.renderTasks.indexOf(internalRenderTask);
  2170. if (i >= 0) {
  2171. intentState.renderTasks.splice(i, 1);
  2172. }
  2173. if (self.cleanupAfterRender) {
  2174. self.pendingDestroy = true;
  2175. }
  2176. self._tryDestroy();
  2177. if (error) {
  2178. internalRenderTask.capability.reject(error);
  2179. } else {
  2180. internalRenderTask.capability.resolve();
  2181. }
  2182. stats.timeEnd('Rendering');
  2183. stats.timeEnd('Overall');
  2184. }
  2185. return renderTask;
  2186. },
  2187. /**
  2188. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  2189. * object that represents page's operator list.
  2190. */
  2191. getOperatorList: function PDFPageProxy_getOperatorList() {
  2192. function operatorListChanged() {
  2193. if (intentState.operatorList.lastChunk) {
  2194. intentState.opListReadCapability.resolve(intentState.operatorList);
  2195. }
  2196. }
  2197. var renderingIntent = 'oplist';
  2198. if (!this.intentStates[renderingIntent]) {
  2199. this.intentStates[renderingIntent] = {};
  2200. }
  2201. var intentState = this.intentStates[renderingIntent];
  2202. if (!intentState.opListReadCapability) {
  2203. var opListTask = {};
  2204. opListTask.operatorListChanged = operatorListChanged;
  2205. intentState.receivingOperatorList = true;
  2206. intentState.opListReadCapability = createPromiseCapability();
  2207. intentState.renderTasks = [];
  2208. intentState.renderTasks.push(opListTask);
  2209. intentState.operatorList = {
  2210. fnArray: [],
  2211. argsArray: [],
  2212. lastChunk: false
  2213. };
  2214. this.transport.messageHandler.send('RenderPageRequest', {
  2215. pageIndex: this.pageIndex,
  2216. intent: renderingIntent
  2217. });
  2218. }
  2219. return intentState.opListReadCapability.promise;
  2220. },
  2221. /**
  2222. * @return {Promise} That is resolved a {@link TextContent}
  2223. * object that represent the page text content.
  2224. */
  2225. getTextContent: function PDFPageProxy_getTextContent() {
  2226. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  2227. pageIndex: this.pageNumber - 1
  2228. });
  2229. },
  2230. /**
  2231. * Destroys resources allocated by the page.
  2232. */
  2233. destroy: function PDFPageProxy_destroy() {
  2234. this.pendingDestroy = true;
  2235. this._tryDestroy();
  2236. },
  2237. /**
  2238. * For internal use only. Attempts to clean up if rendering is in a state
  2239. * where that's possible.
  2240. * @ignore
  2241. */
  2242. _tryDestroy: function PDFPageProxy__destroy() {
  2243. if (!this.pendingDestroy ||
  2244. Object.keys(this.intentStates).some(function(intent) {
  2245. var intentState = this.intentStates[intent];
  2246. return (intentState.renderTasks.length !== 0 ||
  2247. intentState.receivingOperatorList);
  2248. }, this)) {
  2249. return;
  2250. }
  2251. Object.keys(this.intentStates).forEach(function(intent) {
  2252. delete this.intentStates[intent];
  2253. }, this);
  2254. this.objs.clear();
  2255. this.annotationsPromise = null;
  2256. this.pendingDestroy = false;
  2257. },
  2258. /**
  2259. * For internal use only.
  2260. * @ignore
  2261. */
  2262. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  2263. intent) {
  2264. var intentState = this.intentStates[intent];
  2265. // TODO Refactor RenderPageRequest to separate rendering
  2266. // and operator list logic
  2267. if (intentState.displayReadyCapability) {
  2268. intentState.displayReadyCapability.resolve(transparency);
  2269. }
  2270. },
  2271. /**
  2272. * For internal use only.
  2273. * @ignore
  2274. */
  2275. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  2276. intent) {
  2277. var intentState = this.intentStates[intent];
  2278. var i, ii;
  2279. // Add the new chunk to the current operator list.
  2280. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2281. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2282. intentState.operatorList.argsArray.push(
  2283. operatorListChunk.argsArray[i]);
  2284. }
  2285. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2286. // Notify all the rendering tasks there are more operators to be consumed.
  2287. for (i = 0; i < intentState.renderTasks.length; i++) {
  2288. intentState.renderTasks[i].operatorListChanged();
  2289. }
  2290. if (operatorListChunk.lastChunk) {
  2291. intentState.receivingOperatorList = false;
  2292. this._tryDestroy();
  2293. }
  2294. }
  2295. };
  2296. return PDFPageProxy;
  2297. })();
  2298. /**
  2299. * For internal use only.
  2300. * @ignore
  2301. */
  2302. var WorkerTransport = (function WorkerTransportClosure() {
  2303. function WorkerTransport(workerInitializedCapability, pdfDataRangeTransport) {
  2304. this.pdfDataRangeTransport = pdfDataRangeTransport;
  2305. this.workerInitializedCapability = workerInitializedCapability;
  2306. this.commonObjs = new PDFObjects();
  2307. this.loadingTask = null;
  2308. this.pageCache = [];
  2309. this.pagePromises = [];
  2310. this.downloadInfoCapability = createPromiseCapability();
  2311. // If worker support isn't disabled explicit and the browser has worker
  2312. // support, create a new web worker and test if it/the browser fullfills
  2313. // all requirements to run parts of pdf.js in a web worker.
  2314. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  2315. // as it arrives on the worker. Chrome added this with version 15.
  2316. // Either workers are disabled, not supported or have thrown an exception.
  2317. // Thus, we fallback to a faked worker.
  2318. this.setupFakeWorker();
  2319. }
  2320. WorkerTransport.prototype = {
  2321. destroy: function WorkerTransport_destroy() {
  2322. this.pageCache = [];
  2323. this.pagePromises = [];
  2324. var self = this;
  2325. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  2326. FontLoader.clear();
  2327. if (self.worker) {
  2328. self.worker.terminate();
  2329. }
  2330. });
  2331. },
  2332. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  2333. globalScope.PDFJS.disableWorker = true;
  2334. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  2335. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  2336. // In the developer build load worker_loader which in turn loads all the
  2337. // other files and resolves the promise. In production only the
  2338. // pdf.worker.js file is needed.
  2339. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  2340. }
  2341. PDFJS.fakeWorkerFilesLoadedCapability.promise.then(function () {
  2342. warn('Setting up fake worker.');
  2343. // If we don't use a worker, just post/sendMessage to the main thread.
  2344. var fakeWorker = {
  2345. postMessage: function WorkerTransport_postMessage(obj) {
  2346. fakeWorker.onmessage({data: obj});
  2347. },
  2348. terminate: function WorkerTransport_terminate() {}
  2349. };
  2350. var messageHandler = new MessageHandler('main', fakeWorker);
  2351. this.setupMessageHandler(messageHandler);
  2352. // If the main thread is our worker, setup the handling for the messages
  2353. // the main thread sends to it self.
  2354. PDFJS.WorkerMessageHandler.setup(messageHandler);
  2355. this.workerInitializedCapability.resolve();
  2356. }.bind(this));
  2357. },
  2358. setupMessageHandler:
  2359. function WorkerTransport_setupMessageHandler(messageHandler) {
  2360. this.messageHandler = messageHandler;
  2361. function updatePassword(password) {
  2362. messageHandler.send('UpdatePassword', password);
  2363. }
  2364. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  2365. if (pdfDataRangeTransport) {
  2366. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  2367. messageHandler.send('OnDataRange', {
  2368. begin: begin,
  2369. chunk: chunk
  2370. });
  2371. });
  2372. pdfDataRangeTransport.addProgressListener(function(loaded) {
  2373. messageHandler.send('OnDataProgress', {
  2374. loaded: loaded
  2375. });
  2376. });
  2377. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  2378. messageHandler.send('OnDataRange', {
  2379. chunk: chunk
  2380. });
  2381. });
  2382. messageHandler.on('RequestDataRange',
  2383. function transportDataRange(data) {
  2384. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  2385. }, this);
  2386. }
  2387. messageHandler.on('GetDoc', function transportDoc(data) {
  2388. var pdfInfo = data.pdfInfo;
  2389. this.numPages = data.pdfInfo.numPages;
  2390. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  2391. this.pdfDocument = pdfDocument;
  2392. this.loadingTask._capability.resolve(pdfDocument);
  2393. }, this);
  2394. messageHandler.on('NeedPassword',
  2395. function transportNeedPassword(exception) {
  2396. var loadingTask = this.loadingTask;
  2397. if (loadingTask.onPassword) {
  2398. return loadingTask.onPassword(updatePassword,
  2399. PasswordResponses.NEED_PASSWORD);
  2400. }
  2401. loadingTask._capability.reject(
  2402. new PasswordException(exception.message, exception.code));
  2403. }, this);
  2404. messageHandler.on('IncorrectPassword',
  2405. function transportIncorrectPassword(exception) {
  2406. var loadingTask = this.loadingTask;
  2407. if (loadingTask.onPassword) {
  2408. return loadingTask.onPassword(updatePassword,
  2409. PasswordResponses.INCORRECT_PASSWORD);
  2410. }
  2411. loadingTask._capability.reject(
  2412. new PasswordException(exception.message, exception.code));
  2413. }, this);
  2414. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  2415. this.loadingTask._capability.reject(
  2416. new InvalidPDFException(exception.message));
  2417. }, this);
  2418. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  2419. this.loadingTask._capability.reject(
  2420. new MissingPDFException(exception.message));
  2421. }, this);
  2422. messageHandler.on('UnexpectedResponse',
  2423. function transportUnexpectedResponse(exception) {
  2424. this.loadingTask._capability.reject(
  2425. new UnexpectedResponseException(exception.message, exception.status));
  2426. }, this);
  2427. messageHandler.on('UnknownError',
  2428. function transportUnknownError(exception) {
  2429. this.loadingTask._capability.reject(
  2430. new UnknownErrorException(exception.message, exception.details));
  2431. }, this);
  2432. messageHandler.on('DataLoaded', function transportPage(data) {
  2433. this.downloadInfoCapability.resolve(data);
  2434. }, this);
  2435. messageHandler.on('PDFManagerReady', function transportPage(data) {
  2436. if (this.pdfDataRangeTransport) {
  2437. this.pdfDataRangeTransport.transportReady();
  2438. }
  2439. }, this);
  2440. messageHandler.on('StartRenderPage', function transportRender(data) {
  2441. var page = this.pageCache[data.pageIndex];
  2442. page.stats.timeEnd('Page Request');
  2443. page._startRenderPage(data.transparency, data.intent);
  2444. }, this);
  2445. messageHandler.on('RenderPageChunk', function transportRender(data) {
  2446. var page = this.pageCache[data.pageIndex];
  2447. page._renderPageChunk(data.operatorList, data.intent);
  2448. }, this);
  2449. messageHandler.on('commonobj', function transportObj(data) {
  2450. var id = data[0];
  2451. var type = data[1];
  2452. if (this.commonObjs.hasData(id)) {
  2453. return;
  2454. }
  2455. switch (type) {
  2456. case 'Font':
  2457. var exportedData = data[2];
  2458. var font;
  2459. if ('error' in exportedData) {
  2460. var error = exportedData.error;
  2461. warn('Error during font loading: ' + error);
  2462. this.commonObjs.resolve(id, error);
  2463. break;
  2464. } else {
  2465. font = new FontFaceObject(exportedData);
  2466. }
  2467. FontLoader.bind(
  2468. [font],
  2469. function fontReady(fontObjs) {
  2470. this.commonObjs.resolve(id, font);
  2471. }.bind(this)
  2472. );
  2473. break;
  2474. case 'FontPath':
  2475. this.commonObjs.resolve(id, data[2]);
  2476. break;
  2477. default:
  2478. error('Got unknown common object type ' + type);
  2479. }
  2480. }, this);
  2481. messageHandler.on('obj', function transportObj(data) {
  2482. var id = data[0];
  2483. var pageIndex = data[1];
  2484. var type = data[2];
  2485. var pageProxy = this.pageCache[pageIndex];
  2486. var imageData;
  2487. if (pageProxy.objs.hasData(id)) {
  2488. return;
  2489. }
  2490. switch (type) {
  2491. case 'JpegStream':
  2492. imageData = data[3];
  2493. loadJpegStream(id, imageData, pageProxy.objs);
  2494. break;
  2495. case 'Image':
  2496. imageData = data[3];
  2497. pageProxy.objs.resolve(id, imageData);
  2498. // heuristics that will allow not to store large data
  2499. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2500. if (imageData && 'data' in imageData &&
  2501. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  2502. pageProxy.cleanupAfterRender = true;
  2503. }
  2504. break;
  2505. default:
  2506. error('Got unknown object type ' + type);
  2507. }
  2508. }, this);
  2509. messageHandler.on('DocProgress', function transportDocProgress(data) {
  2510. var loadingTask = this.loadingTask;
  2511. if (loadingTask.onProgress) {
  2512. loadingTask.onProgress({
  2513. loaded: data.loaded,
  2514. total: data.total
  2515. });
  2516. }
  2517. }, this);
  2518. messageHandler.on('PageError', function transportError(data) {
  2519. var page = this.pageCache[data.pageNum - 1];
  2520. var intentState = page.intentStates[data.intent];
  2521. if (intentState.displayReadyCapability) {
  2522. intentState.displayReadyCapability.reject(data.error);
  2523. } else {
  2524. error(data.error);
  2525. }
  2526. }, this);
  2527. messageHandler.on('JpegDecode', function(data) {
  2528. var imageUrl = data[0];
  2529. var components = data[1];
  2530. if (components !== 3 && components !== 1) {
  2531. return Promise.reject(
  2532. new Error('Only 3 components or 1 component can be returned'));
  2533. }
  2534. return new Promise(function (resolve, reject) {
  2535. var img = new Image();
  2536. img.onload = function () {
  2537. var width = img.width;
  2538. var height = img.height;
  2539. var size = width * height;
  2540. var rgbaLength = size * 4;
  2541. var buf = new Uint8Array(size * components);
  2542. var tmpCanvas = createScratchCanvas(width, height);
  2543. var tmpCtx = tmpCanvas.getContext('2d');
  2544. tmpCtx.drawImage(img, 0, 0);
  2545. var data = tmpCtx.getImageData(0, 0, width, height).data;
  2546. var i, j;
  2547. if (components === 3) {
  2548. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  2549. buf[j] = data[i];
  2550. buf[j + 1] = data[i + 1];
  2551. buf[j + 2] = data[i + 2];
  2552. }
  2553. } else if (components === 1) {
  2554. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  2555. buf[j] = data[i];
  2556. }
  2557. }
  2558. resolve({ data: buf, width: width, height: height});
  2559. };
  2560. img.onerror = function () {
  2561. reject(new Error('JpegDecode failed to load image'));
  2562. };
  2563. img.src = imageUrl;
  2564. });
  2565. });
  2566. },
  2567. fetchDocument: function WorkerTransport_fetchDocument(loadingTask, source) {
  2568. this.loadingTask = loadingTask;
  2569. source.disableAutoFetch = PDFJS.disableAutoFetch;
  2570. source.disableStream = PDFJS.disableStream;
  2571. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  2572. if (this.pdfDataRangeTransport) {
  2573. source.length = this.pdfDataRangeTransport.length;
  2574. source.initialData = this.pdfDataRangeTransport.initialData;
  2575. }
  2576. this.messageHandler.send('GetDocRequest', {
  2577. source: source,
  2578. disableRange: PDFJS.disableRange,
  2579. maxImageSize: PDFJS.maxImageSize,
  2580. cMapUrl: PDFJS.cMapUrl,
  2581. cMapPacked: PDFJS.cMapPacked,
  2582. disableFontFace: PDFJS.disableFontFace,
  2583. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  2584. verbosity: PDFJS.verbosity
  2585. });
  2586. },
  2587. getData: function WorkerTransport_getData() {
  2588. return this.messageHandler.sendWithPromise('GetData', null);
  2589. },
  2590. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  2591. if (pageNumber <= 0 || pageNumber > this.numPages ||
  2592. (pageNumber|0) !== pageNumber) {
  2593. return Promise.reject(new Error('Invalid page request'));
  2594. }
  2595. var pageIndex = pageNumber - 1;
  2596. if (pageIndex in this.pagePromises) {
  2597. return this.pagePromises[pageIndex];
  2598. }
  2599. var promise = this.messageHandler.sendWithPromise('GetPage', {
  2600. pageIndex: pageIndex
  2601. }).then(function (pageInfo) {
  2602. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  2603. this.pageCache[pageIndex] = page;
  2604. return page;
  2605. }.bind(this));
  2606. this.pagePromises[pageIndex] = promise;
  2607. return promise;
  2608. },
  2609. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  2610. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  2611. },
  2612. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  2613. return this.messageHandler.sendWithPromise('GetAnnotations',
  2614. { pageIndex: pageIndex });
  2615. },
  2616. getDestinations: function WorkerTransport_getDestinations() {
  2617. return this.messageHandler.sendWithPromise('GetDestinations', null);
  2618. },
  2619. getDestination: function WorkerTransport_getDestination(id) {
  2620. return this.messageHandler.sendWithPromise('GetDestination', { id: id } );
  2621. },
  2622. getAttachments: function WorkerTransport_getAttachments() {
  2623. return this.messageHandler.sendWithPromise('GetAttachments', null);
  2624. },
  2625. getJavaScript: function WorkerTransport_getJavaScript() {
  2626. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  2627. },
  2628. getOutline: function WorkerTransport_getOutline() {
  2629. return this.messageHandler.sendWithPromise('GetOutline', null);
  2630. },
  2631. getMetadata: function WorkerTransport_getMetadata() {
  2632. return this.messageHandler.sendWithPromise('GetMetadata', null).
  2633. then(function transportMetadata(results) {
  2634. return {
  2635. info: results[0],
  2636. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  2637. };
  2638. });
  2639. },
  2640. getStats: function WorkerTransport_getStats() {
  2641. return this.messageHandler.sendWithPromise('GetStats', null);
  2642. },
  2643. startCleanup: function WorkerTransport_startCleanup() {
  2644. this.messageHandler.sendWithPromise('Cleanup', null).
  2645. then(function endCleanup() {
  2646. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  2647. var page = this.pageCache[i];
  2648. if (page) {
  2649. page.destroy();
  2650. }
  2651. }
  2652. this.commonObjs.clear();
  2653. FontLoader.clear();
  2654. }.bind(this));
  2655. }
  2656. };
  2657. return WorkerTransport;
  2658. })();
  2659. /**
  2660. * A PDF document and page is built of many objects. E.g. there are objects
  2661. * for fonts, images, rendering code and such. These objects might get processed
  2662. * inside of a worker. The `PDFObjects` implements some basic functions to
  2663. * manage these objects.
  2664. * @ignore
  2665. */
  2666. var PDFObjects = (function PDFObjectsClosure() {
  2667. function PDFObjects() {
  2668. this.objs = {};
  2669. }
  2670. PDFObjects.prototype = {
  2671. /**
  2672. * Internal function.
  2673. * Ensures there is an object defined for `objId`.
  2674. */
  2675. ensureObj: function PDFObjects_ensureObj(objId) {
  2676. if (this.objs[objId]) {
  2677. return this.objs[objId];
  2678. }
  2679. var obj = {
  2680. capability: createPromiseCapability(),
  2681. data: null,
  2682. resolved: false
  2683. };
  2684. this.objs[objId] = obj;
  2685. return obj;
  2686. },
  2687. /**
  2688. * If called *without* callback, this returns the data of `objId` but the
  2689. * object needs to be resolved. If it isn't, this function throws.
  2690. *
  2691. * If called *with* a callback, the callback is called with the data of the
  2692. * object once the object is resolved. That means, if you call this
  2693. * function and the object is already resolved, the callback gets called
  2694. * right away.
  2695. */
  2696. get: function PDFObjects_get(objId, callback) {
  2697. // If there is a callback, then the get can be async and the object is
  2698. // not required to be resolved right now
  2699. if (callback) {
  2700. this.ensureObj(objId).capability.promise.then(callback);
  2701. return null;
  2702. }
  2703. // If there isn't a callback, the user expects to get the resolved data
  2704. // directly.
  2705. var obj = this.objs[objId];
  2706. // If there isn't an object yet or the object isn't resolved, then the
  2707. // data isn't ready yet!
  2708. if (!obj || !obj.resolved) {
  2709. error('Requesting object that isn\'t resolved yet ' + objId);
  2710. }
  2711. return obj.data;
  2712. },
  2713. /**
  2714. * Resolves the object `objId` with optional `data`.
  2715. */
  2716. resolve: function PDFObjects_resolve(objId, data) {
  2717. var obj = this.ensureObj(objId);
  2718. obj.resolved = true;
  2719. obj.data = data;
  2720. obj.capability.resolve(data);
  2721. },
  2722. isResolved: function PDFObjects_isResolved(objId) {
  2723. var objs = this.objs;
  2724. if (!objs[objId]) {
  2725. return false;
  2726. } else {
  2727. return objs[objId].resolved;
  2728. }
  2729. },
  2730. hasData: function PDFObjects_hasData(objId) {
  2731. return this.isResolved(objId);
  2732. },
  2733. /**
  2734. * Returns the data of `objId` if object exists, null otherwise.
  2735. */
  2736. getData: function PDFObjects_getData(objId) {
  2737. var objs = this.objs;
  2738. if (!objs[objId] || !objs[objId].resolved) {
  2739. return null;
  2740. } else {
  2741. return objs[objId].data;
  2742. }
  2743. },
  2744. clear: function PDFObjects_clear() {
  2745. this.objs = {};
  2746. }
  2747. };
  2748. return PDFObjects;
  2749. })();
  2750. /**
  2751. * Allows controlling of the rendering tasks.
  2752. * @class
  2753. */
  2754. var RenderTask = (function RenderTaskClosure() {
  2755. function RenderTask(internalRenderTask) {
  2756. this._internalRenderTask = internalRenderTask;
  2757. /**
  2758. * Callback for incremental rendering -- a function that will be called
  2759. * each time the rendering is paused. To continue rendering call the
  2760. * function that is the first argument to the callback.
  2761. * @type {function}
  2762. */
  2763. this.onContinue = null;
  2764. }
  2765. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  2766. /**
  2767. * Promise for rendering task completion.
  2768. * @return {Promise}
  2769. */
  2770. get promise() {
  2771. return this._internalRenderTask.capability.promise;
  2772. },
  2773. /**
  2774. * Cancels the rendering task. If the task is currently rendering it will
  2775. * not be cancelled until graphics pauses with a timeout. The promise that
  2776. * this object extends will resolved when cancelled.
  2777. */
  2778. cancel: function RenderTask_cancel() {
  2779. this._internalRenderTask.cancel();
  2780. },
  2781. /**
  2782. * Registers callbacks to indicate the rendering task completion.
  2783. *
  2784. * @param {function} onFulfilled The callback for the rendering completion.
  2785. * @param {function} onRejected The callback for the rendering failure.
  2786. * @return {Promise} A promise that is resolved after the onFulfilled or
  2787. * onRejected callback.
  2788. */
  2789. then: function RenderTask_then(onFulfilled, onRejected) {
  2790. return this.promise.then.apply(this.promise, arguments);
  2791. }
  2792. };
  2793. return RenderTask;
  2794. })();
  2795. /**
  2796. * For internal use only.
  2797. * @ignore
  2798. */
  2799. var InternalRenderTask = (function InternalRenderTaskClosure() {
  2800. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  2801. pageNumber) {
  2802. this.callback = callback;
  2803. this.params = params;
  2804. this.objs = objs;
  2805. this.commonObjs = commonObjs;
  2806. this.operatorListIdx = null;
  2807. this.operatorList = operatorList;
  2808. this.pageNumber = pageNumber;
  2809. this.running = false;
  2810. this.graphicsReadyCallback = null;
  2811. this.graphicsReady = false;
  2812. this.useRequestAnimationFrame = false;
  2813. this.cancelled = false;
  2814. this.capability = createPromiseCapability();
  2815. this.task = new RenderTask(this);
  2816. // caching this-bound methods
  2817. this._continueBound = this._continue.bind(this);
  2818. this._scheduleNextBound = this._scheduleNext.bind(this);
  2819. this._nextBound = this._next.bind(this);
  2820. }
  2821. InternalRenderTask.prototype = {
  2822. initalizeGraphics:
  2823. function InternalRenderTask_initalizeGraphics(transparency) {
  2824. if (this.cancelled) {
  2825. return;
  2826. }
  2827. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  2828. globalScope.StepperManager.enabled) {
  2829. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  2830. this.stepper.init(this.operatorList);
  2831. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2832. }
  2833. var params = this.params;
  2834. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  2835. this.objs, params.imageLayer);
  2836. this.gfx.beginDrawing(params.viewport, transparency);
  2837. this.operatorListIdx = 0;
  2838. this.graphicsReady = true;
  2839. if (this.graphicsReadyCallback) {
  2840. this.graphicsReadyCallback();
  2841. }
  2842. },
  2843. cancel: function InternalRenderTask_cancel() {
  2844. this.running = false;
  2845. this.cancelled = true;
  2846. this.callback('cancelled');
  2847. },
  2848. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  2849. if (!this.graphicsReady) {
  2850. if (!this.graphicsReadyCallback) {
  2851. this.graphicsReadyCallback = this._continueBound;
  2852. }
  2853. return;
  2854. }
  2855. if (this.stepper) {
  2856. this.stepper.updateOperatorList(this.operatorList);
  2857. }
  2858. if (this.running) {
  2859. return;
  2860. }
  2861. this._continue();
  2862. },
  2863. _continue: function InternalRenderTask__continue() {
  2864. this.running = true;
  2865. if (this.cancelled) {
  2866. return;
  2867. }
  2868. if (this.task.onContinue) {
  2869. this.task.onContinue.call(this.task, this._scheduleNextBound);
  2870. } else {
  2871. this._scheduleNext();
  2872. }
  2873. },
  2874. _scheduleNext: function InternalRenderTask__scheduleNext() {
  2875. if (this.useRequestAnimationFrame) {
  2876. window.requestAnimationFrame(this._nextBound);
  2877. } else {
  2878. Promise.resolve(undefined).then(this._nextBound);
  2879. }
  2880. },
  2881. _next: function InternalRenderTask__next() {
  2882. if (this.cancelled) {
  2883. return;
  2884. }
  2885. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  2886. this.operatorListIdx,
  2887. this._continueBound,
  2888. this.stepper);
  2889. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2890. this.running = false;
  2891. if (this.operatorList.lastChunk) {
  2892. this.gfx.endDrawing();
  2893. this.callback();
  2894. }
  2895. }
  2896. }
  2897. };
  2898. return InternalRenderTask;
  2899. })();
  2900. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  2901. function fixMetadata(meta) {
  2902. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2903. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2904. function(code, d1, d2, d3) {
  2905. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2906. });
  2907. var chars = '';
  2908. for (var i = 0; i < bytes.length; i += 2) {
  2909. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2910. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2911. code !== 38 && false ? String.fromCharCode(code) :
  2912. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2913. }
  2914. return '>' + chars;
  2915. });
  2916. }
  2917. function Metadata(meta) {
  2918. if (typeof meta === 'string') {
  2919. // Ghostscript produces invalid metadata
  2920. meta = fixMetadata(meta);
  2921. var parser = new DOMParser();
  2922. meta = parser.parseFromString(meta, 'application/xml');
  2923. } else if (!(meta instanceof Document)) {
  2924. error('Metadata: Invalid metadata object');
  2925. }
  2926. this.metaDocument = meta;
  2927. this.metadata = {};
  2928. this.parse();
  2929. }
  2930. Metadata.prototype = {
  2931. parse: function Metadata_parse() {
  2932. var doc = this.metaDocument;
  2933. var rdf = doc.documentElement;
  2934. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2935. rdf = rdf.firstChild;
  2936. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2937. rdf = rdf.nextSibling;
  2938. }
  2939. }
  2940. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2941. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2942. return;
  2943. }
  2944. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2945. for (i = 0, length = children.length; i < length; i++) {
  2946. desc = children[i];
  2947. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2948. continue;
  2949. }
  2950. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2951. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2952. entry = desc.childNodes[ii];
  2953. name = entry.nodeName.toLowerCase();
  2954. this.metadata[name] = entry.textContent.trim();
  2955. }
  2956. }
  2957. }
  2958. },
  2959. get: function Metadata_get(name) {
  2960. return this.metadata[name] || null;
  2961. },
  2962. has: function Metadata_has(name) {
  2963. return typeof this.metadata[name] !== 'undefined';
  2964. }
  2965. };
  2966. return Metadata;
  2967. })();
  2968. // <canvas> contexts store most of the state we need natively.
  2969. // However, PDF needs a bit more state, which we store here.
  2970. // Minimal font size that would be used during canvas fillText operations.
  2971. var MIN_FONT_SIZE = 16;
  2972. // Maximum font size that would be used during canvas fillText operations.
  2973. var MAX_FONT_SIZE = 100;
  2974. var MAX_GROUP_SIZE = 4096;
  2975. // Heuristic value used when enforcing minimum line widths.
  2976. var MIN_WIDTH_FACTOR = 0.65;
  2977. var COMPILE_TYPE3_GLYPHS = true;
  2978. var MAX_SIZE_TO_COMPILE = 1000;
  2979. var FULL_CHUNK_HEIGHT = 16;
  2980. function createScratchCanvas(width, height) {
  2981. var canvas = document.createElement('canvas');
  2982. canvas.width = width;
  2983. canvas.height = height;
  2984. return canvas;
  2985. }
  2986. function addContextCurrentTransform(ctx) {
  2987. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  2988. if (!ctx.mozCurrentTransform) {
  2989. ctx._originalSave = ctx.save;
  2990. ctx._originalRestore = ctx.restore;
  2991. ctx._originalRotate = ctx.rotate;
  2992. ctx._originalScale = ctx.scale;
  2993. ctx._originalTranslate = ctx.translate;
  2994. ctx._originalTransform = ctx.transform;
  2995. ctx._originalSetTransform = ctx.setTransform;
  2996. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  2997. ctx._transformStack = [];
  2998. Object.defineProperty(ctx, 'mozCurrentTransform', {
  2999. get: function getCurrentTransform() {
  3000. return this._transformMatrix;
  3001. }
  3002. });
  3003. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  3004. get: function getCurrentTransformInverse() {
  3005. // Calculation done using WolframAlpha:
  3006. // http://www.wolframalpha.com/input/?
  3007. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  3008. var m = this._transformMatrix;
  3009. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  3010. var ad_bc = a * d - b * c;
  3011. var bc_ad = b * c - a * d;
  3012. return [
  3013. d / ad_bc,
  3014. b / bc_ad,
  3015. c / bc_ad,
  3016. a / ad_bc,
  3017. (d * e - c * f) / bc_ad,
  3018. (b * e - a * f) / ad_bc
  3019. ];
  3020. }
  3021. });
  3022. ctx.save = function ctxSave() {
  3023. var old = this._transformMatrix;
  3024. this._transformStack.push(old);
  3025. this._transformMatrix = old.slice(0, 6);
  3026. this._originalSave();
  3027. };
  3028. ctx.restore = function ctxRestore() {
  3029. var prev = this._transformStack.pop();
  3030. if (prev) {
  3031. this._transformMatrix = prev;
  3032. this._originalRestore();
  3033. }
  3034. };
  3035. ctx.translate = function ctxTranslate(x, y) {
  3036. var m = this._transformMatrix;
  3037. m[4] = m[0] * x + m[2] * y + m[4];
  3038. m[5] = m[1] * x + m[3] * y + m[5];
  3039. this._originalTranslate(x, y);
  3040. };
  3041. ctx.scale = function ctxScale(x, y) {
  3042. var m = this._transformMatrix;
  3043. m[0] = m[0] * x;
  3044. m[1] = m[1] * x;
  3045. m[2] = m[2] * y;
  3046. m[3] = m[3] * y;
  3047. this._originalScale(x, y);
  3048. };
  3049. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  3050. var m = this._transformMatrix;
  3051. this._transformMatrix = [
  3052. m[0] * a + m[2] * b,
  3053. m[1] * a + m[3] * b,
  3054. m[0] * c + m[2] * d,
  3055. m[1] * c + m[3] * d,
  3056. m[0] * e + m[2] * f + m[4],
  3057. m[1] * e + m[3] * f + m[5]
  3058. ];
  3059. ctx._originalTransform(a, b, c, d, e, f);
  3060. };
  3061. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  3062. this._transformMatrix = [a, b, c, d, e, f];
  3063. ctx._originalSetTransform(a, b, c, d, e, f);
  3064. };
  3065. ctx.rotate = function ctxRotate(angle) {
  3066. var cosValue = Math.cos(angle);
  3067. var sinValue = Math.sin(angle);
  3068. var m = this._transformMatrix;
  3069. this._transformMatrix = [
  3070. m[0] * cosValue + m[2] * sinValue,
  3071. m[1] * cosValue + m[3] * sinValue,
  3072. m[0] * (-sinValue) + m[2] * cosValue,
  3073. m[1] * (-sinValue) + m[3] * cosValue,
  3074. m[4],
  3075. m[5]
  3076. ];
  3077. this._originalRotate(angle);
  3078. };
  3079. }
  3080. }
  3081. var CachedCanvases = (function CachedCanvasesClosure() {
  3082. var cache = {};
  3083. return {
  3084. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  3085. trackTransform) {
  3086. var canvasEntry;
  3087. if (cache[id] !== undefined) {
  3088. canvasEntry = cache[id];
  3089. canvasEntry.canvas.width = width;
  3090. canvasEntry.canvas.height = height;
  3091. // reset canvas transform for emulated mozCurrentTransform, if needed
  3092. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  3093. } else {
  3094. var canvas = createScratchCanvas(width, height);
  3095. var ctx = canvas.getContext('2d');
  3096. if (trackTransform) {
  3097. addContextCurrentTransform(ctx);
  3098. }
  3099. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  3100. }
  3101. return canvasEntry;
  3102. },
  3103. clear: function () {
  3104. for (var id in cache) {
  3105. var canvasEntry = cache[id];
  3106. // Zeroing the width and height causes Firefox to release graphics
  3107. // resources immediately, which can greatly reduce memory consumption.
  3108. canvasEntry.canvas.width = 0;
  3109. canvasEntry.canvas.height = 0;
  3110. delete cache[id];
  3111. }
  3112. }
  3113. };
  3114. })();
  3115. function compileType3Glyph(imgData) {
  3116. var POINT_TO_PROCESS_LIMIT = 1000;
  3117. var width = imgData.width, height = imgData.height;
  3118. var i, j, j0, width1 = width + 1;
  3119. var points = new Uint8Array(width1 * (height + 1));
  3120. var POINT_TYPES =
  3121. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  3122. // decodes bit-packed mask data
  3123. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  3124. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  3125. for (i = 0, ii = data0.length; i < ii; i++) {
  3126. var mask = 128, elem = data0[i];
  3127. while (mask > 0) {
  3128. data[pos++] = (elem & mask) ? 0 : 255;
  3129. mask >>= 1;
  3130. }
  3131. }
  3132. // finding iteresting points: every point is located between mask pixels,
  3133. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  3134. // will have flags assigned based on neighboring mask pixels:
  3135. // 4 | 8
  3136. // --P--
  3137. // 2 | 1
  3138. // We are interested only in points with the flags:
  3139. // - outside corners: 1, 2, 4, 8;
  3140. // - inside corners: 7, 11, 13, 14;
  3141. // - and, intersections: 5, 10.
  3142. var count = 0;
  3143. pos = 0;
  3144. if (data[pos] !== 0) {
  3145. points[0] = 1;
  3146. ++count;
  3147. }
  3148. for (j = 1; j < width; j++) {
  3149. if (data[pos] !== data[pos + 1]) {
  3150. points[j] = data[pos] ? 2 : 1;
  3151. ++count;
  3152. }
  3153. pos++;
  3154. }
  3155. if (data[pos] !== 0) {
  3156. points[j] = 2;
  3157. ++count;
  3158. }
  3159. for (i = 1; i < height; i++) {
  3160. pos = i * lineSize;
  3161. j0 = i * width1;
  3162. if (data[pos - lineSize] !== data[pos]) {
  3163. points[j0] = data[pos] ? 1 : 8;
  3164. ++count;
  3165. }
  3166. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  3167. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  3168. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  3169. for (j = 1; j < width; j++) {
  3170. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  3171. (data[pos - lineSize + 1] ? 8 : 0);
  3172. if (POINT_TYPES[sum]) {
  3173. points[j0 + j] = POINT_TYPES[sum];
  3174. ++count;
  3175. }
  3176. pos++;
  3177. }
  3178. if (data[pos - lineSize] !== data[pos]) {
  3179. points[j0 + j] = data[pos] ? 2 : 4;
  3180. ++count;
  3181. }
  3182. if (count > POINT_TO_PROCESS_LIMIT) {
  3183. return null;
  3184. }
  3185. }
  3186. pos = lineSize * (height - 1);
  3187. j0 = i * width1;
  3188. if (data[pos] !== 0) {
  3189. points[j0] = 8;
  3190. ++count;
  3191. }
  3192. for (j = 1; j < width; j++) {
  3193. if (data[pos] !== data[pos + 1]) {
  3194. points[j0 + j] = data[pos] ? 4 : 8;
  3195. ++count;
  3196. }
  3197. pos++;
  3198. }
  3199. if (data[pos] !== 0) {
  3200. points[j0 + j] = 4;
  3201. ++count;
  3202. }
  3203. if (count > POINT_TO_PROCESS_LIMIT) {
  3204. return null;
  3205. }
  3206. // building outlines
  3207. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  3208. var outlines = [];
  3209. for (i = 0; count && i <= height; i++) {
  3210. var p = i * width1;
  3211. var end = p + width;
  3212. while (p < end && !points[p]) {
  3213. p++;
  3214. }
  3215. if (p === end) {
  3216. continue;
  3217. }
  3218. var coords = [p % width1, i];
  3219. var type = points[p], p0 = p, pp;
  3220. do {
  3221. var step = steps[type];
  3222. do {
  3223. p += step;
  3224. } while (!points[p]);
  3225. pp = points[p];
  3226. if (pp !== 5 && pp !== 10) {
  3227. // set new direction
  3228. type = pp;
  3229. // delete mark
  3230. points[p] = 0;
  3231. } else { // type is 5 or 10, ie, a crossing
  3232. // set new direction
  3233. type = pp & ((0x33 * type) >> 4);
  3234. // set new type for "future hit"
  3235. points[p] &= (type >> 2 | type << 2);
  3236. }
  3237. coords.push(p % width1);
  3238. coords.push((p / width1) | 0);
  3239. --count;
  3240. } while (p0 !== p);
  3241. outlines.push(coords);
  3242. --i;
  3243. }
  3244. var drawOutline = function(c) {
  3245. c.save();
  3246. // the path shall be painted in [0..1]x[0..1] space
  3247. c.scale(1 / width, -1 / height);
  3248. c.translate(0, -height);
  3249. c.beginPath();
  3250. for (var i = 0, ii = outlines.length; i < ii; i++) {
  3251. var o = outlines[i];
  3252. c.moveTo(o[0], o[1]);
  3253. for (var j = 2, jj = o.length; j < jj; j += 2) {
  3254. c.lineTo(o[j], o[j+1]);
  3255. }
  3256. }
  3257. c.fill();
  3258. c.beginPath();
  3259. c.restore();
  3260. };
  3261. return drawOutline;
  3262. }
  3263. var CanvasExtraState = (function CanvasExtraStateClosure() {
  3264. function CanvasExtraState(old) {
  3265. // Are soft masks and alpha values shapes or opacities?
  3266. this.alphaIsShape = false;
  3267. this.fontSize = 0;
  3268. this.fontSizeScale = 1;
  3269. this.textMatrix = IDENTITY_MATRIX;
  3270. this.textMatrixScale = 1;
  3271. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3272. this.leading = 0;
  3273. // Current point (in user coordinates)
  3274. this.x = 0;
  3275. this.y = 0;
  3276. // Start of text line (in text coordinates)
  3277. this.lineX = 0;
  3278. this.lineY = 0;
  3279. // Character and word spacing
  3280. this.charSpacing = 0;
  3281. this.wordSpacing = 0;
  3282. this.textHScale = 1;
  3283. this.textRenderingMode = TextRenderingMode.FILL;
  3284. this.textRise = 0;
  3285. // Default fore and background colors
  3286. this.fillColor = '#000000';
  3287. this.strokeColor = '#000000';
  3288. this.patternFill = false;
  3289. // Note: fill alpha applies to all non-stroking operations
  3290. this.fillAlpha = 1;
  3291. this.strokeAlpha = 1;
  3292. this.lineWidth = 1;
  3293. this.activeSMask = null; // nonclonable field (see the save method below)
  3294. this.old = old;
  3295. }
  3296. CanvasExtraState.prototype = {
  3297. clone: function CanvasExtraState_clone() {
  3298. return Object.create(this);
  3299. },
  3300. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  3301. this.x = x;
  3302. this.y = y;
  3303. }
  3304. };
  3305. return CanvasExtraState;
  3306. })();
  3307. var CanvasGraphics = (function CanvasGraphicsClosure() {
  3308. // Defines the time the executeOperatorList is going to be executing
  3309. // before it stops and shedules a continue of execution.
  3310. var EXECUTION_TIME = 15;
  3311. // Defines the number of steps before checking the execution time
  3312. var EXECUTION_STEPS = 10;
  3313. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  3314. this.ctx = canvasCtx;
  3315. this.current = new CanvasExtraState();
  3316. this.stateStack = [];
  3317. this.pendingClip = null;
  3318. this.pendingEOFill = false;
  3319. this.res = null;
  3320. this.xobjs = null;
  3321. this.commonObjs = commonObjs;
  3322. this.objs = objs;
  3323. this.imageLayer = imageLayer;
  3324. this.groupStack = [];
  3325. this.processingType3 = null;
  3326. // Patterns are painted relative to the initial page/form transform, see pdf
  3327. // spec 8.7.2 NOTE 1.
  3328. this.baseTransform = null;
  3329. this.baseTransformStack = [];
  3330. this.groupLevel = 0;
  3331. this.smaskStack = [];
  3332. this.smaskCounter = 0;
  3333. this.tempSMask = null;
  3334. if (canvasCtx) {
  3335. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  3336. // the transformation must already be set in canvasCtx._transformMatrix.
  3337. addContextCurrentTransform(canvasCtx);
  3338. }
  3339. this.cachedGetSinglePixelWidth = null;
  3340. }
  3341. function putBinaryImageData(ctx, imgData) {
  3342. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  3343. ctx.putImageData(imgData, 0, 0);
  3344. return;
  3345. }
  3346. // Put the image data to the canvas in chunks, rather than putting the
  3347. // whole image at once. This saves JS memory, because the ImageData object
  3348. // is smaller. It also possibly saves C++ memory within the implementation
  3349. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  3350. // the data passed to putImageData()). |n| shouldn't be too small, however,
  3351. // because too many putImageData() calls will slow things down.
  3352. //
  3353. // Note: as written, if the last chunk is partial, the putImageData() call
  3354. // will (conceptually) put pixels past the bounds of the canvas. But
  3355. // that's ok; any such pixels are ignored.
  3356. var height = imgData.height, width = imgData.width;
  3357. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3358. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3359. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3360. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3361. var srcPos = 0, destPos;
  3362. var src = imgData.data;
  3363. var dest = chunkImgData.data;
  3364. var i, j, thisChunkHeight, elemsInThisChunk;
  3365. // There are multiple forms in which the pixel data can be passed, and
  3366. // imgData.kind tells us which one this is.
  3367. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  3368. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  3369. var srcLength = src.byteLength;
  3370. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  3371. new Uint32ArrayView(dest);
  3372. var dest32DataLength = dest32.length;
  3373. var fullSrcDiff = (width + 7) >> 3;
  3374. var white = 0xFFFFFFFF;
  3375. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  3376. 0xFF000000 : 0x000000FF;
  3377. for (i = 0; i < totalChunks; i++) {
  3378. thisChunkHeight =
  3379. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3380. destPos = 0;
  3381. for (j = 0; j < thisChunkHeight; j++) {
  3382. var srcDiff = srcLength - srcPos;
  3383. var k = 0;
  3384. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  3385. var kEndUnrolled = kEnd & ~7;
  3386. var mask = 0;
  3387. var srcByte = 0;
  3388. for (; k < kEndUnrolled; k += 8) {
  3389. srcByte = src[srcPos++];
  3390. dest32[destPos++] = (srcByte & 128) ? white : black;
  3391. dest32[destPos++] = (srcByte & 64) ? white : black;
  3392. dest32[destPos++] = (srcByte & 32) ? white : black;
  3393. dest32[destPos++] = (srcByte & 16) ? white : black;
  3394. dest32[destPos++] = (srcByte & 8) ? white : black;
  3395. dest32[destPos++] = (srcByte & 4) ? white : black;
  3396. dest32[destPos++] = (srcByte & 2) ? white : black;
  3397. dest32[destPos++] = (srcByte & 1) ? white : black;
  3398. }
  3399. for (; k < kEnd; k++) {
  3400. if (mask === 0) {
  3401. srcByte = src[srcPos++];
  3402. mask = 128;
  3403. }
  3404. dest32[destPos++] = (srcByte & mask) ? white : black;
  3405. mask >>= 1;
  3406. }
  3407. }
  3408. // We ran out of input. Make all remaining pixels transparent.
  3409. while (destPos < dest32DataLength) {
  3410. dest32[destPos++] = 0;
  3411. }
  3412. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3413. }
  3414. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  3415. // RGBA, 32-bits per pixel.
  3416. j = 0;
  3417. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  3418. for (i = 0; i < fullChunks; i++) {
  3419. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3420. srcPos += elemsInThisChunk;
  3421. ctx.putImageData(chunkImgData, 0, j);
  3422. j += FULL_CHUNK_HEIGHT;
  3423. }
  3424. if (i < totalChunks) {
  3425. elemsInThisChunk = width * partialChunkHeight * 4;
  3426. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3427. ctx.putImageData(chunkImgData, 0, j);
  3428. }
  3429. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  3430. // RGB, 24-bits per pixel.
  3431. thisChunkHeight = FULL_CHUNK_HEIGHT;
  3432. elemsInThisChunk = width * thisChunkHeight;
  3433. for (i = 0; i < totalChunks; i++) {
  3434. if (i >= fullChunks) {
  3435. thisChunkHeight = partialChunkHeight;
  3436. elemsInThisChunk = width * thisChunkHeight;
  3437. }
  3438. destPos = 0;
  3439. for (j = elemsInThisChunk; j--;) {
  3440. dest[destPos++] = src[srcPos++];
  3441. dest[destPos++] = src[srcPos++];
  3442. dest[destPos++] = src[srcPos++];
  3443. dest[destPos++] = 255;
  3444. }
  3445. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3446. }
  3447. } else {
  3448. error('bad image kind: ' + imgData.kind);
  3449. }
  3450. }
  3451. function putBinaryImageMask(ctx, imgData) {
  3452. var height = imgData.height, width = imgData.width;
  3453. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3454. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3455. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3456. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3457. var srcPos = 0;
  3458. var src = imgData.data;
  3459. var dest = chunkImgData.data;
  3460. for (var i = 0; i < totalChunks; i++) {
  3461. var thisChunkHeight =
  3462. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3463. // Expand the mask so it can be used by the canvas. Any required
  3464. // inversion has already been handled.
  3465. var destPos = 3; // alpha component offset
  3466. for (var j = 0; j < thisChunkHeight; j++) {
  3467. var mask = 0;
  3468. for (var k = 0; k < width; k++) {
  3469. if (!mask) {
  3470. var elem = src[srcPos++];
  3471. mask = 128;
  3472. }
  3473. dest[destPos] = (elem & mask) ? 0 : 255;
  3474. destPos += 4;
  3475. mask >>= 1;
  3476. }
  3477. }
  3478. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3479. }
  3480. }
  3481. function copyCtxState(sourceCtx, destCtx) {
  3482. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  3483. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  3484. 'globalCompositeOperation', 'font'];
  3485. for (var i = 0, ii = properties.length; i < ii; i++) {
  3486. var property = properties[i];
  3487. if (sourceCtx[property] !== undefined) {
  3488. destCtx[property] = sourceCtx[property];
  3489. }
  3490. }
  3491. if (sourceCtx.setLineDash !== undefined) {
  3492. destCtx.setLineDash(sourceCtx.getLineDash());
  3493. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  3494. } else if (sourceCtx.mozDashOffset !== undefined) {
  3495. destCtx.mozDash = sourceCtx.mozDash;
  3496. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  3497. }
  3498. }
  3499. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  3500. var length = bytes.length;
  3501. for (var i = 3; i < length; i += 4) {
  3502. var alpha = bytes[i];
  3503. if (alpha === 0) {
  3504. bytes[i - 3] = r0;
  3505. bytes[i - 2] = g0;
  3506. bytes[i - 1] = b0;
  3507. } else if (alpha < 255) {
  3508. var alpha_ = 255 - alpha;
  3509. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  3510. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  3511. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  3512. }
  3513. }
  3514. }
  3515. function composeSMaskAlpha(maskData, layerData) {
  3516. var length = maskData.length;
  3517. var scale = 1 / 255;
  3518. for (var i = 3; i < length; i += 4) {
  3519. var alpha = maskData[i];
  3520. layerData[i] = (layerData[i] * alpha * scale) | 0;
  3521. }
  3522. }
  3523. function composeSMaskLuminosity(maskData, layerData) {
  3524. var length = maskData.length;
  3525. for (var i = 3; i < length; i += 4) {
  3526. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  3527. (maskData[i - 2] * 152) + // * 0.59 ....
  3528. (maskData[i - 1] * 28); // * 0.11 ....
  3529. layerData[i] = (layerData[i] * y) >> 16;
  3530. }
  3531. }
  3532. function genericComposeSMask(maskCtx, layerCtx, width, height,
  3533. subtype, backdrop) {
  3534. var hasBackdrop = !!backdrop;
  3535. var r0 = hasBackdrop ? backdrop[0] : 0;
  3536. var g0 = hasBackdrop ? backdrop[1] : 0;
  3537. var b0 = hasBackdrop ? backdrop[2] : 0;
  3538. var composeFn;
  3539. if (subtype === 'Luminosity') {
  3540. composeFn = composeSMaskLuminosity;
  3541. } else {
  3542. composeFn = composeSMaskAlpha;
  3543. }
  3544. // processing image in chunks to save memory
  3545. var PIXELS_TO_PROCESS = 1048576;
  3546. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  3547. for (var row = 0; row < height; row += chunkSize) {
  3548. var chunkHeight = Math.min(chunkSize, height - row);
  3549. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  3550. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  3551. if (hasBackdrop) {
  3552. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  3553. }
  3554. composeFn(maskData.data, layerData.data);
  3555. maskCtx.putImageData(layerData, 0, row);
  3556. }
  3557. }
  3558. function composeSMask(ctx, smask, layerCtx) {
  3559. var mask = smask.canvas;
  3560. var maskCtx = smask.context;
  3561. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  3562. smask.offsetX, smask.offsetY);
  3563. var backdrop = smask.backdrop || null;
  3564. if (WebGLUtils.isEnabled) {
  3565. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  3566. {subtype: smask.subtype, backdrop: backdrop});
  3567. ctx.setTransform(1, 0, 0, 1, 0, 0);
  3568. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  3569. return;
  3570. }
  3571. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  3572. smask.subtype, backdrop);
  3573. ctx.drawImage(mask, 0, 0);
  3574. }
  3575. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3576. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3577. var NORMAL_CLIP = {};
  3578. var EO_CLIP = {};
  3579. CanvasGraphics.prototype = {
  3580. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  3581. // For pdfs that use blend modes we have to clear the canvas else certain
  3582. // blend modes can look wrong since we'd be blending with a white
  3583. // backdrop. The problem with a transparent backdrop though is we then
  3584. // don't get sub pixel anti aliasing on text, so we fill with white if
  3585. // we can.
  3586. var width = this.ctx.canvas.width;
  3587. var height = this.ctx.canvas.height;
  3588. if (transparency) {
  3589. this.ctx.clearRect(0, 0, width, height);
  3590. } else {
  3591. this.ctx.mozOpaque = true;
  3592. this.ctx.save();
  3593. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  3594. this.ctx.fillRect(0, 0, width, height);
  3595. this.ctx.restore();
  3596. }
  3597. var transform = viewport.transform;
  3598. this.ctx.save();
  3599. this.ctx.transform.apply(this.ctx, transform);
  3600. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  3601. if (this.imageLayer) {
  3602. this.imageLayer.beginLayout();
  3603. }
  3604. },
  3605. executeOperatorList: function CanvasGraphics_executeOperatorList(
  3606. operatorList,
  3607. executionStartIdx, continueCallback,
  3608. stepper) {
  3609. var argsArray = operatorList.argsArray;
  3610. var fnArray = operatorList.fnArray;
  3611. var i = executionStartIdx || 0;
  3612. var argsArrayLen = argsArray.length;
  3613. // Sometimes the OperatorList to execute is empty.
  3614. if (argsArrayLen === i) {
  3615. return i;
  3616. }
  3617. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  3618. typeof continueCallback === 'function');
  3619. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  3620. var steps = 0;
  3621. var commonObjs = this.commonObjs;
  3622. var objs = this.objs;
  3623. var fnId;
  3624. while (true) {
  3625. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  3626. stepper.breakIt(i, continueCallback);
  3627. return i;
  3628. }
  3629. fnId = fnArray[i];
  3630. if (fnId !== OPS.dependency) {
  3631. this[fnId].apply(this, argsArray[i]);
  3632. } else {
  3633. var deps = argsArray[i];
  3634. for (var n = 0, nn = deps.length; n < nn; n++) {
  3635. var depObjId = deps[n];
  3636. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  3637. var objsPool = common ? commonObjs : objs;
  3638. // If the promise isn't resolved yet, add the continueCallback
  3639. // to the promise and bail out.
  3640. if (!objsPool.isResolved(depObjId)) {
  3641. objsPool.get(depObjId, continueCallback);
  3642. return i;
  3643. }
  3644. }
  3645. }
  3646. i++;
  3647. // If the entire operatorList was executed, stop as were done.
  3648. if (i === argsArrayLen) {
  3649. return i;
  3650. }
  3651. // If the execution took longer then a certain amount of time and
  3652. // `continueCallback` is specified, interrupt the execution.
  3653. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  3654. if (Date.now() > endTime) {
  3655. continueCallback();
  3656. return i;
  3657. }
  3658. steps = 0;
  3659. }
  3660. // If the operatorList isn't executed completely yet OR the execution
  3661. // time was short enough, do another execution round.
  3662. }
  3663. },
  3664. endDrawing: function CanvasGraphics_endDrawing() {
  3665. this.ctx.restore();
  3666. CachedCanvases.clear();
  3667. WebGLUtils.clear();
  3668. if (this.imageLayer) {
  3669. this.imageLayer.endLayout();
  3670. }
  3671. },
  3672. // Graphics state
  3673. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  3674. this.current.lineWidth = width;
  3675. this.ctx.lineWidth = width;
  3676. },
  3677. setLineCap: function CanvasGraphics_setLineCap(style) {
  3678. this.ctx.lineCap = LINE_CAP_STYLES[style];
  3679. },
  3680. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  3681. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  3682. },
  3683. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  3684. this.ctx.miterLimit = limit;
  3685. },
  3686. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  3687. var ctx = this.ctx;
  3688. if (ctx.setLineDash !== undefined) {
  3689. ctx.setLineDash(dashArray);
  3690. ctx.lineDashOffset = dashPhase;
  3691. } else {
  3692. ctx.mozDash = dashArray;
  3693. ctx.mozDashOffset = dashPhase;
  3694. }
  3695. },
  3696. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  3697. // Maybe if we one day fully support color spaces this will be important
  3698. // for now we can ignore.
  3699. // TODO set rendering intent?
  3700. },
  3701. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  3702. // There's no way to control this with canvas, but we can safely ignore.
  3703. // TODO set flatness?
  3704. },
  3705. setGState: function CanvasGraphics_setGState(states) {
  3706. for (var i = 0, ii = states.length; i < ii; i++) {
  3707. var state = states[i];
  3708. var key = state[0];
  3709. var value = state[1];
  3710. switch (key) {
  3711. case 'LW':
  3712. this.setLineWidth(value);
  3713. break;
  3714. case 'LC':
  3715. this.setLineCap(value);
  3716. break;
  3717. case 'LJ':
  3718. this.setLineJoin(value);
  3719. break;
  3720. case 'ML':
  3721. this.setMiterLimit(value);
  3722. break;
  3723. case 'D':
  3724. this.setDash(value[0], value[1]);
  3725. break;
  3726. case 'RI':
  3727. this.setRenderingIntent(value);
  3728. break;
  3729. case 'FL':
  3730. this.setFlatness(value);
  3731. break;
  3732. case 'Font':
  3733. this.setFont(value[0], value[1]);
  3734. break;
  3735. case 'CA':
  3736. this.current.strokeAlpha = state[1];
  3737. break;
  3738. case 'ca':
  3739. this.current.fillAlpha = state[1];
  3740. this.ctx.globalAlpha = state[1];
  3741. break;
  3742. case 'BM':
  3743. if (value && value.name && (value.name !== 'Normal')) {
  3744. var mode = value.name.replace(/([A-Z])/g,
  3745. function(c) {
  3746. return '-' + c.toLowerCase();
  3747. }
  3748. ).substring(1);
  3749. this.ctx.globalCompositeOperation = mode;
  3750. if (this.ctx.globalCompositeOperation !== mode) {
  3751. warn('globalCompositeOperation "' + mode +
  3752. '" is not supported');
  3753. }
  3754. } else {
  3755. this.ctx.globalCompositeOperation = 'source-over';
  3756. }
  3757. break;
  3758. case 'SMask':
  3759. if (this.current.activeSMask) {
  3760. this.endSMaskGroup();
  3761. }
  3762. this.current.activeSMask = value ? this.tempSMask : null;
  3763. if (this.current.activeSMask) {
  3764. this.beginSMaskGroup();
  3765. }
  3766. this.tempSMask = null;
  3767. break;
  3768. }
  3769. }
  3770. },
  3771. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  3772. var activeSMask = this.current.activeSMask;
  3773. var drawnWidth = activeSMask.canvas.width;
  3774. var drawnHeight = activeSMask.canvas.height;
  3775. var cacheId = 'smaskGroupAt' + this.groupLevel;
  3776. var scratchCanvas = CachedCanvases.getCanvas(
  3777. cacheId, drawnWidth, drawnHeight, true);
  3778. var currentCtx = this.ctx;
  3779. var currentTransform = currentCtx.mozCurrentTransform;
  3780. this.ctx.save();
  3781. var groupCtx = scratchCanvas.context;
  3782. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  3783. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  3784. groupCtx.transform.apply(groupCtx, currentTransform);
  3785. copyCtxState(currentCtx, groupCtx);
  3786. this.ctx = groupCtx;
  3787. this.setGState([
  3788. ['BM', 'Normal'],
  3789. ['ca', 1],
  3790. ['CA', 1]
  3791. ]);
  3792. this.groupStack.push(currentCtx);
  3793. this.groupLevel++;
  3794. },
  3795. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  3796. var groupCtx = this.ctx;
  3797. this.groupLevel--;
  3798. this.ctx = this.groupStack.pop();
  3799. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  3800. this.ctx.restore();
  3801. },
  3802. save: function CanvasGraphics_save() {
  3803. this.ctx.save();
  3804. var old = this.current;
  3805. this.stateStack.push(old);
  3806. this.current = old.clone();
  3807. this.current.activeSMask = null;
  3808. },
  3809. restore: function CanvasGraphics_restore() {
  3810. if (this.stateStack.length !== 0) {
  3811. if (this.current.activeSMask !== null) {
  3812. this.endSMaskGroup();
  3813. }
  3814. this.current = this.stateStack.pop();
  3815. this.ctx.restore();
  3816. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  3817. this.pendingClip = null;
  3818. this.cachedGetSinglePixelWidth = null;
  3819. }
  3820. },
  3821. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  3822. this.ctx.transform(a, b, c, d, e, f);
  3823. this.cachedGetSinglePixelWidth = null;
  3824. },
  3825. // Path
  3826. constructPath: function CanvasGraphics_constructPath(ops, args) {
  3827. var ctx = this.ctx;
  3828. var current = this.current;
  3829. var x = current.x, y = current.y;
  3830. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  3831. switch (ops[i] | 0) {
  3832. case OPS.rectangle:
  3833. x = args[j++];
  3834. y = args[j++];
  3835. var width = args[j++];
  3836. var height = args[j++];
  3837. if (width === 0) {
  3838. width = this.getSinglePixelWidth();
  3839. }
  3840. if (height === 0) {
  3841. height = this.getSinglePixelWidth();
  3842. }
  3843. var xw = x + width;
  3844. var yh = y + height;
  3845. this.ctx.moveTo(x, y);
  3846. this.ctx.lineTo(xw, y);
  3847. this.ctx.lineTo(xw, yh);
  3848. this.ctx.lineTo(x, yh);
  3849. this.ctx.lineTo(x, y);
  3850. this.ctx.closePath();
  3851. break;
  3852. case OPS.moveTo:
  3853. x = args[j++];
  3854. y = args[j++];
  3855. ctx.moveTo(x, y);
  3856. break;
  3857. case OPS.lineTo:
  3858. x = args[j++];
  3859. y = args[j++];
  3860. ctx.lineTo(x, y);
  3861. break;
  3862. case OPS.curveTo:
  3863. x = args[j + 4];
  3864. y = args[j + 5];
  3865. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  3866. x, y);
  3867. j += 6;
  3868. break;
  3869. case OPS.curveTo2:
  3870. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  3871. args[j + 2], args[j + 3]);
  3872. x = args[j + 2];
  3873. y = args[j + 3];
  3874. j += 4;
  3875. break;
  3876. case OPS.curveTo3:
  3877. x = args[j + 2];
  3878. y = args[j + 3];
  3879. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  3880. j += 4;
  3881. break;
  3882. case OPS.closePath:
  3883. ctx.closePath();
  3884. break;
  3885. }
  3886. }
  3887. current.setCurrentPoint(x, y);
  3888. },
  3889. closePath: function CanvasGraphics_closePath() {
  3890. this.ctx.closePath();
  3891. },
  3892. stroke: function CanvasGraphics_stroke(consumePath) {
  3893. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3894. var ctx = this.ctx;
  3895. var strokeColor = this.current.strokeColor;
  3896. // Prevent drawing too thin lines by enforcing a minimum line width.
  3897. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  3898. this.current.lineWidth);
  3899. // For stroke we want to temporarily change the global alpha to the
  3900. // stroking alpha.
  3901. ctx.globalAlpha = this.current.strokeAlpha;
  3902. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  3903. strokeColor.type === 'Pattern') {
  3904. // for patterns, we transform to pattern space, calculate
  3905. // the pattern, call stroke, and restore to user space
  3906. ctx.save();
  3907. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  3908. ctx.stroke();
  3909. ctx.restore();
  3910. } else {
  3911. ctx.stroke();
  3912. }
  3913. if (consumePath) {
  3914. this.consumePath();
  3915. }
  3916. // Restore the global alpha to the fill alpha
  3917. ctx.globalAlpha = this.current.fillAlpha;
  3918. },
  3919. closeStroke: function CanvasGraphics_closeStroke() {
  3920. this.closePath();
  3921. this.stroke();
  3922. },
  3923. fill: function CanvasGraphics_fill(consumePath) {
  3924. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3925. var ctx = this.ctx;
  3926. var fillColor = this.current.fillColor;
  3927. var isPatternFill = this.current.patternFill;
  3928. var needRestore = false;
  3929. if (isPatternFill) {
  3930. ctx.save();
  3931. ctx.fillStyle = fillColor.getPattern(ctx, this);
  3932. needRestore = true;
  3933. }
  3934. if (this.pendingEOFill) {
  3935. if (ctx.mozFillRule !== undefined) {
  3936. ctx.mozFillRule = 'evenodd';
  3937. ctx.fill();
  3938. ctx.mozFillRule = 'nonzero';
  3939. } else {
  3940. ctx.fill('evenodd');
  3941. }
  3942. this.pendingEOFill = false;
  3943. } else {
  3944. ctx.fill();
  3945. }
  3946. if (needRestore) {
  3947. ctx.restore();
  3948. }
  3949. if (consumePath) {
  3950. this.consumePath();
  3951. }
  3952. },
  3953. eoFill: function CanvasGraphics_eoFill() {
  3954. this.pendingEOFill = true;
  3955. this.fill();
  3956. },
  3957. fillStroke: function CanvasGraphics_fillStroke() {
  3958. this.fill(false);
  3959. this.stroke(false);
  3960. this.consumePath();
  3961. },
  3962. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  3963. this.pendingEOFill = true;
  3964. this.fillStroke();
  3965. },
  3966. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  3967. this.closePath();
  3968. this.fillStroke();
  3969. },
  3970. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  3971. this.pendingEOFill = true;
  3972. this.closePath();
  3973. this.fillStroke();
  3974. },
  3975. endPath: function CanvasGraphics_endPath() {
  3976. this.consumePath();
  3977. },
  3978. // Clipping
  3979. clip: function CanvasGraphics_clip() {
  3980. this.pendingClip = NORMAL_CLIP;
  3981. },
  3982. eoClip: function CanvasGraphics_eoClip() {
  3983. this.pendingClip = EO_CLIP;
  3984. },
  3985. // Text
  3986. beginText: function CanvasGraphics_beginText() {
  3987. this.current.textMatrix = IDENTITY_MATRIX;
  3988. this.current.textMatrixScale = 1;
  3989. this.current.x = this.current.lineX = 0;
  3990. this.current.y = this.current.lineY = 0;
  3991. },
  3992. endText: function CanvasGraphics_endText() {
  3993. var paths = this.pendingTextPaths;
  3994. var ctx = this.ctx;
  3995. if (paths === undefined) {
  3996. ctx.beginPath();
  3997. return;
  3998. }
  3999. ctx.save();
  4000. ctx.beginPath();
  4001. for (var i = 0; i < paths.length; i++) {
  4002. var path = paths[i];
  4003. ctx.setTransform.apply(ctx, path.transform);
  4004. ctx.translate(path.x, path.y);
  4005. path.addToPath(ctx, path.fontSize);
  4006. }
  4007. ctx.restore();
  4008. ctx.clip();
  4009. ctx.beginPath();
  4010. delete this.pendingTextPaths;
  4011. },
  4012. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  4013. this.current.charSpacing = spacing;
  4014. },
  4015. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  4016. this.current.wordSpacing = spacing;
  4017. },
  4018. setHScale: function CanvasGraphics_setHScale(scale) {
  4019. this.current.textHScale = scale / 100;
  4020. },
  4021. setLeading: function CanvasGraphics_setLeading(leading) {
  4022. this.current.leading = -leading;
  4023. },
  4024. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  4025. var fontObj = this.commonObjs.get(fontRefName);
  4026. var current = this.current;
  4027. if (!fontObj) {
  4028. error('Can\'t find font for ' + fontRefName);
  4029. }
  4030. current.fontMatrix = (fontObj.fontMatrix ?
  4031. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  4032. // A valid matrix needs all main diagonal elements to be non-zero
  4033. // This also ensures we bypass FF bugzilla bug #719844.
  4034. if (current.fontMatrix[0] === 0 ||
  4035. current.fontMatrix[3] === 0) {
  4036. warn('Invalid font matrix for font ' + fontRefName);
  4037. }
  4038. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  4039. // and in some docs this can be negative (inverted x-y axes).
  4040. if (size < 0) {
  4041. size = -size;
  4042. current.fontDirection = -1;
  4043. } else {
  4044. current.fontDirection = 1;
  4045. }
  4046. this.current.font = fontObj;
  4047. this.current.fontSize = size;
  4048. if (fontObj.isType3Font) {
  4049. return; // we don't need ctx.font for Type3 fonts
  4050. }
  4051. var name = fontObj.loadedName || 'sans-serif';
  4052. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  4053. (fontObj.bold ? 'bold' : 'normal');
  4054. var italic = fontObj.italic ? 'italic' : 'normal';
  4055. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  4056. // Some font backends cannot handle fonts below certain size.
  4057. // Keeping the font at minimal size and using the fontSizeScale to change
  4058. // the current transformation matrix before the fillText/strokeText.
  4059. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  4060. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  4061. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  4062. this.current.fontSizeScale = size / browserFontSize;
  4063. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  4064. this.ctx.font = rule;
  4065. },
  4066. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  4067. this.current.textRenderingMode = mode;
  4068. },
  4069. setTextRise: function CanvasGraphics_setTextRise(rise) {
  4070. this.current.textRise = rise;
  4071. },
  4072. moveText: function CanvasGraphics_moveText(x, y) {
  4073. this.current.x = this.current.lineX += x;
  4074. this.current.y = this.current.lineY += y;
  4075. },
  4076. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  4077. this.setLeading(-y);
  4078. this.moveText(x, y);
  4079. },
  4080. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  4081. this.current.textMatrix = [a, b, c, d, e, f];
  4082. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  4083. this.current.x = this.current.lineX = 0;
  4084. this.current.y = this.current.lineY = 0;
  4085. },
  4086. nextLine: function CanvasGraphics_nextLine() {
  4087. this.moveText(0, this.current.leading);
  4088. },
  4089. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  4090. var ctx = this.ctx;
  4091. var current = this.current;
  4092. var font = current.font;
  4093. var textRenderingMode = current.textRenderingMode;
  4094. var fontSize = current.fontSize / current.fontSizeScale;
  4095. var fillStrokeMode = textRenderingMode &
  4096. TextRenderingMode.FILL_STROKE_MASK;
  4097. var isAddToPathSet = !!(textRenderingMode &
  4098. TextRenderingMode.ADD_TO_PATH_FLAG);
  4099. var addToPath;
  4100. if (font.disableFontFace || isAddToPathSet) {
  4101. addToPath = font.getPathGenerator(this.commonObjs, character);
  4102. }
  4103. if (font.disableFontFace) {
  4104. ctx.save();
  4105. ctx.translate(x, y);
  4106. ctx.beginPath();
  4107. addToPath(ctx, fontSize);
  4108. if (fillStrokeMode === TextRenderingMode.FILL ||
  4109. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4110. ctx.fill();
  4111. }
  4112. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4113. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4114. ctx.stroke();
  4115. }
  4116. ctx.restore();
  4117. } else {
  4118. if (fillStrokeMode === TextRenderingMode.FILL ||
  4119. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4120. ctx.fillText(character, x, y);
  4121. }
  4122. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4123. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4124. ctx.strokeText(character, x, y);
  4125. }
  4126. }
  4127. if (isAddToPathSet) {
  4128. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  4129. paths.push({
  4130. transform: ctx.mozCurrentTransform,
  4131. x: x,
  4132. y: y,
  4133. fontSize: fontSize,
  4134. addToPath: addToPath
  4135. });
  4136. }
  4137. },
  4138. get isFontSubpixelAAEnabled() {
  4139. // Checks if anti-aliasing is enabled when scaled text is painted.
  4140. // On Windows GDI scaled fonts looks bad.
  4141. var ctx = document.createElement('canvas').getContext('2d');
  4142. ctx.scale(1.5, 1);
  4143. ctx.fillText('I', 0, 10);
  4144. var data = ctx.getImageData(0, 0, 10, 10).data;
  4145. var enabled = false;
  4146. for (var i = 3; i < data.length; i += 4) {
  4147. if (data[i] > 0 && data[i] < 255) {
  4148. enabled = true;
  4149. break;
  4150. }
  4151. }
  4152. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  4153. },
  4154. showText: function CanvasGraphics_showText(glyphs) {
  4155. var current = this.current;
  4156. var font = current.font;
  4157. if (font.isType3Font) {
  4158. return this.showType3Text(glyphs);
  4159. }
  4160. var fontSize = current.fontSize;
  4161. if (fontSize === 0) {
  4162. return;
  4163. }
  4164. var ctx = this.ctx;
  4165. var fontSizeScale = current.fontSizeScale;
  4166. var charSpacing = current.charSpacing;
  4167. var wordSpacing = current.wordSpacing;
  4168. var fontDirection = current.fontDirection;
  4169. var textHScale = current.textHScale * fontDirection;
  4170. var glyphsLength = glyphs.length;
  4171. var vertical = font.vertical;
  4172. var spacingDir = vertical ? 1 : -1;
  4173. var defaultVMetrics = font.defaultVMetrics;
  4174. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  4175. var simpleFillText =
  4176. current.textRenderingMode === TextRenderingMode.FILL &&
  4177. !font.disableFontFace;
  4178. ctx.save();
  4179. ctx.transform.apply(ctx, current.textMatrix);
  4180. ctx.translate(current.x, current.y + current.textRise);
  4181. if (fontDirection > 0) {
  4182. ctx.scale(textHScale, -1);
  4183. } else {
  4184. ctx.scale(textHScale, 1);
  4185. }
  4186. var lineWidth = current.lineWidth;
  4187. var scale = current.textMatrixScale;
  4188. if (scale === 0 || lineWidth === 0) {
  4189. var fillStrokeMode = current.textRenderingMode &
  4190. TextRenderingMode.FILL_STROKE_MASK;
  4191. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4192. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4193. this.cachedGetSinglePixelWidth = null;
  4194. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  4195. }
  4196. } else {
  4197. lineWidth /= scale;
  4198. }
  4199. if (fontSizeScale !== 1.0) {
  4200. ctx.scale(fontSizeScale, fontSizeScale);
  4201. lineWidth /= fontSizeScale;
  4202. }
  4203. ctx.lineWidth = lineWidth;
  4204. var x = 0, i;
  4205. for (i = 0; i < glyphsLength; ++i) {
  4206. var glyph = glyphs[i];
  4207. if (glyph === null) {
  4208. // word break
  4209. x += fontDirection * wordSpacing;
  4210. continue;
  4211. } else if (isNum(glyph)) {
  4212. x += spacingDir * glyph * fontSize / 1000;
  4213. continue;
  4214. }
  4215. var restoreNeeded = false;
  4216. var character = glyph.fontChar;
  4217. var accent = glyph.accent;
  4218. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  4219. var width = glyph.width;
  4220. if (vertical) {
  4221. var vmetric, vx, vy;
  4222. vmetric = glyph.vmetric || defaultVMetrics;
  4223. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  4224. vx = -vx * widthAdvanceScale;
  4225. vy = vmetric[2] * widthAdvanceScale;
  4226. width = vmetric ? -vmetric[0] : width;
  4227. scaledX = vx / fontSizeScale;
  4228. scaledY = (x + vy) / fontSizeScale;
  4229. } else {
  4230. scaledX = x / fontSizeScale;
  4231. scaledY = 0;
  4232. }
  4233. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  4234. // some standard fonts may not have the exact width, trying to
  4235. // rescale per character
  4236. var measuredWidth = ctx.measureText(character).width * 1000 /
  4237. fontSize * fontSizeScale;
  4238. var characterScaleX = width / measuredWidth;
  4239. restoreNeeded = true;
  4240. ctx.save();
  4241. ctx.scale(characterScaleX, 1);
  4242. scaledX /= characterScaleX;
  4243. }
  4244. if (simpleFillText && !accent) {
  4245. // common case
  4246. ctx.fillText(character, scaledX, scaledY);
  4247. } else {
  4248. this.paintChar(character, scaledX, scaledY);
  4249. if (accent) {
  4250. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  4251. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  4252. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  4253. }
  4254. }
  4255. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  4256. x += charWidth;
  4257. if (restoreNeeded) {
  4258. ctx.restore();
  4259. }
  4260. }
  4261. if (vertical) {
  4262. current.y -= x * textHScale;
  4263. } else {
  4264. current.x += x * textHScale;
  4265. }
  4266. ctx.restore();
  4267. },
  4268. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  4269. // Type3 fonts - each glyph is a "mini-PDF"
  4270. var ctx = this.ctx;
  4271. var current = this.current;
  4272. var font = current.font;
  4273. var fontSize = current.fontSize;
  4274. var fontDirection = current.fontDirection;
  4275. var spacingDir = font.vertical ? 1 : -1;
  4276. var charSpacing = current.charSpacing;
  4277. var wordSpacing = current.wordSpacing;
  4278. var textHScale = current.textHScale * fontDirection;
  4279. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  4280. var glyphsLength = glyphs.length;
  4281. var isTextInvisible =
  4282. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  4283. var i, glyph, width, spacingLength;
  4284. if (isTextInvisible || fontSize === 0) {
  4285. return;
  4286. }
  4287. this.cachedGetSinglePixelWidth = null;
  4288. ctx.save();
  4289. ctx.transform.apply(ctx, current.textMatrix);
  4290. ctx.translate(current.x, current.y);
  4291. ctx.scale(textHScale, fontDirection);
  4292. for (i = 0; i < glyphsLength; ++i) {
  4293. glyph = glyphs[i];
  4294. if (glyph === null) {
  4295. // word break
  4296. this.ctx.translate(wordSpacing, 0);
  4297. current.x += wordSpacing * textHScale;
  4298. continue;
  4299. } else if (isNum(glyph)) {
  4300. spacingLength = spacingDir * glyph * fontSize / 1000;
  4301. this.ctx.translate(spacingLength, 0);
  4302. current.x += spacingLength * textHScale;
  4303. continue;
  4304. }
  4305. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4306. if (!operatorList) {
  4307. warn('Type3 character \"' + glyph.operatorListId +
  4308. '\" is not available');
  4309. continue;
  4310. }
  4311. this.processingType3 = glyph;
  4312. this.save();
  4313. ctx.scale(fontSize, fontSize);
  4314. ctx.transform.apply(ctx, fontMatrix);
  4315. this.executeOperatorList(operatorList);
  4316. this.restore();
  4317. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4318. width = transformed[0] * fontSize + charSpacing;
  4319. ctx.translate(width, 0);
  4320. current.x += width * textHScale;
  4321. }
  4322. ctx.restore();
  4323. this.processingType3 = null;
  4324. },
  4325. // Type3 fonts
  4326. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4327. // We can safely ignore this since the width should be the same
  4328. // as the width in the Widths array.
  4329. },
  4330. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4331. yWidth,
  4332. llx,
  4333. lly,
  4334. urx,
  4335. ury) {
  4336. // TODO According to the spec we're also suppose to ignore any operators
  4337. // that set color or include images while processing this type3 font.
  4338. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  4339. this.clip();
  4340. this.endPath();
  4341. },
  4342. // Color
  4343. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4344. var pattern;
  4345. if (IR[0] === 'TilingPattern') {
  4346. var color = IR[1];
  4347. var baseTransform = this.baseTransform ||
  4348. this.ctx.mozCurrentTransform.slice();
  4349. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4350. this.commonObjs, baseTransform);
  4351. } else {
  4352. pattern = getShadingPatternFromIR(IR);
  4353. }
  4354. return pattern;
  4355. },
  4356. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4357. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4358. },
  4359. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4360. this.current.fillColor = this.getColorN_Pattern(arguments);
  4361. this.current.patternFill = true;
  4362. },
  4363. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4364. var color = Util.makeCssRgb(r, g, b);
  4365. this.ctx.strokeStyle = color;
  4366. this.current.strokeColor = color;
  4367. },
  4368. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4369. var color = Util.makeCssRgb(r, g, b);
  4370. this.ctx.fillStyle = color;
  4371. this.current.fillColor = color;
  4372. this.current.patternFill = false;
  4373. },
  4374. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4375. var ctx = this.ctx;
  4376. this.save();
  4377. var pattern = getShadingPatternFromIR(patternIR);
  4378. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4379. var inv = ctx.mozCurrentTransformInverse;
  4380. if (inv) {
  4381. var canvas = ctx.canvas;
  4382. var width = canvas.width;
  4383. var height = canvas.height;
  4384. var bl = Util.applyTransform([0, 0], inv);
  4385. var br = Util.applyTransform([0, height], inv);
  4386. var ul = Util.applyTransform([width, 0], inv);
  4387. var ur = Util.applyTransform([width, height], inv);
  4388. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4389. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4390. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4391. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4392. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4393. } else {
  4394. // HACK to draw the gradient onto an infinite rectangle.
  4395. // PDF gradients are drawn across the entire image while
  4396. // Canvas only allows gradients to be drawn in a rectangle
  4397. // The following bug should allow us to remove this.
  4398. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4399. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4400. }
  4401. this.restore();
  4402. },
  4403. // Images
  4404. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4405. error('Should not call beginInlineImage');
  4406. },
  4407. beginImageData: function CanvasGraphics_beginImageData() {
  4408. error('Should not call beginImageData');
  4409. },
  4410. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4411. bbox) {
  4412. this.save();
  4413. this.baseTransformStack.push(this.baseTransform);
  4414. if (isArray(matrix) && 6 === matrix.length) {
  4415. this.transform.apply(this, matrix);
  4416. }
  4417. this.baseTransform = this.ctx.mozCurrentTransform;
  4418. if (isArray(bbox) && 4 === bbox.length) {
  4419. var width = bbox[2] - bbox[0];
  4420. var height = bbox[3] - bbox[1];
  4421. this.ctx.rect(bbox[0], bbox[1], width, height);
  4422. this.clip();
  4423. this.endPath();
  4424. }
  4425. },
  4426. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4427. this.restore();
  4428. this.baseTransform = this.baseTransformStack.pop();
  4429. },
  4430. beginGroup: function CanvasGraphics_beginGroup(group) {
  4431. this.save();
  4432. var currentCtx = this.ctx;
  4433. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4434. // group results aren't usually that different and they even have tools
  4435. // that ignore this setting. Notes from Rik on implmenting:
  4436. // - When you encounter an transparency group, create a new canvas with
  4437. // the dimensions of the bbox
  4438. // - copy the content from the previous canvas to the new canvas
  4439. // - draw as usual
  4440. // - remove the backdrop alpha:
  4441. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4442. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4443. // backdrop
  4444. // - remove background color:
  4445. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4446. if (!group.isolated) {
  4447. info('TODO: Support non-isolated groups.');
  4448. }
  4449. // TODO knockout - supposedly possible with the clever use of compositing
  4450. // modes.
  4451. if (group.knockout) {
  4452. warn('Knockout groups not supported.');
  4453. }
  4454. var currentTransform = currentCtx.mozCurrentTransform;
  4455. if (group.matrix) {
  4456. currentCtx.transform.apply(currentCtx, group.matrix);
  4457. }
  4458. assert(group.bbox, 'Bounding box is required.');
  4459. // Based on the current transform figure out how big the bounding box
  4460. // will actually be.
  4461. var bounds = Util.getAxialAlignedBoundingBox(
  4462. group.bbox,
  4463. currentCtx.mozCurrentTransform);
  4464. // Clip the bounding box to the current canvas.
  4465. var canvasBounds = [0,
  4466. 0,
  4467. currentCtx.canvas.width,
  4468. currentCtx.canvas.height];
  4469. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4470. // Use ceil in case we're between sizes so we don't create canvas that is
  4471. // too small and make the canvas at least 1x1 pixels.
  4472. var offsetX = Math.floor(bounds[0]);
  4473. var offsetY = Math.floor(bounds[1]);
  4474. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4475. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4476. var scaleX = 1, scaleY = 1;
  4477. if (drawnWidth > MAX_GROUP_SIZE) {
  4478. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4479. drawnWidth = MAX_GROUP_SIZE;
  4480. }
  4481. if (drawnHeight > MAX_GROUP_SIZE) {
  4482. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4483. drawnHeight = MAX_GROUP_SIZE;
  4484. }
  4485. var cacheId = 'groupAt' + this.groupLevel;
  4486. if (group.smask) {
  4487. // Using two cache entries is case if masks are used one after another.
  4488. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4489. }
  4490. var scratchCanvas = CachedCanvases.getCanvas(
  4491. cacheId, drawnWidth, drawnHeight, true);
  4492. var groupCtx = scratchCanvas.context;
  4493. // Since we created a new canvas that is just the size of the bounding box
  4494. // we have to translate the group ctx.
  4495. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4496. groupCtx.translate(-offsetX, -offsetY);
  4497. groupCtx.transform.apply(groupCtx, currentTransform);
  4498. if (group.smask) {
  4499. // Saving state and cached mask to be used in setGState.
  4500. this.smaskStack.push({
  4501. canvas: scratchCanvas.canvas,
  4502. context: groupCtx,
  4503. offsetX: offsetX,
  4504. offsetY: offsetY,
  4505. scaleX: scaleX,
  4506. scaleY: scaleY,
  4507. subtype: group.smask.subtype,
  4508. backdrop: group.smask.backdrop
  4509. });
  4510. } else {
  4511. // Setup the current ctx so when the group is popped we draw it at the
  4512. // right location.
  4513. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4514. currentCtx.translate(offsetX, offsetY);
  4515. currentCtx.scale(scaleX, scaleY);
  4516. }
  4517. // The transparency group inherits all off the current graphics state
  4518. // except the blend mode, soft mask, and alpha constants.
  4519. copyCtxState(currentCtx, groupCtx);
  4520. this.ctx = groupCtx;
  4521. this.setGState([
  4522. ['BM', 'Normal'],
  4523. ['ca', 1],
  4524. ['CA', 1]
  4525. ]);
  4526. this.groupStack.push(currentCtx);
  4527. this.groupLevel++;
  4528. },
  4529. endGroup: function CanvasGraphics_endGroup(group) {
  4530. this.groupLevel--;
  4531. var groupCtx = this.ctx;
  4532. this.ctx = this.groupStack.pop();
  4533. // Turn off image smoothing to avoid sub pixel interpolation which can
  4534. // look kind of blurry for some pdfs.
  4535. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4536. this.ctx.imageSmoothingEnabled = false;
  4537. } else {
  4538. this.ctx.mozImageSmoothingEnabled = false;
  4539. }
  4540. if (group.smask) {
  4541. this.tempSMask = this.smaskStack.pop();
  4542. } else {
  4543. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4544. }
  4545. this.restore();
  4546. },
  4547. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4548. this.save();
  4549. this.current = new CanvasExtraState();
  4550. },
  4551. endAnnotations: function CanvasGraphics_endAnnotations() {
  4552. this.restore();
  4553. },
  4554. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4555. matrix) {
  4556. this.save();
  4557. if (isArray(rect) && 4 === rect.length) {
  4558. var width = rect[2] - rect[0];
  4559. var height = rect[3] - rect[1];
  4560. this.ctx.rect(rect[0], rect[1], width, height);
  4561. this.clip();
  4562. this.endPath();
  4563. }
  4564. this.transform.apply(this, transform);
  4565. this.transform.apply(this, matrix);
  4566. },
  4567. endAnnotation: function CanvasGraphics_endAnnotation() {
  4568. this.restore();
  4569. },
  4570. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4571. var domImage = this.objs.get(objId);
  4572. if (!domImage) {
  4573. warn('Dependent image isn\'t ready yet');
  4574. return;
  4575. }
  4576. this.save();
  4577. var ctx = this.ctx;
  4578. // scale the image to the unit square
  4579. ctx.scale(1 / w, -1 / h);
  4580. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4581. 0, -h, w, h);
  4582. if (this.imageLayer) {
  4583. var currentTransform = ctx.mozCurrentTransformInverse;
  4584. var position = this.getCanvasPosition(0, 0);
  4585. this.imageLayer.appendImage({
  4586. objId: objId,
  4587. left: position[0],
  4588. top: position[1],
  4589. width: w / currentTransform[0],
  4590. height: h / currentTransform[3]
  4591. });
  4592. }
  4593. this.restore();
  4594. },
  4595. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  4596. var ctx = this.ctx;
  4597. var width = img.width, height = img.height;
  4598. var fillColor = this.current.fillColor;
  4599. var isPatternFill = this.current.patternFill;
  4600. var glyph = this.processingType3;
  4601. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  4602. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  4603. glyph.compiled =
  4604. compileType3Glyph({data: img.data, width: width, height: height});
  4605. } else {
  4606. glyph.compiled = null;
  4607. }
  4608. }
  4609. if (glyph && glyph.compiled) {
  4610. glyph.compiled(ctx);
  4611. return;
  4612. }
  4613. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4614. var maskCtx = maskCanvas.context;
  4615. maskCtx.save();
  4616. putBinaryImageMask(maskCtx, img);
  4617. maskCtx.globalCompositeOperation = 'source-in';
  4618. maskCtx.fillStyle = isPatternFill ?
  4619. fillColor.getPattern(maskCtx, this) : fillColor;
  4620. maskCtx.fillRect(0, 0, width, height);
  4621. maskCtx.restore();
  4622. this.paintInlineImageXObject(maskCanvas.canvas);
  4623. },
  4624. paintImageMaskXObjectRepeat:
  4625. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  4626. scaleY, positions) {
  4627. var width = imgData.width;
  4628. var height = imgData.height;
  4629. var fillColor = this.current.fillColor;
  4630. var isPatternFill = this.current.patternFill;
  4631. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4632. var maskCtx = maskCanvas.context;
  4633. maskCtx.save();
  4634. putBinaryImageMask(maskCtx, imgData);
  4635. maskCtx.globalCompositeOperation = 'source-in';
  4636. maskCtx.fillStyle = isPatternFill ?
  4637. fillColor.getPattern(maskCtx, this) : fillColor;
  4638. maskCtx.fillRect(0, 0, width, height);
  4639. maskCtx.restore();
  4640. var ctx = this.ctx;
  4641. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4642. ctx.save();
  4643. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  4644. ctx.scale(1, -1);
  4645. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4646. 0, -1, 1, 1);
  4647. ctx.restore();
  4648. }
  4649. },
  4650. paintImageMaskXObjectGroup:
  4651. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  4652. var ctx = this.ctx;
  4653. var fillColor = this.current.fillColor;
  4654. var isPatternFill = this.current.patternFill;
  4655. for (var i = 0, ii = images.length; i < ii; i++) {
  4656. var image = images[i];
  4657. var width = image.width, height = image.height;
  4658. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4659. var maskCtx = maskCanvas.context;
  4660. maskCtx.save();
  4661. putBinaryImageMask(maskCtx, image);
  4662. maskCtx.globalCompositeOperation = 'source-in';
  4663. maskCtx.fillStyle = isPatternFill ?
  4664. fillColor.getPattern(maskCtx, this) : fillColor;
  4665. maskCtx.fillRect(0, 0, width, height);
  4666. maskCtx.restore();
  4667. ctx.save();
  4668. ctx.transform.apply(ctx, image.transform);
  4669. ctx.scale(1, -1);
  4670. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4671. 0, -1, 1, 1);
  4672. ctx.restore();
  4673. }
  4674. },
  4675. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  4676. var imgData = this.objs.get(objId);
  4677. if (!imgData) {
  4678. warn('Dependent image isn\'t ready yet');
  4679. return;
  4680. }
  4681. this.paintInlineImageXObject(imgData);
  4682. },
  4683. paintImageXObjectRepeat:
  4684. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  4685. positions) {
  4686. var imgData = this.objs.get(objId);
  4687. if (!imgData) {
  4688. warn('Dependent image isn\'t ready yet');
  4689. return;
  4690. }
  4691. var width = imgData.width;
  4692. var height = imgData.height;
  4693. var map = [];
  4694. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4695. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  4696. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  4697. }
  4698. this.paintInlineImageXObjectGroup(imgData, map);
  4699. },
  4700. paintInlineImageXObject:
  4701. function CanvasGraphics_paintInlineImageXObject(imgData) {
  4702. var width = imgData.width;
  4703. var height = imgData.height;
  4704. var ctx = this.ctx;
  4705. this.save();
  4706. // scale the image to the unit square
  4707. ctx.scale(1 / width, -1 / height);
  4708. var currentTransform = ctx.mozCurrentTransformInverse;
  4709. var a = currentTransform[0], b = currentTransform[1];
  4710. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  4711. var c = currentTransform[2], d = currentTransform[3];
  4712. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  4713. var imgToPaint, tmpCanvas;
  4714. // instanceof HTMLElement does not work in jsdom node.js module
  4715. if (imgData instanceof HTMLElement || !imgData.data) {
  4716. imgToPaint = imgData;
  4717. } else {
  4718. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  4719. var tmpCtx = tmpCanvas.context;
  4720. putBinaryImageData(tmpCtx, imgData);
  4721. imgToPaint = tmpCanvas.canvas;
  4722. }
  4723. var paintWidth = width, paintHeight = height;
  4724. var tmpCanvasId = 'prescale1';
  4725. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  4726. // pixels during drawImage operation, painting on the temporary canvas(es)
  4727. // that are twice smaller in size
  4728. while ((widthScale > 2 && paintWidth > 1) ||
  4729. (heightScale > 2 && paintHeight > 1)) {
  4730. var newWidth = paintWidth, newHeight = paintHeight;
  4731. if (widthScale > 2 && paintWidth > 1) {
  4732. newWidth = Math.ceil(paintWidth / 2);
  4733. widthScale /= paintWidth / newWidth;
  4734. }
  4735. if (heightScale > 2 && paintHeight > 1) {
  4736. newHeight = Math.ceil(paintHeight / 2);
  4737. heightScale /= paintHeight / newHeight;
  4738. }
  4739. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  4740. tmpCtx = tmpCanvas.context;
  4741. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  4742. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4743. 0, 0, newWidth, newHeight);
  4744. imgToPaint = tmpCanvas.canvas;
  4745. paintWidth = newWidth;
  4746. paintHeight = newHeight;
  4747. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  4748. }
  4749. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4750. 0, -height, width, height);
  4751. if (this.imageLayer) {
  4752. var position = this.getCanvasPosition(0, -height);
  4753. this.imageLayer.appendImage({
  4754. imgData: imgData,
  4755. left: position[0],
  4756. top: position[1],
  4757. width: width / currentTransform[0],
  4758. height: height / currentTransform[3]
  4759. });
  4760. }
  4761. this.restore();
  4762. },
  4763. paintInlineImageXObjectGroup:
  4764. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  4765. var ctx = this.ctx;
  4766. var w = imgData.width;
  4767. var h = imgData.height;
  4768. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  4769. var tmpCtx = tmpCanvas.context;
  4770. putBinaryImageData(tmpCtx, imgData);
  4771. for (var i = 0, ii = map.length; i < ii; i++) {
  4772. var entry = map[i];
  4773. ctx.save();
  4774. ctx.transform.apply(ctx, entry.transform);
  4775. ctx.scale(1, -1);
  4776. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  4777. 0, -1, 1, 1);
  4778. if (this.imageLayer) {
  4779. var position = this.getCanvasPosition(entry.x, entry.y);
  4780. this.imageLayer.appendImage({
  4781. imgData: imgData,
  4782. left: position[0],
  4783. top: position[1],
  4784. width: w,
  4785. height: h
  4786. });
  4787. }
  4788. ctx.restore();
  4789. }
  4790. },
  4791. paintSolidColorImageMask:
  4792. function CanvasGraphics_paintSolidColorImageMask() {
  4793. this.ctx.fillRect(0, 0, 1, 1);
  4794. },
  4795. paintXObject: function CanvasGraphics_paintXObject() {
  4796. UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
  4797. warn('Unsupported \'paintXObject\' command.');
  4798. },
  4799. // Marked content
  4800. markPoint: function CanvasGraphics_markPoint(tag) {
  4801. // TODO Marked content.
  4802. },
  4803. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  4804. // TODO Marked content.
  4805. },
  4806. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  4807. // TODO Marked content.
  4808. },
  4809. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  4810. tag, properties) {
  4811. // TODO Marked content.
  4812. },
  4813. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  4814. // TODO Marked content.
  4815. },
  4816. // Compatibility
  4817. beginCompat: function CanvasGraphics_beginCompat() {
  4818. // TODO ignore undefined operators (should we do that anyway?)
  4819. },
  4820. endCompat: function CanvasGraphics_endCompat() {
  4821. // TODO stop ignoring undefined operators
  4822. },
  4823. // Helper functions
  4824. consumePath: function CanvasGraphics_consumePath() {
  4825. var ctx = this.ctx;
  4826. if (this.pendingClip) {
  4827. if (this.pendingClip === EO_CLIP) {
  4828. if (ctx.mozFillRule !== undefined) {
  4829. ctx.mozFillRule = 'evenodd';
  4830. ctx.clip();
  4831. ctx.mozFillRule = 'nonzero';
  4832. } else {
  4833. ctx.clip('evenodd');
  4834. }
  4835. } else {
  4836. ctx.clip();
  4837. }
  4838. this.pendingClip = null;
  4839. }
  4840. ctx.beginPath();
  4841. },
  4842. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  4843. if (this.cachedGetSinglePixelWidth === null) {
  4844. var inverse = this.ctx.mozCurrentTransformInverse;
  4845. // max of the current horizontal and vertical scale
  4846. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  4847. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  4848. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  4849. }
  4850. return this.cachedGetSinglePixelWidth;
  4851. },
  4852. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  4853. var transform = this.ctx.mozCurrentTransform;
  4854. return [
  4855. transform[0] * x + transform[2] * y + transform[4],
  4856. transform[1] * x + transform[3] * y + transform[5]
  4857. ];
  4858. }
  4859. };
  4860. for (var op in OPS) {
  4861. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  4862. }
  4863. return CanvasGraphics;
  4864. })();
  4865. var WebGLUtils = (function WebGLUtilsClosure() {
  4866. function loadShader(gl, code, shaderType) {
  4867. var shader = gl.createShader(shaderType);
  4868. gl.shaderSource(shader, code);
  4869. gl.compileShader(shader);
  4870. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4871. if (!compiled) {
  4872. var errorMsg = gl.getShaderInfoLog(shader);
  4873. throw new Error('Error during shader compilation: ' + errorMsg);
  4874. }
  4875. return shader;
  4876. }
  4877. function createVertexShader(gl, code) {
  4878. return loadShader(gl, code, gl.VERTEX_SHADER);
  4879. }
  4880. function createFragmentShader(gl, code) {
  4881. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4882. }
  4883. function createProgram(gl, shaders) {
  4884. var program = gl.createProgram();
  4885. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4886. gl.attachShader(program, shaders[i]);
  4887. }
  4888. gl.linkProgram(program);
  4889. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4890. if (!linked) {
  4891. var errorMsg = gl.getProgramInfoLog(program);
  4892. throw new Error('Error during program linking: ' + errorMsg);
  4893. }
  4894. return program;
  4895. }
  4896. function createTexture(gl, image, textureId) {
  4897. gl.activeTexture(textureId);
  4898. var texture = gl.createTexture();
  4899. gl.bindTexture(gl.TEXTURE_2D, texture);
  4900. // Set the parameters so we can render any size image.
  4901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4902. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4903. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4904. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4905. // Upload the image into the texture.
  4906. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4907. return texture;
  4908. }
  4909. var currentGL, currentCanvas;
  4910. function generateGL() {
  4911. if (currentGL) {
  4912. return;
  4913. }
  4914. currentCanvas = document.createElement('canvas');
  4915. currentGL = currentCanvas.getContext('webgl',
  4916. { premultipliedalpha: false });
  4917. }
  4918. var smaskVertexShaderCode = '\
  4919. attribute vec2 a_position; \
  4920. attribute vec2 a_texCoord; \
  4921. \
  4922. uniform vec2 u_resolution; \
  4923. \
  4924. varying vec2 v_texCoord; \
  4925. \
  4926. void main() { \
  4927. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4928. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4929. \
  4930. v_texCoord = a_texCoord; \
  4931. } ';
  4932. var smaskFragmentShaderCode = '\
  4933. precision mediump float; \
  4934. \
  4935. uniform vec4 u_backdrop; \
  4936. uniform int u_subtype; \
  4937. uniform sampler2D u_image; \
  4938. uniform sampler2D u_mask; \
  4939. \
  4940. varying vec2 v_texCoord; \
  4941. \
  4942. void main() { \
  4943. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4944. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4945. if (u_backdrop.a > 0.0) { \
  4946. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4947. u_backdrop.rgb * (1.0 - maskColor.a); \
  4948. } \
  4949. float lum; \
  4950. if (u_subtype == 0) { \
  4951. lum = maskColor.a; \
  4952. } else { \
  4953. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4954. maskColor.b * 0.11; \
  4955. } \
  4956. imageColor.a *= lum; \
  4957. imageColor.rgb *= imageColor.a; \
  4958. gl_FragColor = imageColor; \
  4959. } ';
  4960. var smaskCache = null;
  4961. function initSmaskGL() {
  4962. var canvas, gl;
  4963. generateGL();
  4964. canvas = currentCanvas;
  4965. currentCanvas = null;
  4966. gl = currentGL;
  4967. currentGL = null;
  4968. // setup a GLSL program
  4969. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  4970. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  4971. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4972. gl.useProgram(program);
  4973. var cache = {};
  4974. cache.gl = gl;
  4975. cache.canvas = canvas;
  4976. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4977. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4978. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  4979. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  4980. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  4981. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  4982. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  4983. // provide texture coordinates for the rectangle.
  4984. var texCoordBuffer = gl.createBuffer();
  4985. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  4986. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4987. 0.0, 0.0,
  4988. 1.0, 0.0,
  4989. 0.0, 1.0,
  4990. 0.0, 1.0,
  4991. 1.0, 0.0,
  4992. 1.0, 1.0]), gl.STATIC_DRAW);
  4993. gl.enableVertexAttribArray(texCoordLocation);
  4994. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  4995. gl.uniform1i(texLayerLocation, 0);
  4996. gl.uniform1i(texMaskLocation, 1);
  4997. smaskCache = cache;
  4998. }
  4999. function composeSMask(layer, mask, properties) {
  5000. var width = layer.width, height = layer.height;
  5001. if (!smaskCache) {
  5002. initSmaskGL();
  5003. }
  5004. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5005. canvas.width = width;
  5006. canvas.height = height;
  5007. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5008. gl.uniform2f(cache.resolutionLocation, width, height);
  5009. if (properties.backdrop) {
  5010. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5011. properties.backdrop[1], properties.backdrop[2], 1);
  5012. } else {
  5013. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5014. }
  5015. gl.uniform1i(cache.subtypeLocation,
  5016. properties.subtype === 'Luminosity' ? 1 : 0);
  5017. // Create a textures
  5018. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5019. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5020. // Create a buffer and put a single clipspace rectangle in
  5021. // it (2 triangles)
  5022. var buffer = gl.createBuffer();
  5023. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5024. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5025. 0, 0,
  5026. width, 0,
  5027. 0, height,
  5028. 0, height,
  5029. width, 0,
  5030. width, height]), gl.STATIC_DRAW);
  5031. gl.enableVertexAttribArray(cache.positionLocation);
  5032. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5033. // draw
  5034. gl.clearColor(0, 0, 0, 0);
  5035. gl.enable(gl.BLEND);
  5036. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5037. gl.clear(gl.COLOR_BUFFER_BIT);
  5038. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5039. gl.flush();
  5040. gl.deleteTexture(texture);
  5041. gl.deleteTexture(maskTexture);
  5042. gl.deleteBuffer(buffer);
  5043. return canvas;
  5044. }
  5045. var figuresVertexShaderCode = '\
  5046. attribute vec2 a_position; \
  5047. attribute vec3 a_color; \
  5048. \
  5049. uniform vec2 u_resolution; \
  5050. uniform vec2 u_scale; \
  5051. uniform vec2 u_offset; \
  5052. \
  5053. varying vec4 v_color; \
  5054. \
  5055. void main() { \
  5056. vec2 position = (a_position + u_offset) * u_scale; \
  5057. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5058. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5059. \
  5060. v_color = vec4(a_color / 255.0, 1.0); \
  5061. } ';
  5062. var figuresFragmentShaderCode = '\
  5063. precision mediump float; \
  5064. \
  5065. varying vec4 v_color; \
  5066. \
  5067. void main() { \
  5068. gl_FragColor = v_color; \
  5069. } ';
  5070. var figuresCache = null;
  5071. function initFiguresGL() {
  5072. var canvas, gl;
  5073. generateGL();
  5074. canvas = currentCanvas;
  5075. currentCanvas = null;
  5076. gl = currentGL;
  5077. currentGL = null;
  5078. // setup a GLSL program
  5079. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5080. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5081. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5082. gl.useProgram(program);
  5083. var cache = {};
  5084. cache.gl = gl;
  5085. cache.canvas = canvas;
  5086. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5087. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5088. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5089. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5090. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5091. figuresCache = cache;
  5092. }
  5093. function drawFigures(width, height, backgroundColor, figures, context) {
  5094. if (!figuresCache) {
  5095. initFiguresGL();
  5096. }
  5097. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5098. canvas.width = width;
  5099. canvas.height = height;
  5100. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5101. gl.uniform2f(cache.resolutionLocation, width, height);
  5102. // count triangle points
  5103. var count = 0;
  5104. var i, ii, rows;
  5105. for (i = 0, ii = figures.length; i < ii; i++) {
  5106. switch (figures[i].type) {
  5107. case 'lattice':
  5108. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5109. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5110. break;
  5111. case 'triangles':
  5112. count += figures[i].coords.length;
  5113. break;
  5114. }
  5115. }
  5116. // transfer data
  5117. var coords = new Float32Array(count * 2);
  5118. var colors = new Uint8Array(count * 3);
  5119. var coordsMap = context.coords, colorsMap = context.colors;
  5120. var pIndex = 0, cIndex = 0;
  5121. for (i = 0, ii = figures.length; i < ii; i++) {
  5122. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5123. switch (figure.type) {
  5124. case 'lattice':
  5125. var cols = figure.verticesPerRow;
  5126. rows = (ps.length / cols) | 0;
  5127. for (var row = 1; row < rows; row++) {
  5128. var offset = row * cols + 1;
  5129. for (var col = 1; col < cols; col++, offset++) {
  5130. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5131. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5132. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5133. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5134. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5135. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5136. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5137. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5138. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5139. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5140. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5141. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5142. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5143. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5144. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5145. coords[pIndex + 6] = coords[pIndex + 2];
  5146. coords[pIndex + 7] = coords[pIndex + 3];
  5147. coords[pIndex + 8] = coords[pIndex + 4];
  5148. coords[pIndex + 9] = coords[pIndex + 5];
  5149. coords[pIndex + 10] = coordsMap[ps[offset]];
  5150. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5151. colors[cIndex + 9] = colors[cIndex + 3];
  5152. colors[cIndex + 10] = colors[cIndex + 4];
  5153. colors[cIndex + 11] = colors[cIndex + 5];
  5154. colors[cIndex + 12] = colors[cIndex + 6];
  5155. colors[cIndex + 13] = colors[cIndex + 7];
  5156. colors[cIndex + 14] = colors[cIndex + 8];
  5157. colors[cIndex + 15] = colorsMap[cs[offset]];
  5158. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5159. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5160. pIndex += 12;
  5161. cIndex += 18;
  5162. }
  5163. }
  5164. break;
  5165. case 'triangles':
  5166. for (var j = 0, jj = ps.length; j < jj; j++) {
  5167. coords[pIndex] = coordsMap[ps[j]];
  5168. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5169. colors[cIndex] = colorsMap[cs[j]];
  5170. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5171. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5172. pIndex += 2;
  5173. cIndex += 3;
  5174. }
  5175. break;
  5176. }
  5177. }
  5178. // draw
  5179. if (backgroundColor) {
  5180. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5181. backgroundColor[2] / 255, 1.0);
  5182. } else {
  5183. gl.clearColor(0, 0, 0, 0);
  5184. }
  5185. gl.clear(gl.COLOR_BUFFER_BIT);
  5186. var coordsBuffer = gl.createBuffer();
  5187. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5188. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5189. gl.enableVertexAttribArray(cache.positionLocation);
  5190. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5191. var colorsBuffer = gl.createBuffer();
  5192. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5193. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5194. gl.enableVertexAttribArray(cache.colorLocation);
  5195. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5196. 0, 0);
  5197. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5198. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5199. gl.drawArrays(gl.TRIANGLES, 0, count);
  5200. gl.flush();
  5201. gl.deleteBuffer(coordsBuffer);
  5202. gl.deleteBuffer(colorsBuffer);
  5203. return canvas;
  5204. }
  5205. function cleanup() {
  5206. if (smaskCache && smaskCache.canvas) {
  5207. smaskCache.canvas.width = 0;
  5208. smaskCache.canvas.height = 0;
  5209. }
  5210. if (figuresCache && figuresCache.canvas) {
  5211. figuresCache.canvas.width = 0;
  5212. figuresCache.canvas.height = 0;
  5213. }
  5214. smaskCache = null;
  5215. figuresCache = null;
  5216. }
  5217. return {
  5218. get isEnabled() {
  5219. if (PDFJS.disableWebGL) {
  5220. return false;
  5221. }
  5222. var enabled = false;
  5223. try {
  5224. generateGL();
  5225. enabled = !!currentGL;
  5226. } catch (e) { }
  5227. return shadow(this, 'isEnabled', enabled);
  5228. },
  5229. composeSMask: composeSMask,
  5230. drawFigures: drawFigures,
  5231. clear: cleanup
  5232. };
  5233. })();
  5234. var ShadingIRs = {};
  5235. ShadingIRs.RadialAxial = {
  5236. fromIR: function RadialAxial_fromIR(raw) {
  5237. var type = raw[1];
  5238. var colorStops = raw[2];
  5239. var p0 = raw[3];
  5240. var p1 = raw[4];
  5241. var r0 = raw[5];
  5242. var r1 = raw[6];
  5243. return {
  5244. type: 'Pattern',
  5245. getPattern: function RadialAxial_getPattern(ctx) {
  5246. var grad;
  5247. if (type === 'axial') {
  5248. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5249. } else if (type === 'radial') {
  5250. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5251. }
  5252. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5253. var c = colorStops[i];
  5254. grad.addColorStop(c[0], c[1]);
  5255. }
  5256. return grad;
  5257. }
  5258. };
  5259. }
  5260. };
  5261. var createMeshCanvas = (function createMeshCanvasClosure() {
  5262. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5263. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5264. var coords = context.coords, colors = context.colors;
  5265. var bytes = data.data, rowSize = data.width * 4;
  5266. var tmp;
  5267. if (coords[p1 + 1] > coords[p2 + 1]) {
  5268. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5269. }
  5270. if (coords[p2 + 1] > coords[p3 + 1]) {
  5271. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5272. }
  5273. if (coords[p1 + 1] > coords[p2 + 1]) {
  5274. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5275. }
  5276. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5277. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5278. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5279. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5280. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5281. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5282. if (y1 >= y3) {
  5283. return;
  5284. }
  5285. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5286. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5287. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5288. var minY = Math.round(y1), maxY = Math.round(y3);
  5289. var xa, car, cag, cab;
  5290. var xb, cbr, cbg, cbb;
  5291. var k;
  5292. for (var y = minY; y <= maxY; y++) {
  5293. if (y < y2) {
  5294. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5295. xa = x1 - (x1 - x2) * k;
  5296. car = c1r - (c1r - c2r) * k;
  5297. cag = c1g - (c1g - c2g) * k;
  5298. cab = c1b - (c1b - c2b) * k;
  5299. } else {
  5300. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5301. xa = x2 - (x2 - x3) * k;
  5302. car = c2r - (c2r - c3r) * k;
  5303. cag = c2g - (c2g - c3g) * k;
  5304. cab = c2b - (c2b - c3b) * k;
  5305. }
  5306. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5307. xb = x1 - (x1 - x3) * k;
  5308. cbr = c1r - (c1r - c3r) * k;
  5309. cbg = c1g - (c1g - c3g) * k;
  5310. cbb = c1b - (c1b - c3b) * k;
  5311. var x1_ = Math.round(Math.min(xa, xb));
  5312. var x2_ = Math.round(Math.max(xa, xb));
  5313. var j = rowSize * y + x1_ * 4;
  5314. for (var x = x1_; x <= x2_; x++) {
  5315. k = (xa - x) / (xa - xb);
  5316. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5317. bytes[j++] = (car - (car - cbr) * k) | 0;
  5318. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5319. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5320. bytes[j++] = 255;
  5321. }
  5322. }
  5323. }
  5324. function drawFigure(data, figure, context) {
  5325. var ps = figure.coords;
  5326. var cs = figure.colors;
  5327. var i, ii;
  5328. switch (figure.type) {
  5329. case 'lattice':
  5330. var verticesPerRow = figure.verticesPerRow;
  5331. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5332. var cols = verticesPerRow - 1;
  5333. for (i = 0; i < rows; i++) {
  5334. var q = i * verticesPerRow;
  5335. for (var j = 0; j < cols; j++, q++) {
  5336. drawTriangle(data, context,
  5337. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5338. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5339. drawTriangle(data, context,
  5340. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5341. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5342. }
  5343. }
  5344. break;
  5345. case 'triangles':
  5346. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5347. drawTriangle(data, context,
  5348. ps[i], ps[i + 1], ps[i + 2],
  5349. cs[i], cs[i + 1], cs[i + 2]);
  5350. }
  5351. break;
  5352. default:
  5353. error('illigal figure');
  5354. break;
  5355. }
  5356. }
  5357. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5358. backgroundColor) {
  5359. // we will increase scale on some weird factor to let antialiasing take
  5360. // care of "rough" edges
  5361. var EXPECTED_SCALE = 1.1;
  5362. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5363. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5364. var offsetX = Math.floor(bounds[0]);
  5365. var offsetY = Math.floor(bounds[1]);
  5366. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5367. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5368. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5369. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5370. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5371. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5372. var scaleX = boundsWidth / width;
  5373. var scaleY = boundsHeight / height;
  5374. var context = {
  5375. coords: coords,
  5376. colors: colors,
  5377. offsetX: -offsetX,
  5378. offsetY: -offsetY,
  5379. scaleX: 1 / scaleX,
  5380. scaleY: 1 / scaleY
  5381. };
  5382. var canvas, tmpCanvas, i, ii;
  5383. if (WebGLUtils.isEnabled) {
  5384. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5385. figures, context);
  5386. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5387. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5388. tmpCanvas.context.drawImage(canvas, 0, 0);
  5389. canvas = tmpCanvas.canvas;
  5390. } else {
  5391. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5392. var tmpCtx = tmpCanvas.context;
  5393. var data = tmpCtx.createImageData(width, height);
  5394. if (backgroundColor) {
  5395. var bytes = data.data;
  5396. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5397. bytes[i] = backgroundColor[0];
  5398. bytes[i + 1] = backgroundColor[1];
  5399. bytes[i + 2] = backgroundColor[2];
  5400. bytes[i + 3] = 255;
  5401. }
  5402. }
  5403. for (i = 0; i < figures.length; i++) {
  5404. drawFigure(data, figures[i], context);
  5405. }
  5406. tmpCtx.putImageData(data, 0, 0);
  5407. canvas = tmpCanvas.canvas;
  5408. }
  5409. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5410. scaleX: scaleX, scaleY: scaleY};
  5411. }
  5412. return createMeshCanvas;
  5413. })();
  5414. ShadingIRs.Mesh = {
  5415. fromIR: function Mesh_fromIR(raw) {
  5416. //var type = raw[1];
  5417. var coords = raw[2];
  5418. var colors = raw[3];
  5419. var figures = raw[4];
  5420. var bounds = raw[5];
  5421. var matrix = raw[6];
  5422. //var bbox = raw[7];
  5423. var background = raw[8];
  5424. return {
  5425. type: 'Pattern',
  5426. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5427. var scale;
  5428. if (shadingFill) {
  5429. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5430. } else {
  5431. // Obtain scale from matrix and current transformation matrix.
  5432. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5433. if (matrix) {
  5434. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5435. scale = [scale[0] * matrixScale[0],
  5436. scale[1] * matrixScale[1]];
  5437. }
  5438. }
  5439. // Rasterizing on the main thread since sending/queue large canvases
  5440. // might cause OOM.
  5441. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5442. colors, figures, shadingFill ? null : background);
  5443. if (!shadingFill) {
  5444. ctx.setTransform.apply(ctx, owner.baseTransform);
  5445. if (matrix) {
  5446. ctx.transform.apply(ctx, matrix);
  5447. }
  5448. }
  5449. ctx.translate(temporaryPatternCanvas.offsetX,
  5450. temporaryPatternCanvas.offsetY);
  5451. ctx.scale(temporaryPatternCanvas.scaleX,
  5452. temporaryPatternCanvas.scaleY);
  5453. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5454. }
  5455. };
  5456. }
  5457. };
  5458. ShadingIRs.Dummy = {
  5459. fromIR: function Dummy_fromIR() {
  5460. return {
  5461. type: 'Pattern',
  5462. getPattern: function Dummy_fromIR_getPattern() {
  5463. return 'hotpink';
  5464. }
  5465. };
  5466. }
  5467. };
  5468. function getShadingPatternFromIR(raw) {
  5469. var shadingIR = ShadingIRs[raw[0]];
  5470. if (!shadingIR) {
  5471. error('Unknown IR type: ' + raw[0]);
  5472. }
  5473. return shadingIR.fromIR(raw);
  5474. }
  5475. var TilingPattern = (function TilingPatternClosure() {
  5476. var PaintType = {
  5477. COLORED: 1,
  5478. UNCOLORED: 2
  5479. };
  5480. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5481. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5482. this.operatorList = IR[2];
  5483. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5484. this.bbox = IR[4];
  5485. this.xstep = IR[5];
  5486. this.ystep = IR[6];
  5487. this.paintType = IR[7];
  5488. this.tilingType = IR[8];
  5489. this.color = color;
  5490. this.objs = objs;
  5491. this.commonObjs = commonObjs;
  5492. this.baseTransform = baseTransform;
  5493. this.type = 'Pattern';
  5494. this.ctx = ctx;
  5495. }
  5496. TilingPattern.prototype = {
  5497. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5498. var operatorList = this.operatorList;
  5499. var bbox = this.bbox;
  5500. var xstep = this.xstep;
  5501. var ystep = this.ystep;
  5502. var paintType = this.paintType;
  5503. var tilingType = this.tilingType;
  5504. var color = this.color;
  5505. var objs = this.objs;
  5506. var commonObjs = this.commonObjs;
  5507. info('TilingType: ' + tilingType);
  5508. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5509. var topLeft = [x0, y0];
  5510. // we want the canvas to be as large as the step size
  5511. var botRight = [x0 + xstep, y0 + ystep];
  5512. var width = botRight[0] - topLeft[0];
  5513. var height = botRight[1] - topLeft[1];
  5514. // Obtain scale from matrix and current transformation matrix.
  5515. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5516. var curMatrixScale = Util.singularValueDecompose2dScale(
  5517. this.baseTransform);
  5518. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5519. matrixScale[1] * curMatrixScale[1]];
  5520. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5521. // Use width and height values that are as close as possible to the end
  5522. // result when the pattern is used. Too low value makes the pattern look
  5523. // blurry. Too large value makes it look too crispy.
  5524. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5525. MAX_PATTERN_SIZE);
  5526. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5527. MAX_PATTERN_SIZE);
  5528. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  5529. var tmpCtx = tmpCanvas.context;
  5530. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5531. graphics.groupLevel = owner.groupLevel;
  5532. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5533. this.setScale(width, height, xstep, ystep);
  5534. this.transformToScale(graphics);
  5535. // transform coordinates to pattern space
  5536. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5537. graphics.transform.apply(graphics, tmpTranslate);
  5538. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5539. graphics.executeOperatorList(operatorList);
  5540. return tmpCanvas.canvas;
  5541. },
  5542. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5543. this.scale = [width / xstep, height / ystep];
  5544. },
  5545. transformToScale: function TilingPattern_transformToScale(graphics) {
  5546. var scale = this.scale;
  5547. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5548. graphics.transform.apply(graphics, tmpScale);
  5549. },
  5550. scaleToContext: function TilingPattern_scaleToContext() {
  5551. var scale = this.scale;
  5552. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5553. },
  5554. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5555. if (bbox && isArray(bbox) && bbox.length === 4) {
  5556. var bboxWidth = x1 - x0;
  5557. var bboxHeight = y1 - y0;
  5558. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5559. graphics.clip();
  5560. graphics.endPath();
  5561. }
  5562. },
  5563. setFillAndStrokeStyleToContext:
  5564. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5565. switch (paintType) {
  5566. case PaintType.COLORED:
  5567. var ctx = this.ctx;
  5568. context.fillStyle = ctx.fillStyle;
  5569. context.strokeStyle = ctx.strokeStyle;
  5570. break;
  5571. case PaintType.UNCOLORED:
  5572. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5573. context.fillStyle = cssColor;
  5574. context.strokeStyle = cssColor;
  5575. break;
  5576. default:
  5577. error('Unsupported paint type: ' + paintType);
  5578. }
  5579. },
  5580. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5581. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5582. ctx = this.ctx;
  5583. ctx.setTransform.apply(ctx, this.baseTransform);
  5584. ctx.transform.apply(ctx, this.matrix);
  5585. this.scaleToContext();
  5586. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5587. }
  5588. };
  5589. return TilingPattern;
  5590. })();
  5591. PDFJS.disableFontFace = false;
  5592. var FontLoader = {
  5593. insertRule: function fontLoaderInsertRule(rule) {
  5594. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5595. if (!styleElement) {
  5596. styleElement = document.createElement('style');
  5597. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  5598. document.documentElement.getElementsByTagName('head')[0].appendChild(
  5599. styleElement);
  5600. }
  5601. var styleSheet = styleElement.sheet;
  5602. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5603. },
  5604. clear: function fontLoaderClear() {
  5605. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5606. if (styleElement) {
  5607. styleElement.parentNode.removeChild(styleElement);
  5608. }
  5609. this.nativeFontFaces.forEach(function(nativeFontFace) {
  5610. document.fonts.delete(nativeFontFace);
  5611. });
  5612. this.nativeFontFaces.length = 0;
  5613. },
  5614. get loadTestFont() {
  5615. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  5616. // height.
  5617. return shadow(this, 'loadTestFont', atob(
  5618. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  5619. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  5620. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  5621. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  5622. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  5623. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  5624. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  5625. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  5626. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  5627. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  5628. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  5629. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  5630. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  5631. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5632. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5633. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5634. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  5635. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  5636. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  5637. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  5638. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  5639. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  5640. ));
  5641. },
  5642. get isEvalSupported() {
  5643. var evalSupport = false;
  5644. if (PDFJS.isEvalSupported) {
  5645. try {
  5646. /* jshint evil: true */
  5647. new Function('');
  5648. evalSupport = true;
  5649. } catch (e) {}
  5650. }
  5651. return shadow(this, 'isEvalSupported', evalSupport);
  5652. },
  5653. loadTestFontId: 0,
  5654. loadingContext: {
  5655. requests: [],
  5656. nextRequestId: 0
  5657. },
  5658. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  5659. if (isWorker) {
  5660. return false;
  5661. }
  5662. // User agent string sniffing is bad, but there is no reliable way to tell
  5663. // if font is fully loaded and ready to be used with canvas.
  5664. var userAgent = window.navigator.userAgent;
  5665. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  5666. if (m && m[1] >= 14) {
  5667. return true;
  5668. }
  5669. // TODO other browsers
  5670. if (userAgent === 'node') {
  5671. return true;
  5672. }
  5673. return false;
  5674. })(),
  5675. nativeFontFaces: [],
  5676. isFontLoadingAPISupported: (!isWorker && typeof document !== 'undefined' &&
  5677. !!document.fonts),
  5678. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  5679. this.nativeFontFaces.push(nativeFontFace);
  5680. document.fonts.add(nativeFontFace);
  5681. },
  5682. bind: function fontLoaderBind(fonts, callback) {
  5683. assert(!isWorker, 'bind() shall be called from main thread');
  5684. var rules = [];
  5685. var fontsToLoad = [];
  5686. var fontLoadPromises = [];
  5687. var getNativeFontPromise = function(nativeFontFace) {
  5688. // Return a promise that is always fulfilled, even when the font fails to
  5689. // load.
  5690. return nativeFontFace.loaded.catch(function(e) {
  5691. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  5692. });
  5693. };
  5694. for (var i = 0, ii = fonts.length; i < ii; i++) {
  5695. var font = fonts[i];
  5696. // Add the font to the DOM only once or skip if the font
  5697. // is already loaded.
  5698. if (font.attached || font.loading === false) {
  5699. continue;
  5700. }
  5701. font.attached = true;
  5702. if (this.isFontLoadingAPISupported) {
  5703. var nativeFontFace = font.createNativeFontFace();
  5704. if (nativeFontFace) {
  5705. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  5706. }
  5707. } else {
  5708. var rule = font.bindDOM();
  5709. if (rule) {
  5710. rules.push(rule);
  5711. fontsToLoad.push(font);
  5712. }
  5713. }
  5714. }
  5715. var request = FontLoader.queueLoadingCallback(callback);
  5716. if (this.isFontLoadingAPISupported) {
  5717. Promise.all(fontLoadPromises).then(function() {
  5718. request.complete();
  5719. });
  5720. } else if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  5721. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  5722. } else {
  5723. request.complete();
  5724. }
  5725. },
  5726. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  5727. function LoadLoader_completeRequest() {
  5728. assert(!request.end, 'completeRequest() cannot be called twice');
  5729. request.end = Date.now();
  5730. // sending all completed requests in order how they were queued
  5731. while (context.requests.length > 0 && context.requests[0].end) {
  5732. var otherRequest = context.requests.shift();
  5733. setTimeout(otherRequest.callback, 0);
  5734. }
  5735. }
  5736. var context = FontLoader.loadingContext;
  5737. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  5738. var request = {
  5739. id: requestId,
  5740. complete: LoadLoader_completeRequest,
  5741. callback: callback,
  5742. started: Date.now()
  5743. };
  5744. context.requests.push(request);
  5745. return request;
  5746. },
  5747. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  5748. fonts,
  5749. request) {
  5750. /** Hack begin */
  5751. // There's currently no event when a font has finished downloading so the
  5752. // following code is a dirty hack to 'guess' when a font is
  5753. // ready. It's assumed fonts are loaded in order, so add a known test
  5754. // font after the desired fonts and then test for the loading of that
  5755. // test font.
  5756. function int32(data, offset) {
  5757. return (data.charCodeAt(offset) << 24) |
  5758. (data.charCodeAt(offset + 1) << 16) |
  5759. (data.charCodeAt(offset + 2) << 8) |
  5760. (data.charCodeAt(offset + 3) & 0xff);
  5761. }
  5762. function spliceString(s, offset, remove, insert) {
  5763. var chunk1 = s.substr(0, offset);
  5764. var chunk2 = s.substr(offset + remove);
  5765. return chunk1 + insert + chunk2;
  5766. }
  5767. var i, ii;
  5768. var canvas = document.createElement('canvas');
  5769. canvas.width = 1;
  5770. canvas.height = 1;
  5771. var ctx = canvas.getContext('2d');
  5772. var called = 0;
  5773. function isFontReady(name, callback) {
  5774. called++;
  5775. // With setTimeout clamping this gives the font ~100ms to load.
  5776. if(called > 30) {
  5777. warn('Load test font never loaded.');
  5778. callback();
  5779. return;
  5780. }
  5781. ctx.font = '30px ' + name;
  5782. ctx.fillText('.', 0, 20);
  5783. var imageData = ctx.getImageData(0, 0, 1, 1);
  5784. if (imageData.data[3] > 0) {
  5785. callback();
  5786. return;
  5787. }
  5788. setTimeout(isFontReady.bind(null, name, callback));
  5789. }
  5790. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  5791. // Chromium seems to cache fonts based on a hash of the actual font data,
  5792. // so the font must be modified for each load test else it will appear to
  5793. // be loaded already.
  5794. // TODO: This could maybe be made faster by avoiding the btoa of the full
  5795. // font by splitting it in chunks before hand and padding the font id.
  5796. var data = this.loadTestFont;
  5797. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  5798. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  5799. loadTestFontId);
  5800. // CFF checksum is important for IE, adjusting it
  5801. var CFF_CHECKSUM_OFFSET = 16;
  5802. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  5803. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5804. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5805. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  5806. }
  5807. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  5808. checksum = (checksum - XXXX_VALUE +
  5809. int32(loadTestFontId + 'XXX', i)) | 0;
  5810. }
  5811. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  5812. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  5813. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  5814. url + '}';
  5815. FontLoader.insertRule(rule);
  5816. var names = [];
  5817. for (i = 0, ii = fonts.length; i < ii; i++) {
  5818. names.push(fonts[i].loadedName);
  5819. }
  5820. names.push(loadTestFontId);
  5821. var div = document.createElement('div');
  5822. div.setAttribute('style',
  5823. 'visibility: hidden;' +
  5824. 'width: 10px; height: 10px;' +
  5825. 'position: absolute; top: 0px; left: 0px;');
  5826. for (i = 0, ii = names.length; i < ii; ++i) {
  5827. var span = document.createElement('span');
  5828. span.textContent = 'Hi';
  5829. span.style.fontFamily = names[i];
  5830. div.appendChild(span);
  5831. }
  5832. document.body.appendChild(div);
  5833. isFontReady(loadTestFontId, function() {
  5834. document.body.removeChild(div);
  5835. request.complete();
  5836. });
  5837. /** Hack end */
  5838. }
  5839. };
  5840. var FontFaceObject = (function FontFaceObjectClosure() {
  5841. function FontFaceObject(name, file, properties) {
  5842. this.compiledGlyphs = {};
  5843. if (arguments.length === 1) {
  5844. // importing translated data
  5845. var data = arguments[0];
  5846. for (var i in data) {
  5847. this[i] = data[i];
  5848. }
  5849. return;
  5850. }
  5851. }
  5852. FontFaceObject.prototype = {
  5853. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  5854. if (!this.data) {
  5855. return null;
  5856. }
  5857. if (PDFJS.disableFontFace) {
  5858. this.disableFontFace = true;
  5859. return null;
  5860. }
  5861. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  5862. FontLoader.addNativeFontFace(nativeFontFace);
  5863. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5864. globalScope['FontInspector'].enabled) {
  5865. globalScope['FontInspector'].fontAdded(this);
  5866. }
  5867. return nativeFontFace;
  5868. },
  5869. bindDOM: function FontFaceObject_bindDOM() {
  5870. if (!this.data) {
  5871. return null;
  5872. }
  5873. if (PDFJS.disableFontFace) {
  5874. this.disableFontFace = true;
  5875. return null;
  5876. }
  5877. var data = bytesToString(new Uint8Array(this.data));
  5878. var fontName = this.loadedName;
  5879. // Add the font-face rule to the document
  5880. var url = ('url(data:' + this.mimetype + ';base64,' +
  5881. window.btoa(data) + ');');
  5882. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  5883. FontLoader.insertRule(rule);
  5884. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5885. globalScope['FontInspector'].enabled) {
  5886. globalScope['FontInspector'].fontAdded(this, url);
  5887. }
  5888. return rule;
  5889. },
  5890. getPathGenerator: function FontLoader_getPathGenerator(objs, character) {
  5891. if (!(character in this.compiledGlyphs)) {
  5892. var cmds = objs.get(this.loadedName + '_path_' + character);
  5893. var current, i, len;
  5894. // If we can, compile cmds into JS for MAXIMUM SPEED
  5895. if (FontLoader.isEvalSupported) {
  5896. var args, js = '';
  5897. for (i = 0, len = cmds.length; i < len; i++) {
  5898. current = cmds[i];
  5899. if (current.args !== undefined) {
  5900. args = current.args.join(',');
  5901. } else {
  5902. args = '';
  5903. }
  5904. js += 'c.' + current.cmd + '(' + args + ');\n';
  5905. }
  5906. /* jshint -W054 */
  5907. this.compiledGlyphs[character] = new Function('c', 'size', js);
  5908. } else {
  5909. // But fall back on using Function.prototype.apply() if we're
  5910. // blocked from using eval() for whatever reason (like CSP policies)
  5911. this.compiledGlyphs[character] = function(c, size) {
  5912. for (i = 0, len = cmds.length; i < len; i++) {
  5913. current = cmds[i];
  5914. if (current.cmd === 'scale') {
  5915. current.args = [size, -size];
  5916. }
  5917. c[current.cmd].apply(c, current.args);
  5918. }
  5919. };
  5920. }
  5921. }
  5922. return this.compiledGlyphs[character];
  5923. }
  5924. };
  5925. return FontFaceObject;
  5926. })();
  5927. var ANNOT_MIN_SIZE = 10; // px
  5928. var AnnotationUtils = (function AnnotationUtilsClosure() {
  5929. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  5930. function setTextStyles(element, item, fontObj) {
  5931. var style = element.style;
  5932. style.fontSize = item.fontSize + 'px';
  5933. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  5934. if (!fontObj) {
  5935. return;
  5936. }
  5937. style.fontWeight = fontObj.black ?
  5938. (fontObj.bold ? 'bolder' : 'bold') :
  5939. (fontObj.bold ? 'bold' : 'normal');
  5940. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  5941. var fontName = fontObj.loadedName;
  5942. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  5943. // Use a reasonable default font if the font doesn't specify a fallback
  5944. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  5945. style.fontFamily = fontFamily + fallbackName;
  5946. }
  5947. function initContainer(item) {
  5948. var container = document.createElement('section');
  5949. var cstyle = container.style;
  5950. var width = item.rect[2] - item.rect[0];
  5951. var height = item.rect[3] - item.rect[1];
  5952. // Border
  5953. if (item.borderStyle.width > 0) {
  5954. // Border width
  5955. container.style.borderWidth = item.borderStyle.width + 'px';
  5956. if (item.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  5957. // Underline styles only have a bottom border, so we do not need
  5958. // to adjust for all borders. This yields a similar result as
  5959. // Adobe Acrobat/Reader.
  5960. width = width - 2 * item.borderStyle.width;
  5961. height = height - 2 * item.borderStyle.width;
  5962. }
  5963. // Horizontal and vertical border radius
  5964. var horizontalRadius = item.borderStyle.horizontalCornerRadius;
  5965. var verticalRadius = item.borderStyle.verticalCornerRadius;
  5966. if (horizontalRadius > 0 || verticalRadius > 0) {
  5967. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  5968. CustomStyle.setProp('borderRadius', container, radius);
  5969. }
  5970. // Border style
  5971. switch (item.borderStyle.style) {
  5972. case AnnotationBorderStyleType.SOLID:
  5973. container.style.borderStyle = 'solid';
  5974. break;
  5975. case AnnotationBorderStyleType.DASHED:
  5976. container.style.borderStyle = 'dashed';
  5977. break;
  5978. case AnnotationBorderStyleType.BEVELED:
  5979. warn('Unimplemented border style: beveled');
  5980. break;
  5981. case AnnotationBorderStyleType.INSET:
  5982. warn('Unimplemented border style: inset');
  5983. break;
  5984. case AnnotationBorderStyleType.UNDERLINE:
  5985. container.style.borderBottomStyle = 'solid';
  5986. break;
  5987. default:
  5988. break;
  5989. }
  5990. // Border color
  5991. if (item.color) {
  5992. container.style.borderColor =
  5993. Util.makeCssRgb(item.color[0] | 0,
  5994. item.color[1] | 0,
  5995. item.color[2] | 0);
  5996. } else {
  5997. // Transparent (invisible) border, so do not draw it at all.
  5998. container.style.borderWidth = 0;
  5999. }
  6000. }
  6001. cstyle.width = width + 'px';
  6002. cstyle.height = height + 'px';
  6003. return container;
  6004. }
  6005. function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
  6006. var element = document.createElement('div');
  6007. var width = item.rect[2] - item.rect[0];
  6008. var height = item.rect[3] - item.rect[1];
  6009. element.style.width = width + 'px';
  6010. element.style.height = height + 'px';
  6011. element.style.display = 'table';
  6012. var content = document.createElement('div');
  6013. content.textContent = item.fieldValue;
  6014. var textAlignment = item.textAlignment;
  6015. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  6016. content.style.verticalAlign = 'middle';
  6017. content.style.display = 'table-cell';
  6018. var fontObj = item.fontRefName ?
  6019. commonObjs.getData(item.fontRefName) : null;
  6020. setTextStyles(content, item, fontObj);
  6021. element.appendChild(content);
  6022. return element;
  6023. }
  6024. function getHtmlElementForTextAnnotation(item) {
  6025. var rect = item.rect;
  6026. // sanity check because of OOo-generated PDFs
  6027. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  6028. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  6029. }
  6030. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  6031. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  6032. }
  6033. var container = initContainer(item);
  6034. container.className = 'annotText';
  6035. var image = document.createElement('img');
  6036. image.style.height = container.style.height;
  6037. image.style.width = container.style.width;
  6038. var iconName = item.name;
  6039. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  6040. iconName.toLowerCase() + '.svg';
  6041. image.alt = '[{{type}} Annotation]';
  6042. image.dataset.l10nId = 'text_annotation_type';
  6043. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  6044. var contentWrapper = document.createElement('div');
  6045. contentWrapper.className = 'annotTextContentWrapper';
  6046. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  6047. contentWrapper.style.top = '-10px';
  6048. var content = document.createElement('div');
  6049. content.className = 'annotTextContent';
  6050. content.setAttribute('hidden', true);
  6051. var i, ii;
  6052. if (item.hasBgColor && item.color) {
  6053. var color = item.color;
  6054. // Enlighten the color (70%)
  6055. var BACKGROUND_ENLIGHT = 0.7;
  6056. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  6057. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  6058. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  6059. content.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  6060. }
  6061. var title = document.createElement('h1');
  6062. var text = document.createElement('p');
  6063. title.textContent = item.title;
  6064. if (!item.content && !item.title) {
  6065. content.setAttribute('hidden', true);
  6066. } else {
  6067. var e = document.createElement('span');
  6068. var lines = item.content.split(/(?:\r\n?|\n)/);
  6069. for (i = 0, ii = lines.length; i < ii; ++i) {
  6070. var line = lines[i];
  6071. e.appendChild(document.createTextNode(line));
  6072. if (i < (ii - 1)) {
  6073. e.appendChild(document.createElement('br'));
  6074. }
  6075. }
  6076. text.appendChild(e);
  6077. var pinned = false;
  6078. var showAnnotation = function showAnnotation(pin) {
  6079. if (pin) {
  6080. pinned = true;
  6081. }
  6082. if (content.hasAttribute('hidden')) {
  6083. container.style.zIndex += 1;
  6084. content.removeAttribute('hidden');
  6085. }
  6086. };
  6087. var hideAnnotation = function hideAnnotation(unpin) {
  6088. if (unpin) {
  6089. pinned = false;
  6090. }
  6091. if (!content.hasAttribute('hidden') && !pinned) {
  6092. container.style.zIndex -= 1;
  6093. content.setAttribute('hidden', true);
  6094. }
  6095. };
  6096. var toggleAnnotation = function toggleAnnotation() {
  6097. if (pinned) {
  6098. hideAnnotation(true);
  6099. } else {
  6100. showAnnotation(true);
  6101. }
  6102. };
  6103. image.addEventListener('click', function image_clickHandler() {
  6104. toggleAnnotation();
  6105. }, false);
  6106. image.addEventListener('mouseover', function image_mouseOverHandler() {
  6107. showAnnotation();
  6108. }, false);
  6109. image.addEventListener('mouseout', function image_mouseOutHandler() {
  6110. hideAnnotation();
  6111. }, false);
  6112. content.addEventListener('click', function content_clickHandler() {
  6113. hideAnnotation(true);
  6114. }, false);
  6115. }
  6116. content.appendChild(title);
  6117. content.appendChild(text);
  6118. contentWrapper.appendChild(content);
  6119. container.appendChild(image);
  6120. container.appendChild(contentWrapper);
  6121. return container;
  6122. }
  6123. function getHtmlElementForLinkAnnotation(item) {
  6124. var container = initContainer(item);
  6125. container.className = 'annotLink';
  6126. var link = document.createElement('a');
  6127. link.href = link.title = item.url || '';
  6128. if (item.url && isExternalLinkTargetSet()) {
  6129. link.target = LinkTargetStringMap[PDFJS.externalLinkTarget];
  6130. }
  6131. container.appendChild(link);
  6132. return container;
  6133. }
  6134. function getHtmlElement(data, objs) {
  6135. switch (data.annotationType) {
  6136. case AnnotationType.WIDGET:
  6137. return getHtmlElementForTextWidgetAnnotation(data, objs);
  6138. case AnnotationType.TEXT:
  6139. return getHtmlElementForTextAnnotation(data);
  6140. case AnnotationType.LINK:
  6141. return getHtmlElementForLinkAnnotation(data);
  6142. default:
  6143. throw new Error('Unsupported annotationType: ' + data.annotationType);
  6144. }
  6145. }
  6146. return {
  6147. getHtmlElement: getHtmlElement
  6148. };
  6149. })();
  6150. PDFJS.AnnotationUtils = AnnotationUtils;
  6151. var SVG_DEFAULTS = {
  6152. fontStyle: 'normal',
  6153. fontWeight: 'normal',
  6154. fillColor: '#000000'
  6155. };
  6156. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  6157. var PNG_HEADER =
  6158. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  6159. var CHUNK_WRAPPER_SIZE = 12;
  6160. var crcTable = new Int32Array(256);
  6161. for (var i = 0; i < 256; i++) {
  6162. var c = i;
  6163. for (var h = 0; h < 8; h++) {
  6164. if (c & 1) {
  6165. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  6166. } else {
  6167. c = (c >> 1) & 0x7fffffff;
  6168. }
  6169. }
  6170. crcTable[i] = c;
  6171. }
  6172. function crc32(data, start, end) {
  6173. var crc = -1;
  6174. for (var i = start; i < end; i++) {
  6175. var a = (crc ^ data[i]) & 0xff;
  6176. var b = crcTable[a];
  6177. crc = (crc >>> 8) ^ b;
  6178. }
  6179. return crc ^ -1;
  6180. }
  6181. function writePngChunk(type, body, data, offset) {
  6182. var p = offset;
  6183. var len = body.length;
  6184. data[p] = len >> 24 & 0xff;
  6185. data[p + 1] = len >> 16 & 0xff;
  6186. data[p + 2] = len >> 8 & 0xff;
  6187. data[p + 3] = len & 0xff;
  6188. p += 4;
  6189. data[p] = type.charCodeAt(0) & 0xff;
  6190. data[p + 1] = type.charCodeAt(1) & 0xff;
  6191. data[p + 2] = type.charCodeAt(2) & 0xff;
  6192. data[p + 3] = type.charCodeAt(3) & 0xff;
  6193. p += 4;
  6194. data.set(body, p);
  6195. p += body.length;
  6196. var crc = crc32(data, offset + 4, p);
  6197. data[p] = crc >> 24 & 0xff;
  6198. data[p + 1] = crc >> 16 & 0xff;
  6199. data[p + 2] = crc >> 8 & 0xff;
  6200. data[p + 3] = crc & 0xff;
  6201. }
  6202. function adler32(data, start, end) {
  6203. var a = 1;
  6204. var b = 0;
  6205. for (var i = start; i < end; ++i) {
  6206. a = (a + (data[i] & 0xff)) % 65521;
  6207. b = (b + a) % 65521;
  6208. }
  6209. return (b << 16) | a;
  6210. }
  6211. function encode(imgData, kind) {
  6212. var width = imgData.width;
  6213. var height = imgData.height;
  6214. var bitDepth, colorType, lineSize;
  6215. var bytes = imgData.data;
  6216. switch (kind) {
  6217. case ImageKind.GRAYSCALE_1BPP:
  6218. colorType = 0;
  6219. bitDepth = 1;
  6220. lineSize = (width + 7) >> 3;
  6221. break;
  6222. case ImageKind.RGB_24BPP:
  6223. colorType = 2;
  6224. bitDepth = 8;
  6225. lineSize = width * 3;
  6226. break;
  6227. case ImageKind.RGBA_32BPP:
  6228. colorType = 6;
  6229. bitDepth = 8;
  6230. lineSize = width * 4;
  6231. break;
  6232. default:
  6233. throw new Error('invalid format');
  6234. }
  6235. // prefix every row with predictor 0
  6236. var literals = new Uint8Array((1 + lineSize) * height);
  6237. var offsetLiterals = 0, offsetBytes = 0;
  6238. var y, i;
  6239. for (y = 0; y < height; ++y) {
  6240. literals[offsetLiterals++] = 0; // no prediction
  6241. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  6242. offsetLiterals);
  6243. offsetBytes += lineSize;
  6244. offsetLiterals += lineSize;
  6245. }
  6246. if (kind === ImageKind.GRAYSCALE_1BPP) {
  6247. // inverting for B/W
  6248. offsetLiterals = 0;
  6249. for (y = 0; y < height; y++) {
  6250. offsetLiterals++; // skipping predictor
  6251. for (i = 0; i < lineSize; i++) {
  6252. literals[offsetLiterals++] ^= 0xFF;
  6253. }
  6254. }
  6255. }
  6256. var ihdr = new Uint8Array([
  6257. width >> 24 & 0xff,
  6258. width >> 16 & 0xff,
  6259. width >> 8 & 0xff,
  6260. width & 0xff,
  6261. height >> 24 & 0xff,
  6262. height >> 16 & 0xff,
  6263. height >> 8 & 0xff,
  6264. height & 0xff,
  6265. bitDepth, // bit depth
  6266. colorType, // color type
  6267. 0x00, // compression method
  6268. 0x00, // filter method
  6269. 0x00 // interlace method
  6270. ]);
  6271. var len = literals.length;
  6272. var maxBlockLength = 0xFFFF;
  6273. var deflateBlocks = Math.ceil(len / maxBlockLength);
  6274. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  6275. var pi = 0;
  6276. idat[pi++] = 0x78; // compression method and flags
  6277. idat[pi++] = 0x9c; // flags
  6278. var pos = 0;
  6279. while (len > maxBlockLength) {
  6280. // writing non-final DEFLATE blocks type 0 and length of 65535
  6281. idat[pi++] = 0x00;
  6282. idat[pi++] = 0xff;
  6283. idat[pi++] = 0xff;
  6284. idat[pi++] = 0x00;
  6285. idat[pi++] = 0x00;
  6286. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  6287. pi += maxBlockLength;
  6288. pos += maxBlockLength;
  6289. len -= maxBlockLength;
  6290. }
  6291. // writing non-final DEFLATE blocks type 0
  6292. idat[pi++] = 0x01;
  6293. idat[pi++] = len & 0xff;
  6294. idat[pi++] = len >> 8 & 0xff;
  6295. idat[pi++] = (~len & 0xffff) & 0xff;
  6296. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  6297. idat.set(literals.subarray(pos), pi);
  6298. pi += literals.length - pos;
  6299. var adler = adler32(literals, 0, literals.length); // checksum
  6300. idat[pi++] = adler >> 24 & 0xff;
  6301. idat[pi++] = adler >> 16 & 0xff;
  6302. idat[pi++] = adler >> 8 & 0xff;
  6303. idat[pi++] = adler & 0xff;
  6304. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  6305. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  6306. ihdr.length + idat.length;
  6307. var data = new Uint8Array(pngLength);
  6308. var offset = 0;
  6309. data.set(PNG_HEADER, offset);
  6310. offset += PNG_HEADER.length;
  6311. writePngChunk('IHDR', ihdr, data, offset);
  6312. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  6313. writePngChunk('IDATA', idat, data, offset);
  6314. offset += CHUNK_WRAPPER_SIZE + idat.length;
  6315. writePngChunk('IEND', new Uint8Array(0), data, offset);
  6316. return PDFJS.createObjectURL(data, 'image/png');
  6317. }
  6318. return function convertImgDataToPng(imgData) {
  6319. var kind = (imgData.kind === undefined ?
  6320. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  6321. return encode(imgData, kind);
  6322. };
  6323. })();
  6324. var SVGExtraState = (function SVGExtraStateClosure() {
  6325. function SVGExtraState() {
  6326. this.fontSizeScale = 1;
  6327. this.fontWeight = SVG_DEFAULTS.fontWeight;
  6328. this.fontSize = 0;
  6329. this.textMatrix = IDENTITY_MATRIX;
  6330. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6331. this.leading = 0;
  6332. // Current point (in user coordinates)
  6333. this.x = 0;
  6334. this.y = 0;
  6335. // Start of text line (in text coordinates)
  6336. this.lineX = 0;
  6337. this.lineY = 0;
  6338. // Character and word spacing
  6339. this.charSpacing = 0;
  6340. this.wordSpacing = 0;
  6341. this.textHScale = 1;
  6342. this.textRise = 0;
  6343. // Default foreground and background colors
  6344. this.fillColor = SVG_DEFAULTS.fillColor;
  6345. this.strokeColor = '#000000';
  6346. this.fillAlpha = 1;
  6347. this.strokeAlpha = 1;
  6348. this.lineWidth = 1;
  6349. this.lineJoin = '';
  6350. this.lineCap = '';
  6351. this.miterLimit = 0;
  6352. this.dashArray = [];
  6353. this.dashPhase = 0;
  6354. this.dependencies = [];
  6355. // Clipping
  6356. this.clipId = '';
  6357. this.pendingClip = false;
  6358. this.maskId = '';
  6359. }
  6360. SVGExtraState.prototype = {
  6361. clone: function SVGExtraState_clone() {
  6362. return Object.create(this);
  6363. },
  6364. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  6365. this.x = x;
  6366. this.y = y;
  6367. }
  6368. };
  6369. return SVGExtraState;
  6370. })();
  6371. var SVGGraphics = (function SVGGraphicsClosure() {
  6372. function createScratchSVG(width, height) {
  6373. var NS = 'http://www.w3.org/2000/svg';
  6374. var svg = document.createElementNS(NS, 'svg:svg');
  6375. svg.setAttributeNS(null, 'version', '1.1');
  6376. svg.setAttributeNS(null, 'width', width + 'px');
  6377. svg.setAttributeNS(null, 'height', height + 'px');
  6378. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  6379. return svg;
  6380. }
  6381. function opListToTree(opList) {
  6382. var opTree = [];
  6383. var tmp = [];
  6384. var opListLen = opList.length;
  6385. for (var x = 0; x < opListLen; x++) {
  6386. if (opList[x].fn === 'save') {
  6387. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  6388. tmp.push(opTree);
  6389. opTree = opTree[opTree.length - 1].items;
  6390. continue;
  6391. }
  6392. if(opList[x].fn === 'restore') {
  6393. opTree = tmp.pop();
  6394. } else {
  6395. opTree.push(opList[x]);
  6396. }
  6397. }
  6398. return opTree;
  6399. }
  6400. /**
  6401. * Formats float number.
  6402. * @param value {number} number to format.
  6403. * @returns {string}
  6404. */
  6405. function pf(value) {
  6406. if (value === (value | 0)) { // integer number
  6407. return value.toString();
  6408. }
  6409. var s = value.toFixed(10);
  6410. var i = s.length - 1;
  6411. if (s[i] !== '0') {
  6412. return s;
  6413. }
  6414. // removing trailing zeros
  6415. do {
  6416. i--;
  6417. } while (s[i] === '0');
  6418. return s.substr(0, s[i] === '.' ? i : i + 1);
  6419. }
  6420. /**
  6421. * Formats transform matrix. The standard rotation, scale and translate
  6422. * matrices are replaced by their shorter forms, and for identity matrix
  6423. * returns empty string to save the memory.
  6424. * @param m {Array} matrix to format.
  6425. * @returns {string}
  6426. */
  6427. function pm(m) {
  6428. if (m[4] === 0 && m[5] === 0) {
  6429. if (m[1] === 0 && m[2] === 0) {
  6430. if (m[0] === 1 && m[3] === 1) {
  6431. return '';
  6432. }
  6433. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  6434. }
  6435. if (m[0] === m[3] && m[1] === -m[2]) {
  6436. var a = Math.acos(m[0]) * 180 / Math.PI;
  6437. return 'rotate(' + pf(a) + ')';
  6438. }
  6439. } else {
  6440. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  6441. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  6442. }
  6443. }
  6444. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  6445. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  6446. }
  6447. function SVGGraphics(commonObjs, objs) {
  6448. this.current = new SVGExtraState();
  6449. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  6450. this.transformStack = [];
  6451. this.extraStack = [];
  6452. this.commonObjs = commonObjs;
  6453. this.objs = objs;
  6454. this.pendingEOFill = false;
  6455. this.embedFonts = false;
  6456. this.embeddedFonts = {};
  6457. this.cssStyle = null;
  6458. }
  6459. var NS = 'http://www.w3.org/2000/svg';
  6460. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  6461. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  6462. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6463. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6464. var clipCount = 0;
  6465. var maskCount = 0;
  6466. SVGGraphics.prototype = {
  6467. save: function SVGGraphics_save() {
  6468. this.transformStack.push(this.transformMatrix);
  6469. var old = this.current;
  6470. this.extraStack.push(old);
  6471. this.current = old.clone();
  6472. },
  6473. restore: function SVGGraphics_restore() {
  6474. this.transformMatrix = this.transformStack.pop();
  6475. this.current = this.extraStack.pop();
  6476. this.tgrp = document.createElementNS(NS, 'svg:g');
  6477. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6478. this.pgrp.appendChild(this.tgrp);
  6479. },
  6480. group: function SVGGraphics_group(items) {
  6481. this.save();
  6482. this.executeOpTree(items);
  6483. this.restore();
  6484. },
  6485. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  6486. var fnArray = operatorList.fnArray;
  6487. var fnArrayLen = fnArray.length;
  6488. var argsArray = operatorList.argsArray;
  6489. var self = this;
  6490. for (var i = 0; i < fnArrayLen; i++) {
  6491. if (OPS.dependency === fnArray[i]) {
  6492. var deps = argsArray[i];
  6493. for (var n = 0, nn = deps.length; n < nn; n++) {
  6494. var obj = deps[n];
  6495. var common = obj.substring(0, 2) === 'g_';
  6496. var promise;
  6497. if (common) {
  6498. promise = new Promise(function(resolve) {
  6499. self.commonObjs.get(obj, resolve);
  6500. });
  6501. } else {
  6502. promise = new Promise(function(resolve) {
  6503. self.objs.get(obj, resolve);
  6504. });
  6505. }
  6506. this.current.dependencies.push(promise);
  6507. }
  6508. }
  6509. }
  6510. return Promise.all(this.current.dependencies);
  6511. },
  6512. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  6513. var transformMatrix = [a, b, c, d, e, f];
  6514. this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,
  6515. transformMatrix);
  6516. this.tgrp = document.createElementNS(NS, 'svg:g');
  6517. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6518. },
  6519. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  6520. this.svg = createScratchSVG(viewport.width, viewport.height);
  6521. this.viewport = viewport;
  6522. return this.loadDependencies(operatorList).then(function () {
  6523. this.transformMatrix = IDENTITY_MATRIX;
  6524. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  6525. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  6526. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  6527. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6528. this.defs = document.createElementNS(NS, 'svg:defs');
  6529. this.pgrp.appendChild(this.defs);
  6530. this.pgrp.appendChild(this.tgrp);
  6531. this.svg.appendChild(this.pgrp);
  6532. var opTree = this.convertOpList(operatorList);
  6533. this.executeOpTree(opTree);
  6534. return this.svg;
  6535. }.bind(this));
  6536. },
  6537. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  6538. var argsArray = operatorList.argsArray;
  6539. var fnArray = operatorList.fnArray;
  6540. var fnArrayLen = fnArray.length;
  6541. var REVOPS = [];
  6542. var opList = [];
  6543. for (var op in OPS) {
  6544. REVOPS[OPS[op]] = op;
  6545. }
  6546. for (var x = 0; x < fnArrayLen; x++) {
  6547. var fnId = fnArray[x];
  6548. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  6549. }
  6550. return opListToTree(opList);
  6551. },
  6552. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  6553. var opTreeLen = opTree.length;
  6554. for(var x = 0; x < opTreeLen; x++) {
  6555. var fn = opTree[x].fn;
  6556. var fnId = opTree[x].fnId;
  6557. var args = opTree[x].args;
  6558. switch (fnId | 0) {
  6559. case OPS.beginText:
  6560. this.beginText();
  6561. break;
  6562. case OPS.setLeading:
  6563. this.setLeading(args);
  6564. break;
  6565. case OPS.setLeadingMoveText:
  6566. this.setLeadingMoveText(args[0], args[1]);
  6567. break;
  6568. case OPS.setFont:
  6569. this.setFont(args);
  6570. break;
  6571. case OPS.showText:
  6572. this.showText(args[0]);
  6573. break;
  6574. case OPS.showSpacedText:
  6575. this.showText(args[0]);
  6576. break;
  6577. case OPS.endText:
  6578. this.endText();
  6579. break;
  6580. case OPS.moveText:
  6581. this.moveText(args[0], args[1]);
  6582. break;
  6583. case OPS.setCharSpacing:
  6584. this.setCharSpacing(args[0]);
  6585. break;
  6586. case OPS.setWordSpacing:
  6587. this.setWordSpacing(args[0]);
  6588. break;
  6589. case OPS.setHScale:
  6590. this.setHScale(args[0]);
  6591. break;
  6592. case OPS.setTextMatrix:
  6593. this.setTextMatrix(args[0], args[1], args[2],
  6594. args[3], args[4], args[5]);
  6595. break;
  6596. case OPS.setLineWidth:
  6597. this.setLineWidth(args[0]);
  6598. break;
  6599. case OPS.setLineJoin:
  6600. this.setLineJoin(args[0]);
  6601. break;
  6602. case OPS.setLineCap:
  6603. this.setLineCap(args[0]);
  6604. break;
  6605. case OPS.setMiterLimit:
  6606. this.setMiterLimit(args[0]);
  6607. break;
  6608. case OPS.setFillRGBColor:
  6609. this.setFillRGBColor(args[0], args[1], args[2]);
  6610. break;
  6611. case OPS.setStrokeRGBColor:
  6612. this.setStrokeRGBColor(args[0], args[1], args[2]);
  6613. break;
  6614. case OPS.setDash:
  6615. this.setDash(args[0], args[1]);
  6616. break;
  6617. case OPS.setGState:
  6618. this.setGState(args[0]);
  6619. break;
  6620. case OPS.fill:
  6621. this.fill();
  6622. break;
  6623. case OPS.eoFill:
  6624. this.eoFill();
  6625. break;
  6626. case OPS.stroke:
  6627. this.stroke();
  6628. break;
  6629. case OPS.fillStroke:
  6630. this.fillStroke();
  6631. break;
  6632. case OPS.eoFillStroke:
  6633. this.eoFillStroke();
  6634. break;
  6635. case OPS.clip:
  6636. this.clip('nonzero');
  6637. break;
  6638. case OPS.eoClip:
  6639. this.clip('evenodd');
  6640. break;
  6641. case OPS.paintSolidColorImageMask:
  6642. this.paintSolidColorImageMask();
  6643. break;
  6644. case OPS.paintJpegXObject:
  6645. this.paintJpegXObject(args[0], args[1], args[2]);
  6646. break;
  6647. case OPS.paintImageXObject:
  6648. this.paintImageXObject(args[0]);
  6649. break;
  6650. case OPS.paintInlineImageXObject:
  6651. this.paintInlineImageXObject(args[0]);
  6652. break;
  6653. case OPS.paintImageMaskXObject:
  6654. this.paintImageMaskXObject(args[0]);
  6655. break;
  6656. case OPS.paintFormXObjectBegin:
  6657. this.paintFormXObjectBegin(args[0], args[1]);
  6658. break;
  6659. case OPS.paintFormXObjectEnd:
  6660. this.paintFormXObjectEnd();
  6661. break;
  6662. case OPS.closePath:
  6663. this.closePath();
  6664. break;
  6665. case OPS.closeStroke:
  6666. this.closeStroke();
  6667. break;
  6668. case OPS.closeFillStroke:
  6669. this.closeFillStroke();
  6670. break;
  6671. case OPS.nextLine:
  6672. this.nextLine();
  6673. break;
  6674. case OPS.transform:
  6675. this.transform(args[0], args[1], args[2], args[3],
  6676. args[4], args[5]);
  6677. break;
  6678. case OPS.constructPath:
  6679. this.constructPath(args[0], args[1]);
  6680. break;
  6681. case OPS.endPath:
  6682. this.endPath();
  6683. break;
  6684. case 92:
  6685. this.group(opTree[x].items);
  6686. break;
  6687. default:
  6688. warn('Unimplemented method '+ fn);
  6689. break;
  6690. }
  6691. }
  6692. },
  6693. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  6694. this.current.wordSpacing = wordSpacing;
  6695. },
  6696. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  6697. this.current.charSpacing = charSpacing;
  6698. },
  6699. nextLine: function SVGGraphics_nextLine() {
  6700. this.moveText(0, this.current.leading);
  6701. },
  6702. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  6703. var current = this.current;
  6704. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  6705. this.current.x = this.current.lineX = 0;
  6706. this.current.y = this.current.lineY = 0;
  6707. current.xcoords = [];
  6708. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6709. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6710. current.tspan.setAttributeNS(null, 'font-size',
  6711. pf(current.fontSize) + 'px');
  6712. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6713. current.txtElement = document.createElementNS(NS, 'svg:text');
  6714. current.txtElement.appendChild(current.tspan);
  6715. },
  6716. beginText: function SVGGraphics_beginText() {
  6717. this.current.x = this.current.lineX = 0;
  6718. this.current.y = this.current.lineY = 0;
  6719. this.current.textMatrix = IDENTITY_MATRIX;
  6720. this.current.lineMatrix = IDENTITY_MATRIX;
  6721. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  6722. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  6723. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  6724. this.current.xcoords = [];
  6725. },
  6726. moveText: function SVGGraphics_moveText(x, y) {
  6727. var current = this.current;
  6728. this.current.x = this.current.lineX += x;
  6729. this.current.y = this.current.lineY += y;
  6730. current.xcoords = [];
  6731. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6732. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6733. current.tspan.setAttributeNS(null, 'font-size',
  6734. pf(current.fontSize) + 'px');
  6735. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6736. },
  6737. showText: function SVGGraphics_showText(glyphs) {
  6738. var current = this.current;
  6739. var font = current.font;
  6740. var fontSize = current.fontSize;
  6741. if (fontSize === 0) {
  6742. return;
  6743. }
  6744. var charSpacing = current.charSpacing;
  6745. var wordSpacing = current.wordSpacing;
  6746. var fontDirection = current.fontDirection;
  6747. var textHScale = current.textHScale * fontDirection;
  6748. var glyphsLength = glyphs.length;
  6749. var vertical = font.vertical;
  6750. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  6751. var x = 0, i;
  6752. for (i = 0; i < glyphsLength; ++i) {
  6753. var glyph = glyphs[i];
  6754. if (glyph === null) {
  6755. // word break
  6756. x += fontDirection * wordSpacing;
  6757. continue;
  6758. } else if (isNum(glyph)) {
  6759. x += -glyph * fontSize * 0.001;
  6760. continue;
  6761. }
  6762. current.xcoords.push(current.x + x * textHScale);
  6763. var width = glyph.width;
  6764. var character = glyph.fontChar;
  6765. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  6766. x += charWidth;
  6767. current.tspan.textContent += character;
  6768. }
  6769. if (vertical) {
  6770. current.y -= x * textHScale;
  6771. } else {
  6772. current.x += x * textHScale;
  6773. }
  6774. current.tspan.setAttributeNS(null, 'x',
  6775. current.xcoords.map(pf).join(' '));
  6776. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6777. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6778. current.tspan.setAttributeNS(null, 'font-size',
  6779. pf(current.fontSize) + 'px');
  6780. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  6781. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  6782. }
  6783. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  6784. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  6785. }
  6786. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  6787. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  6788. }
  6789. current.txtElement.setAttributeNS(null, 'transform',
  6790. pm(current.textMatrix) +
  6791. ' scale(1, -1)' );
  6792. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  6793. current.txtElement.appendChild(current.tspan);
  6794. current.txtgrp.appendChild(current.txtElement);
  6795. this.tgrp.appendChild(current.txtElement);
  6796. },
  6797. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  6798. this.setLeading(-y);
  6799. this.moveText(x, y);
  6800. },
  6801. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  6802. if (!this.cssStyle) {
  6803. this.cssStyle = document.createElementNS(NS, 'svg:style');
  6804. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  6805. this.defs.appendChild(this.cssStyle);
  6806. }
  6807. var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);
  6808. this.cssStyle.textContent +=
  6809. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  6810. ' src: url(' + url + '); }\n';
  6811. },
  6812. setFont: function SVGGraphics_setFont(details) {
  6813. var current = this.current;
  6814. var fontObj = this.commonObjs.get(details[0]);
  6815. var size = details[1];
  6816. this.current.font = fontObj;
  6817. if (this.embedFonts && fontObj.data &&
  6818. !this.embeddedFonts[fontObj.loadedName]) {
  6819. this.addFontStyle(fontObj);
  6820. this.embeddedFonts[fontObj.loadedName] = fontObj;
  6821. }
  6822. current.fontMatrix = (fontObj.fontMatrix ?
  6823. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  6824. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  6825. (fontObj.bold ? 'bold' : 'normal');
  6826. var italic = fontObj.italic ? 'italic' : 'normal';
  6827. if (size < 0) {
  6828. size = -size;
  6829. current.fontDirection = -1;
  6830. } else {
  6831. current.fontDirection = 1;
  6832. }
  6833. current.fontSize = size;
  6834. current.fontFamily = fontObj.loadedName;
  6835. current.fontWeight = bold;
  6836. current.fontStyle = italic;
  6837. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6838. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6839. current.xcoords = [];
  6840. },
  6841. endText: function SVGGraphics_endText() {
  6842. if (this.current.pendingClip) {
  6843. this.cgrp.appendChild(this.tgrp);
  6844. this.pgrp.appendChild(this.cgrp);
  6845. } else {
  6846. this.pgrp.appendChild(this.tgrp);
  6847. }
  6848. this.tgrp = document.createElementNS(NS, 'svg:g');
  6849. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6850. },
  6851. // Path properties
  6852. setLineWidth: function SVGGraphics_setLineWidth(width) {
  6853. this.current.lineWidth = width;
  6854. },
  6855. setLineCap: function SVGGraphics_setLineCap(style) {
  6856. this.current.lineCap = LINE_CAP_STYLES[style];
  6857. },
  6858. setLineJoin: function SVGGraphics_setLineJoin(style) {
  6859. this.current.lineJoin = LINE_JOIN_STYLES[style];
  6860. },
  6861. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  6862. this.current.miterLimit = limit;
  6863. },
  6864. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  6865. var color = Util.makeCssRgb(r, g, b);
  6866. this.current.strokeColor = color;
  6867. },
  6868. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  6869. var color = Util.makeCssRgb(r, g, b);
  6870. this.current.fillColor = color;
  6871. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  6872. this.current.xcoords = [];
  6873. },
  6874. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  6875. this.current.dashArray = dashArray;
  6876. this.current.dashPhase = dashPhase;
  6877. },
  6878. constructPath: function SVGGraphics_constructPath(ops, args) {
  6879. var current = this.current;
  6880. var x = current.x, y = current.y;
  6881. current.path = document.createElementNS(NS, 'svg:path');
  6882. var d = [];
  6883. var opLength = ops.length;
  6884. for (var i = 0, j = 0; i < opLength; i++) {
  6885. switch (ops[i] | 0) {
  6886. case OPS.rectangle:
  6887. x = args[j++];
  6888. y = args[j++];
  6889. var width = args[j++];
  6890. var height = args[j++];
  6891. var xw = x + width;
  6892. var yh = y + height;
  6893. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  6894. 'L', pf(x), pf(yh), 'Z');
  6895. break;
  6896. case OPS.moveTo:
  6897. x = args[j++];
  6898. y = args[j++];
  6899. d.push('M', pf(x), pf(y));
  6900. break;
  6901. case OPS.lineTo:
  6902. x = args[j++];
  6903. y = args[j++];
  6904. d.push('L', pf(x) , pf(y));
  6905. break;
  6906. case OPS.curveTo:
  6907. x = args[j + 4];
  6908. y = args[j + 5];
  6909. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  6910. pf(args[j + 3]), pf(x), pf(y));
  6911. j += 6;
  6912. break;
  6913. case OPS.curveTo2:
  6914. x = args[j + 2];
  6915. y = args[j + 3];
  6916. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  6917. pf(args[j + 2]), pf(args[j + 3]));
  6918. j += 4;
  6919. break;
  6920. case OPS.curveTo3:
  6921. x = args[j + 2];
  6922. y = args[j + 3];
  6923. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  6924. pf(x), pf(y));
  6925. j += 4;
  6926. break;
  6927. case OPS.closePath:
  6928. d.push('Z');
  6929. break;
  6930. }
  6931. }
  6932. current.path.setAttributeNS(null, 'd', d.join(' '));
  6933. current.path.setAttributeNS(null, 'stroke-miterlimit',
  6934. pf(current.miterLimit));
  6935. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  6936. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  6937. current.path.setAttributeNS(null, 'stroke-width',
  6938. pf(current.lineWidth) + 'px');
  6939. current.path.setAttributeNS(null, 'stroke-dasharray',
  6940. current.dashArray.map(pf).join(' '));
  6941. current.path.setAttributeNS(null, 'stroke-dashoffset',
  6942. pf(current.dashPhase) + 'px');
  6943. current.path.setAttributeNS(null, 'fill', 'none');
  6944. this.tgrp.appendChild(current.path);
  6945. if (current.pendingClip) {
  6946. this.cgrp.appendChild(this.tgrp);
  6947. this.pgrp.appendChild(this.cgrp);
  6948. } else {
  6949. this.pgrp.appendChild(this.tgrp);
  6950. }
  6951. // Saving a reference in current.element so that it can be addressed
  6952. // in 'fill' and 'stroke'
  6953. current.element = current.path;
  6954. current.setCurrentPoint(x, y);
  6955. },
  6956. endPath: function SVGGraphics_endPath() {
  6957. var current = this.current;
  6958. if (current.pendingClip) {
  6959. this.cgrp.appendChild(this.tgrp);
  6960. this.pgrp.appendChild(this.cgrp);
  6961. } else {
  6962. this.pgrp.appendChild(this.tgrp);
  6963. }
  6964. this.tgrp = document.createElementNS(NS, 'svg:g');
  6965. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6966. },
  6967. clip: function SVGGraphics_clip(type) {
  6968. var current = this.current;
  6969. // Add current path to clipping path
  6970. current.clipId = 'clippath' + clipCount;
  6971. clipCount++;
  6972. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  6973. this.clippath.setAttributeNS(null, 'id', current.clipId);
  6974. var clipElement = current.element.cloneNode();
  6975. if (type === 'evenodd') {
  6976. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  6977. } else {
  6978. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  6979. }
  6980. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6981. this.clippath.appendChild(clipElement);
  6982. this.defs.appendChild(this.clippath);
  6983. // Create a new group with that attribute
  6984. current.pendingClip = true;
  6985. this.cgrp = document.createElementNS(NS, 'svg:g');
  6986. this.cgrp.setAttributeNS(null, 'clip-path',
  6987. 'url(#' + current.clipId + ')');
  6988. this.pgrp.appendChild(this.cgrp);
  6989. },
  6990. closePath: function SVGGraphics_closePath() {
  6991. var current = this.current;
  6992. var d = current.path.getAttributeNS(null, 'd');
  6993. d += 'Z';
  6994. current.path.setAttributeNS(null, 'd', d);
  6995. },
  6996. setLeading: function SVGGraphics_setLeading(leading) {
  6997. this.current.leading = -leading;
  6998. },
  6999. setTextRise: function SVGGraphics_setTextRise(textRise) {
  7000. this.current.textRise = textRise;
  7001. },
  7002. setHScale: function SVGGraphics_setHScale(scale) {
  7003. this.current.textHScale = scale / 100;
  7004. },
  7005. setGState: function SVGGraphics_setGState(states) {
  7006. for (var i = 0, ii = states.length; i < ii; i++) {
  7007. var state = states[i];
  7008. var key = state[0];
  7009. var value = state[1];
  7010. switch (key) {
  7011. case 'LW':
  7012. this.setLineWidth(value);
  7013. break;
  7014. case 'LC':
  7015. this.setLineCap(value);
  7016. break;
  7017. case 'LJ':
  7018. this.setLineJoin(value);
  7019. break;
  7020. case 'ML':
  7021. this.setMiterLimit(value);
  7022. break;
  7023. case 'D':
  7024. this.setDash(value[0], value[1]);
  7025. break;
  7026. case 'RI':
  7027. break;
  7028. case 'FL':
  7029. break;
  7030. case 'Font':
  7031. this.setFont(value);
  7032. break;
  7033. case 'CA':
  7034. break;
  7035. case 'ca':
  7036. break;
  7037. case 'BM':
  7038. break;
  7039. case 'SMask':
  7040. break;
  7041. }
  7042. }
  7043. },
  7044. fill: function SVGGraphics_fill() {
  7045. var current = this.current;
  7046. current.element.setAttributeNS(null, 'fill', current.fillColor);
  7047. },
  7048. stroke: function SVGGraphics_stroke() {
  7049. var current = this.current;
  7050. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  7051. current.element.setAttributeNS(null, 'fill', 'none');
  7052. },
  7053. eoFill: function SVGGraphics_eoFill() {
  7054. var current = this.current;
  7055. current.element.setAttributeNS(null, 'fill', current.fillColor);
  7056. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  7057. },
  7058. fillStroke: function SVGGraphics_fillStroke() {
  7059. // Order is important since stroke wants fill to be none.
  7060. // First stroke, then if fill needed, it will be overwritten.
  7061. this.stroke();
  7062. this.fill();
  7063. },
  7064. eoFillStroke: function SVGGraphics_eoFillStroke() {
  7065. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  7066. this.fillStroke();
  7067. },
  7068. closeStroke: function SVGGraphics_closeStroke() {
  7069. this.closePath();
  7070. this.stroke();
  7071. },
  7072. closeFillStroke: function SVGGraphics_closeFillStroke() {
  7073. this.closePath();
  7074. this.fillStroke();
  7075. },
  7076. paintSolidColorImageMask:
  7077. function SVGGraphics_paintSolidColorImageMask() {
  7078. var current = this.current;
  7079. var rect = document.createElementNS(NS, 'svg:rect');
  7080. rect.setAttributeNS(null, 'x', '0');
  7081. rect.setAttributeNS(null, 'y', '0');
  7082. rect.setAttributeNS(null, 'width', '1px');
  7083. rect.setAttributeNS(null, 'height', '1px');
  7084. rect.setAttributeNS(null, 'fill', current.fillColor);
  7085. this.tgrp.appendChild(rect);
  7086. },
  7087. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  7088. var current = this.current;
  7089. var imgObj = this.objs.get(objId);
  7090. var imgEl = document.createElementNS(NS, 'svg:image');
  7091. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  7092. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  7093. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  7094. imgEl.setAttributeNS(null, 'x', '0');
  7095. imgEl.setAttributeNS(null, 'y', pf(-h));
  7096. imgEl.setAttributeNS(null, 'transform',
  7097. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  7098. this.tgrp.appendChild(imgEl);
  7099. if (current.pendingClip) {
  7100. this.cgrp.appendChild(this.tgrp);
  7101. this.pgrp.appendChild(this.cgrp);
  7102. } else {
  7103. this.pgrp.appendChild(this.tgrp);
  7104. }
  7105. },
  7106. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  7107. var imgData = this.objs.get(objId);
  7108. if (!imgData) {
  7109. warn('Dependent image isn\'t ready yet');
  7110. return;
  7111. }
  7112. this.paintInlineImageXObject(imgData);
  7113. },
  7114. paintInlineImageXObject:
  7115. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  7116. var current = this.current;
  7117. var width = imgData.width;
  7118. var height = imgData.height;
  7119. var imgSrc = convertImgDataToPng(imgData);
  7120. var cliprect = document.createElementNS(NS, 'svg:rect');
  7121. cliprect.setAttributeNS(null, 'x', '0');
  7122. cliprect.setAttributeNS(null, 'y', '0');
  7123. cliprect.setAttributeNS(null, 'width', pf(width));
  7124. cliprect.setAttributeNS(null, 'height', pf(height));
  7125. current.element = cliprect;
  7126. this.clip('nonzero');
  7127. var imgEl = document.createElementNS(NS, 'svg:image');
  7128. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  7129. imgEl.setAttributeNS(null, 'x', '0');
  7130. imgEl.setAttributeNS(null, 'y', pf(-height));
  7131. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  7132. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  7133. imgEl.setAttributeNS(null, 'transform',
  7134. 'scale(' + pf(1 / width) + ' ' +
  7135. pf(-1 / height) + ')');
  7136. if (mask) {
  7137. mask.appendChild(imgEl);
  7138. } else {
  7139. this.tgrp.appendChild(imgEl);
  7140. }
  7141. if (current.pendingClip) {
  7142. this.cgrp.appendChild(this.tgrp);
  7143. this.pgrp.appendChild(this.cgrp);
  7144. } else {
  7145. this.pgrp.appendChild(this.tgrp);
  7146. }
  7147. },
  7148. paintImageMaskXObject:
  7149. function SVGGraphics_paintImageMaskXObject(imgData) {
  7150. var current = this.current;
  7151. var width = imgData.width;
  7152. var height = imgData.height;
  7153. var fillColor = current.fillColor;
  7154. current.maskId = 'mask' + maskCount++;
  7155. var mask = document.createElementNS(NS, 'svg:mask');
  7156. mask.setAttributeNS(null, 'id', current.maskId);
  7157. var rect = document.createElementNS(NS, 'svg:rect');
  7158. rect.setAttributeNS(null, 'x', '0');
  7159. rect.setAttributeNS(null, 'y', '0');
  7160. rect.setAttributeNS(null, 'width', pf(width));
  7161. rect.setAttributeNS(null, 'height', pf(height));
  7162. rect.setAttributeNS(null, 'fill', fillColor);
  7163. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  7164. this.defs.appendChild(mask);
  7165. this.tgrp.appendChild(rect);
  7166. this.paintInlineImageXObject(imgData, mask);
  7167. },
  7168. paintFormXObjectBegin:
  7169. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  7170. this.save();
  7171. if (isArray(matrix) && matrix.length === 6) {
  7172. this.transform(matrix[0], matrix[1], matrix[2],
  7173. matrix[3], matrix[4], matrix[5]);
  7174. }
  7175. if (isArray(bbox) && bbox.length === 4) {
  7176. var width = bbox[2] - bbox[0];
  7177. var height = bbox[3] - bbox[1];
  7178. var cliprect = document.createElementNS(NS, 'svg:rect');
  7179. cliprect.setAttributeNS(null, 'x', bbox[0]);
  7180. cliprect.setAttributeNS(null, 'y', bbox[1]);
  7181. cliprect.setAttributeNS(null, 'width', pf(width));
  7182. cliprect.setAttributeNS(null, 'height', pf(height));
  7183. this.current.element = cliprect;
  7184. this.clip('nonzero');
  7185. this.endPath();
  7186. }
  7187. },
  7188. paintFormXObjectEnd:
  7189. function SVGGraphics_paintFormXObjectEnd() {
  7190. this.restore();
  7191. }
  7192. };
  7193. return SVGGraphics;
  7194. })();
  7195. PDFJS.SVGGraphics = SVGGraphics;
  7196. var NetworkManager = (function NetworkManagerClosure() {
  7197. var OK_RESPONSE = 200;
  7198. var PARTIAL_CONTENT_RESPONSE = 206;
  7199. function NetworkManager(url, args) {
  7200. this.url = url;
  7201. args = args || {};
  7202. this.isHttp = /^https?:/i.test(url);
  7203. this.httpHeaders = (this.isHttp && args.httpHeaders) || {};
  7204. this.withCredentials = args.withCredentials || false;
  7205. this.getXhr = args.getXhr ||
  7206. function NetworkManager_getXhr() {
  7207. return new XMLHttpRequest();
  7208. };
  7209. this.currXhrId = 0;
  7210. this.pendingRequests = {};
  7211. this.loadedRequests = {};
  7212. }
  7213. function getArrayBuffer(xhr) {
  7214. var data = xhr.response;
  7215. if (typeof data !== 'string') {
  7216. return data;
  7217. }
  7218. var length = data.length;
  7219. var array = new Uint8Array(length);
  7220. for (var i = 0; i < length; i++) {
  7221. array[i] = data.charCodeAt(i) & 0xFF;
  7222. }
  7223. return array.buffer;
  7224. }
  7225. var supportsMozChunked = (function supportsMozChunkedClosure() {
  7226. try {
  7227. var x = new XMLHttpRequest();
  7228. // Firefox 37- required .open() to be called before setting responseType.
  7229. // https://bugzilla.mozilla.org/show_bug.cgi?id=707484
  7230. // Even though the URL is not visited, .open() could fail if the URL is
  7231. // blocked, e.g. via the connect-src CSP directive or the NoScript addon.
  7232. // When this error occurs, this feature detection method will mistakenly
  7233. // report that moz-chunked-arraybuffer is not supported in Firefox 37-.
  7234. x.open('GET', 'https://example.com');
  7235. x.responseType = 'moz-chunked-arraybuffer';
  7236. return x.responseType === 'moz-chunked-arraybuffer';
  7237. } catch (e) {
  7238. return false;
  7239. }
  7240. })();
  7241. NetworkManager.prototype = {
  7242. requestRange: function NetworkManager_requestRange(begin, end, listeners) {
  7243. var args = {
  7244. begin: begin,
  7245. end: end
  7246. };
  7247. for (var prop in listeners) {
  7248. args[prop] = listeners[prop];
  7249. }
  7250. return this.request(args);
  7251. },
  7252. requestFull: function NetworkManager_requestFull(listeners) {
  7253. return this.request(listeners);
  7254. },
  7255. request: function NetworkManager_request(args) {
  7256. var xhr = this.getXhr();
  7257. var xhrId = this.currXhrId++;
  7258. var pendingRequest = this.pendingRequests[xhrId] = {
  7259. xhr: xhr
  7260. };
  7261. xhr.open('GET', this.url);
  7262. xhr.withCredentials = this.withCredentials;
  7263. for (var property in this.httpHeaders) {
  7264. var value = this.httpHeaders[property];
  7265. if (typeof value === 'undefined') {
  7266. continue;
  7267. }
  7268. xhr.setRequestHeader(property, value);
  7269. }
  7270. if (this.isHttp && 'begin' in args && 'end' in args) {
  7271. var rangeStr = args.begin + '-' + (args.end - 1);
  7272. xhr.setRequestHeader('Range', 'bytes=' + rangeStr);
  7273. pendingRequest.expectedStatus = 206;
  7274. } else {
  7275. pendingRequest.expectedStatus = 200;
  7276. }
  7277. var useMozChunkedLoading = supportsMozChunked && !!args.onProgressiveData;
  7278. if (useMozChunkedLoading) {
  7279. xhr.responseType = 'moz-chunked-arraybuffer';
  7280. pendingRequest.onProgressiveData = args.onProgressiveData;
  7281. pendingRequest.mozChunked = true;
  7282. } else {
  7283. xhr.responseType = 'arraybuffer';
  7284. }
  7285. if (args.onError) {
  7286. xhr.onerror = function(evt) {
  7287. args.onError(xhr.status);
  7288. };
  7289. }
  7290. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  7291. xhr.onprogress = this.onProgress.bind(this, xhrId);
  7292. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  7293. pendingRequest.onDone = args.onDone;
  7294. pendingRequest.onError = args.onError;
  7295. pendingRequest.onProgress = args.onProgress;
  7296. xhr.send(null);
  7297. return xhrId;
  7298. },
  7299. onProgress: function NetworkManager_onProgress(xhrId, evt) {
  7300. var pendingRequest = this.pendingRequests[xhrId];
  7301. if (!pendingRequest) {
  7302. // Maybe abortRequest was called...
  7303. return;
  7304. }
  7305. if (pendingRequest.mozChunked) {
  7306. var chunk = getArrayBuffer(pendingRequest.xhr);
  7307. pendingRequest.onProgressiveData(chunk);
  7308. }
  7309. var onProgress = pendingRequest.onProgress;
  7310. if (onProgress) {
  7311. onProgress(evt);
  7312. }
  7313. },
  7314. onStateChange: function NetworkManager_onStateChange(xhrId, evt) {
  7315. var pendingRequest = this.pendingRequests[xhrId];
  7316. if (!pendingRequest) {
  7317. // Maybe abortRequest was called...
  7318. return;
  7319. }
  7320. var xhr = pendingRequest.xhr;
  7321. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  7322. pendingRequest.onHeadersReceived();
  7323. delete pendingRequest.onHeadersReceived;
  7324. }
  7325. if (xhr.readyState !== 4) {
  7326. return;
  7327. }
  7328. if (!(xhrId in this.pendingRequests)) {
  7329. // The XHR request might have been aborted in onHeadersReceived()
  7330. // callback, in which case we should abort request
  7331. return;
  7332. }
  7333. delete this.pendingRequests[xhrId];
  7334. // success status == 0 can be on ftp, file and other protocols
  7335. if (xhr.status === 0 && this.isHttp) {
  7336. if (pendingRequest.onError) {
  7337. pendingRequest.onError(xhr.status);
  7338. }
  7339. return;
  7340. }
  7341. var xhrStatus = xhr.status || OK_RESPONSE;
  7342. // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2:
  7343. // "A server MAY ignore the Range header". This means it's possible to
  7344. // get a 200 rather than a 206 response from a range request.
  7345. var ok_response_on_range_request =
  7346. xhrStatus === OK_RESPONSE &&
  7347. pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  7348. if (!ok_response_on_range_request &&
  7349. xhrStatus !== pendingRequest.expectedStatus) {
  7350. if (pendingRequest.onError) {
  7351. pendingRequest.onError(xhr.status);
  7352. }
  7353. return;
  7354. }
  7355. this.loadedRequests[xhrId] = true;
  7356. var chunk = getArrayBuffer(xhr);
  7357. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  7358. var rangeHeader = xhr.getResponseHeader('Content-Range');
  7359. var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  7360. var begin = parseInt(matches[1], 10);
  7361. pendingRequest.onDone({
  7362. begin: begin,
  7363. chunk: chunk
  7364. });
  7365. } else if (pendingRequest.onProgressiveData) {
  7366. pendingRequest.onDone(null);
  7367. } else {
  7368. pendingRequest.onDone({
  7369. begin: 0,
  7370. chunk: chunk
  7371. });
  7372. }
  7373. },
  7374. hasPendingRequests: function NetworkManager_hasPendingRequests() {
  7375. for (var xhrId in this.pendingRequests) {
  7376. return true;
  7377. }
  7378. return false;
  7379. },
  7380. getRequestXhr: function NetworkManager_getXhr(xhrId) {
  7381. return this.pendingRequests[xhrId].xhr;
  7382. },
  7383. isStreamingRequest: function NetworkManager_isStreamingRequest(xhrId) {
  7384. return !!(this.pendingRequests[xhrId].onProgressiveData);
  7385. },
  7386. isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {
  7387. return xhrId in this.pendingRequests;
  7388. },
  7389. isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {
  7390. return xhrId in this.loadedRequests;
  7391. },
  7392. abortAllRequests: function NetworkManager_abortAllRequests() {
  7393. for (var xhrId in this.pendingRequests) {
  7394. this.abortRequest(xhrId | 0);
  7395. }
  7396. },
  7397. abortRequest: function NetworkManager_abortRequest(xhrId) {
  7398. var xhr = this.pendingRequests[xhrId].xhr;
  7399. delete this.pendingRequests[xhrId];
  7400. xhr.abort();
  7401. }
  7402. };
  7403. return NetworkManager;
  7404. })();
  7405. var ChunkedStream = (function ChunkedStreamClosure() {
  7406. function ChunkedStream(length, chunkSize, manager) {
  7407. this.bytes = new Uint8Array(length);
  7408. this.start = 0;
  7409. this.pos = 0;
  7410. this.end = length;
  7411. this.chunkSize = chunkSize;
  7412. this.loadedChunks = [];
  7413. this.numChunksLoaded = 0;
  7414. this.numChunks = Math.ceil(length / chunkSize);
  7415. this.manager = manager;
  7416. this.progressiveDataLength = 0;
  7417. this.lastSuccessfulEnsureByteChunk = -1; // a single-entry cache
  7418. }
  7419. // required methods for a stream. if a particular stream does not
  7420. // implement these, an error should be thrown
  7421. ChunkedStream.prototype = {
  7422. getMissingChunks: function ChunkedStream_getMissingChunks() {
  7423. var chunks = [];
  7424. for (var chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
  7425. if (!this.loadedChunks[chunk]) {
  7426. chunks.push(chunk);
  7427. }
  7428. }
  7429. return chunks;
  7430. },
  7431. getBaseStreams: function ChunkedStream_getBaseStreams() {
  7432. return [this];
  7433. },
  7434. allChunksLoaded: function ChunkedStream_allChunksLoaded() {
  7435. return this.numChunksLoaded === this.numChunks;
  7436. },
  7437. onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) {
  7438. var end = begin + chunk.byteLength;
  7439. assert(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin);
  7440. // Using this.length is inaccurate here since this.start can be moved
  7441. // See ChunkedStream.moveStart()
  7442. var length = this.bytes.length;
  7443. assert(end % this.chunkSize === 0 || end === length,
  7444. 'Bad end offset: ' + end);
  7445. this.bytes.set(new Uint8Array(chunk), begin);
  7446. var chunkSize = this.chunkSize;
  7447. var beginChunk = Math.floor(begin / chunkSize);
  7448. var endChunk = Math.floor((end - 1) / chunkSize) + 1;
  7449. var curChunk;
  7450. for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  7451. if (!this.loadedChunks[curChunk]) {
  7452. this.loadedChunks[curChunk] = true;
  7453. ++this.numChunksLoaded;
  7454. }
  7455. }
  7456. },
  7457. onReceiveProgressiveData:
  7458. function ChunkedStream_onReceiveProgressiveData(data) {
  7459. var position = this.progressiveDataLength;
  7460. var beginChunk = Math.floor(position / this.chunkSize);
  7461. this.bytes.set(new Uint8Array(data), position);
  7462. position += data.byteLength;
  7463. this.progressiveDataLength = position;
  7464. var endChunk = position >= this.end ? this.numChunks :
  7465. Math.floor(position / this.chunkSize);
  7466. var curChunk;
  7467. for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  7468. if (!this.loadedChunks[curChunk]) {
  7469. this.loadedChunks[curChunk] = true;
  7470. ++this.numChunksLoaded;
  7471. }
  7472. }
  7473. },
  7474. ensureByte: function ChunkedStream_ensureByte(pos) {
  7475. var chunk = Math.floor(pos / this.chunkSize);
  7476. if (chunk === this.lastSuccessfulEnsureByteChunk) {
  7477. return;
  7478. }
  7479. if (!this.loadedChunks[chunk]) {
  7480. throw new MissingDataException(pos, pos + 1);
  7481. }
  7482. this.lastSuccessfulEnsureByteChunk = chunk;
  7483. },
  7484. ensureRange: function ChunkedStream_ensureRange(begin, end) {
  7485. if (begin >= end) {
  7486. return;
  7487. }
  7488. if (end <= this.progressiveDataLength) {
  7489. return;
  7490. }
  7491. var chunkSize = this.chunkSize;
  7492. var beginChunk = Math.floor(begin / chunkSize);
  7493. var endChunk = Math.floor((end - 1) / chunkSize) + 1;
  7494. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7495. if (!this.loadedChunks[chunk]) {
  7496. throw new MissingDataException(begin, end);
  7497. }
  7498. }
  7499. },
  7500. nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) {
  7501. var chunk, numChunks = this.numChunks;
  7502. for (var i = 0; i < numChunks; ++i) {
  7503. chunk = (beginChunk + i) % numChunks; // Wrap around to beginning
  7504. if (!this.loadedChunks[chunk]) {
  7505. return chunk;
  7506. }
  7507. }
  7508. return null;
  7509. },
  7510. hasChunk: function ChunkedStream_hasChunk(chunk) {
  7511. return !!this.loadedChunks[chunk];
  7512. },
  7513. get length() {
  7514. return this.end - this.start;
  7515. },
  7516. get isEmpty() {
  7517. return this.length === 0;
  7518. },
  7519. getByte: function ChunkedStream_getByte() {
  7520. var pos = this.pos;
  7521. if (pos >= this.end) {
  7522. return -1;
  7523. }
  7524. this.ensureByte(pos);
  7525. return this.bytes[this.pos++];
  7526. },
  7527. getUint16: function ChunkedStream_getUint16() {
  7528. var b0 = this.getByte();
  7529. var b1 = this.getByte();
  7530. if (b0 === -1 || b1 === -1) {
  7531. return -1;
  7532. }
  7533. return (b0 << 8) + b1;
  7534. },
  7535. getInt32: function ChunkedStream_getInt32() {
  7536. var b0 = this.getByte();
  7537. var b1 = this.getByte();
  7538. var b2 = this.getByte();
  7539. var b3 = this.getByte();
  7540. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  7541. },
  7542. // returns subarray of original buffer
  7543. // should only be read
  7544. getBytes: function ChunkedStream_getBytes(length) {
  7545. var bytes = this.bytes;
  7546. var pos = this.pos;
  7547. var strEnd = this.end;
  7548. if (!length) {
  7549. this.ensureRange(pos, strEnd);
  7550. return bytes.subarray(pos, strEnd);
  7551. }
  7552. var end = pos + length;
  7553. if (end > strEnd) {
  7554. end = strEnd;
  7555. }
  7556. this.ensureRange(pos, end);
  7557. this.pos = end;
  7558. return bytes.subarray(pos, end);
  7559. },
  7560. peekByte: function ChunkedStream_peekByte() {
  7561. var peekedByte = this.getByte();
  7562. this.pos--;
  7563. return peekedByte;
  7564. },
  7565. peekBytes: function ChunkedStream_peekBytes(length) {
  7566. var bytes = this.getBytes(length);
  7567. this.pos -= bytes.length;
  7568. return bytes;
  7569. },
  7570. getByteRange: function ChunkedStream_getBytes(begin, end) {
  7571. this.ensureRange(begin, end);
  7572. return this.bytes.subarray(begin, end);
  7573. },
  7574. skip: function ChunkedStream_skip(n) {
  7575. if (!n) {
  7576. n = 1;
  7577. }
  7578. this.pos += n;
  7579. },
  7580. reset: function ChunkedStream_reset() {
  7581. this.pos = this.start;
  7582. },
  7583. moveStart: function ChunkedStream_moveStart() {
  7584. this.start = this.pos;
  7585. },
  7586. makeSubStream: function ChunkedStream_makeSubStream(start, length, dict) {
  7587. this.ensureRange(start, start + length);
  7588. function ChunkedStreamSubstream() {}
  7589. ChunkedStreamSubstream.prototype = Object.create(this);
  7590. ChunkedStreamSubstream.prototype.getMissingChunks = function() {
  7591. var chunkSize = this.chunkSize;
  7592. var beginChunk = Math.floor(this.start / chunkSize);
  7593. var endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
  7594. var missingChunks = [];
  7595. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7596. if (!this.loadedChunks[chunk]) {
  7597. missingChunks.push(chunk);
  7598. }
  7599. }
  7600. return missingChunks;
  7601. };
  7602. var subStream = new ChunkedStreamSubstream();
  7603. subStream.pos = subStream.start = start;
  7604. subStream.end = start + length || this.end;
  7605. subStream.dict = dict;
  7606. return subStream;
  7607. },
  7608. isStream: true
  7609. };
  7610. return ChunkedStream;
  7611. })();
  7612. var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {
  7613. function ChunkedStreamManager(length, chunkSize, url, args) {
  7614. this.stream = new ChunkedStream(length, chunkSize, this);
  7615. this.length = length;
  7616. this.chunkSize = chunkSize;
  7617. this.url = url;
  7618. this.disableAutoFetch = args.disableAutoFetch;
  7619. var msgHandler = this.msgHandler = args.msgHandler;
  7620. if (args.chunkedViewerLoading) {
  7621. msgHandler.on('OnDataRange', this.onReceiveData.bind(this));
  7622. msgHandler.on('OnDataProgress', this.onProgress.bind(this));
  7623. this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {
  7624. msgHandler.send('RequestDataRange', { begin: begin, end: end });
  7625. };
  7626. } else {
  7627. var getXhr = function getXhr() {
  7628. return new XMLHttpRequest();
  7629. };
  7630. this.networkManager = new NetworkManager(this.url, {
  7631. getXhr: getXhr,
  7632. httpHeaders: args.httpHeaders,
  7633. withCredentials: args.withCredentials
  7634. });
  7635. this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {
  7636. this.networkManager.requestRange(begin, end, {
  7637. onDone: this.onReceiveData.bind(this),
  7638. onProgress: this.onProgress.bind(this)
  7639. });
  7640. };
  7641. }
  7642. this.currRequestId = 0;
  7643. this.chunksNeededByRequest = {};
  7644. this.requestsByChunk = {};
  7645. this.callbacksByRequest = {};
  7646. this.progressiveDataLength = 0;
  7647. this._loadedStreamCapability = createPromiseCapability();
  7648. if (args.initialData) {
  7649. this.onReceiveData({chunk: args.initialData});
  7650. }
  7651. }
  7652. ChunkedStreamManager.prototype = {
  7653. onLoadedStream: function ChunkedStreamManager_getLoadedStream() {
  7654. return this._loadedStreamCapability.promise;
  7655. },
  7656. // Get all the chunks that are not yet loaded and groups them into
  7657. // contiguous ranges to load in as few requests as possible
  7658. requestAllChunks: function ChunkedStreamManager_requestAllChunks() {
  7659. var missingChunks = this.stream.getMissingChunks();
  7660. this.requestChunks(missingChunks);
  7661. return this._loadedStreamCapability.promise;
  7662. },
  7663. requestChunks: function ChunkedStreamManager_requestChunks(chunks,
  7664. callback) {
  7665. var requestId = this.currRequestId++;
  7666. var chunksNeeded;
  7667. var i, ii;
  7668. this.chunksNeededByRequest[requestId] = chunksNeeded = {};
  7669. for (i = 0, ii = chunks.length; i < ii; i++) {
  7670. if (!this.stream.hasChunk(chunks[i])) {
  7671. chunksNeeded[chunks[i]] = true;
  7672. }
  7673. }
  7674. if (isEmptyObj(chunksNeeded)) {
  7675. if (callback) {
  7676. callback();
  7677. }
  7678. return;
  7679. }
  7680. this.callbacksByRequest[requestId] = callback;
  7681. var chunksToRequest = [];
  7682. for (var chunk in chunksNeeded) {
  7683. chunk = chunk | 0;
  7684. if (!(chunk in this.requestsByChunk)) {
  7685. this.requestsByChunk[chunk] = [];
  7686. chunksToRequest.push(chunk);
  7687. }
  7688. this.requestsByChunk[chunk].push(requestId);
  7689. }
  7690. if (!chunksToRequest.length) {
  7691. return;
  7692. }
  7693. var groupedChunksToRequest = this.groupChunks(chunksToRequest);
  7694. for (i = 0; i < groupedChunksToRequest.length; ++i) {
  7695. var groupedChunk = groupedChunksToRequest[i];
  7696. var begin = groupedChunk.beginChunk * this.chunkSize;
  7697. var end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
  7698. this.sendRequest(begin, end);
  7699. }
  7700. },
  7701. getStream: function ChunkedStreamManager_getStream() {
  7702. return this.stream;
  7703. },
  7704. // Loads any chunks in the requested range that are not yet loaded
  7705. requestRange: function ChunkedStreamManager_requestRange(
  7706. begin, end, callback) {
  7707. end = Math.min(end, this.length);
  7708. var beginChunk = this.getBeginChunk(begin);
  7709. var endChunk = this.getEndChunk(end);
  7710. var chunks = [];
  7711. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7712. chunks.push(chunk);
  7713. }
  7714. this.requestChunks(chunks, callback);
  7715. },
  7716. requestRanges: function ChunkedStreamManager_requestRanges(ranges,
  7717. callback) {
  7718. ranges = ranges || [];
  7719. var chunksToRequest = [];
  7720. for (var i = 0; i < ranges.length; i++) {
  7721. var beginChunk = this.getBeginChunk(ranges[i].begin);
  7722. var endChunk = this.getEndChunk(ranges[i].end);
  7723. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7724. if (chunksToRequest.indexOf(chunk) < 0) {
  7725. chunksToRequest.push(chunk);
  7726. }
  7727. }
  7728. }
  7729. chunksToRequest.sort(function(a, b) { return a - b; });
  7730. this.requestChunks(chunksToRequest, callback);
  7731. },
  7732. // Groups a sorted array of chunks into as few contiguous larger
  7733. // chunks as possible
  7734. groupChunks: function ChunkedStreamManager_groupChunks(chunks) {
  7735. var groupedChunks = [];
  7736. var beginChunk = -1;
  7737. var prevChunk = -1;
  7738. for (var i = 0; i < chunks.length; ++i) {
  7739. var chunk = chunks[i];
  7740. if (beginChunk < 0) {
  7741. beginChunk = chunk;
  7742. }
  7743. if (prevChunk >= 0 && prevChunk + 1 !== chunk) {
  7744. groupedChunks.push({ beginChunk: beginChunk,
  7745. endChunk: prevChunk + 1 });
  7746. beginChunk = chunk;
  7747. }
  7748. if (i + 1 === chunks.length) {
  7749. groupedChunks.push({ beginChunk: beginChunk,
  7750. endChunk: chunk + 1 });
  7751. }
  7752. prevChunk = chunk;
  7753. }
  7754. return groupedChunks;
  7755. },
  7756. onProgress: function ChunkedStreamManager_onProgress(args) {
  7757. var bytesLoaded = (this.stream.numChunksLoaded * this.chunkSize +
  7758. args.loaded);
  7759. this.msgHandler.send('DocProgress', {
  7760. loaded: bytesLoaded,
  7761. total: this.length
  7762. });
  7763. },
  7764. onReceiveData: function ChunkedStreamManager_onReceiveData(args) {
  7765. var chunk = args.chunk;
  7766. var isProgressive = args.begin === undefined;
  7767. var begin = isProgressive ? this.progressiveDataLength : args.begin;
  7768. var end = begin + chunk.byteLength;
  7769. var beginChunk = Math.floor(begin / this.chunkSize);
  7770. var endChunk = end < this.length ? Math.floor(end / this.chunkSize) :
  7771. Math.ceil(end / this.chunkSize);
  7772. if (isProgressive) {
  7773. this.stream.onReceiveProgressiveData(chunk);
  7774. this.progressiveDataLength = end;
  7775. } else {
  7776. this.stream.onReceiveData(begin, chunk);
  7777. }
  7778. if (this.stream.allChunksLoaded()) {
  7779. this._loadedStreamCapability.resolve(this.stream);
  7780. }
  7781. var loadedRequests = [];
  7782. var i, requestId;
  7783. for (chunk = beginChunk; chunk < endChunk; ++chunk) {
  7784. // The server might return more chunks than requested
  7785. var requestIds = this.requestsByChunk[chunk] || [];
  7786. delete this.requestsByChunk[chunk];
  7787. for (i = 0; i < requestIds.length; ++i) {
  7788. requestId = requestIds[i];
  7789. var chunksNeeded = this.chunksNeededByRequest[requestId];
  7790. if (chunk in chunksNeeded) {
  7791. delete chunksNeeded[chunk];
  7792. }
  7793. if (!isEmptyObj(chunksNeeded)) {
  7794. continue;
  7795. }
  7796. loadedRequests.push(requestId);
  7797. }
  7798. }
  7799. // If there are no pending requests, automatically fetch the next
  7800. // unfetched chunk of the PDF
  7801. if (!this.disableAutoFetch && isEmptyObj(this.requestsByChunk)) {
  7802. var nextEmptyChunk;
  7803. if (this.stream.numChunksLoaded === 1) {
  7804. // This is a special optimization so that after fetching the first
  7805. // chunk, rather than fetching the second chunk, we fetch the last
  7806. // chunk.
  7807. var lastChunk = this.stream.numChunks - 1;
  7808. if (!this.stream.hasChunk(lastChunk)) {
  7809. nextEmptyChunk = lastChunk;
  7810. }
  7811. } else {
  7812. nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
  7813. }
  7814. if (isInt(nextEmptyChunk)) {
  7815. this.requestChunks([nextEmptyChunk]);
  7816. }
  7817. }
  7818. for (i = 0; i < loadedRequests.length; ++i) {
  7819. requestId = loadedRequests[i];
  7820. var callback = this.callbacksByRequest[requestId];
  7821. delete this.callbacksByRequest[requestId];
  7822. if (callback) {
  7823. callback();
  7824. }
  7825. }
  7826. this.msgHandler.send('DocProgress', {
  7827. loaded: this.stream.numChunksLoaded * this.chunkSize,
  7828. total: this.length
  7829. });
  7830. },
  7831. onError: function ChunkedStreamManager_onError(err) {
  7832. this._loadedStreamCapability.reject(err);
  7833. },
  7834. getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) {
  7835. var chunk = Math.floor(begin / this.chunkSize);
  7836. return chunk;
  7837. },
  7838. getEndChunk: function ChunkedStreamManager_getEndChunk(end) {
  7839. var chunk = Math.floor((end - 1) / this.chunkSize) + 1;
  7840. return chunk;
  7841. }
  7842. };
  7843. return ChunkedStreamManager;
  7844. })();
  7845. // The maximum number of bytes fetched per range request
  7846. var RANGE_CHUNK_SIZE = 65536;
  7847. // TODO(mack): Make use of PDFJS.Util.inherit() when it becomes available
  7848. var BasePdfManager = (function BasePdfManagerClosure() {
  7849. function BasePdfManager() {
  7850. throw new Error('Cannot initialize BaseManagerManager');
  7851. }
  7852. BasePdfManager.prototype = {
  7853. onLoadedStream: function BasePdfManager_onLoadedStream() {
  7854. throw new NotImplementedException();
  7855. },
  7856. ensureDoc: function BasePdfManager_ensureDoc(prop, args) {
  7857. return this.ensure(this.pdfDocument, prop, args);
  7858. },
  7859. ensureXRef: function BasePdfManager_ensureXRef(prop, args) {
  7860. return this.ensure(this.pdfDocument.xref, prop, args);
  7861. },
  7862. ensureCatalog: function BasePdfManager_ensureCatalog(prop, args) {
  7863. return this.ensure(this.pdfDocument.catalog, prop, args);
  7864. },
  7865. getPage: function BasePdfManager_pagePage(pageIndex) {
  7866. return this.pdfDocument.getPage(pageIndex);
  7867. },
  7868. cleanup: function BasePdfManager_cleanup() {
  7869. return this.pdfDocument.cleanup();
  7870. },
  7871. ensure: function BasePdfManager_ensure(obj, prop, args) {
  7872. return new NotImplementedException();
  7873. },
  7874. requestRange: function BasePdfManager_ensure(begin, end) {
  7875. return new NotImplementedException();
  7876. },
  7877. requestLoadedStream: function BasePdfManager_requestLoadedStream() {
  7878. return new NotImplementedException();
  7879. },
  7880. sendProgressiveData: function BasePdfManager_sendProgressiveData(chunk) {
  7881. return new NotImplementedException();
  7882. },
  7883. updatePassword: function BasePdfManager_updatePassword(password) {
  7884. this.pdfDocument.xref.password = this.password = password;
  7885. if (this._passwordChangedCapability) {
  7886. this._passwordChangedCapability.resolve();
  7887. }
  7888. },
  7889. passwordChanged: function BasePdfManager_passwordChanged() {
  7890. this._passwordChangedCapability = createPromiseCapability();
  7891. return this._passwordChangedCapability.promise;
  7892. },
  7893. terminate: function BasePdfManager_terminate() {
  7894. return new NotImplementedException();
  7895. }
  7896. };
  7897. return BasePdfManager;
  7898. })();
  7899. var LocalPdfManager = (function LocalPdfManagerClosure() {
  7900. function LocalPdfManager(data, password) {
  7901. var stream = new Stream(data);
  7902. this.pdfDocument = new PDFDocument(this, stream, password);
  7903. this._loadedStreamCapability = createPromiseCapability();
  7904. this._loadedStreamCapability.resolve(stream);
  7905. }
  7906. LocalPdfManager.prototype = Object.create(BasePdfManager.prototype);
  7907. LocalPdfManager.prototype.constructor = LocalPdfManager;
  7908. LocalPdfManager.prototype.ensure =
  7909. function LocalPdfManager_ensure(obj, prop, args) {
  7910. return new Promise(function (resolve, reject) {
  7911. try {
  7912. var value = obj[prop];
  7913. var result;
  7914. if (typeof value === 'function') {
  7915. result = value.apply(obj, args);
  7916. } else {
  7917. result = value;
  7918. }
  7919. resolve(result);
  7920. } catch (e) {
  7921. reject(e);
  7922. }
  7923. });
  7924. };
  7925. LocalPdfManager.prototype.requestRange =
  7926. function LocalPdfManager_requestRange(begin, end) {
  7927. return Promise.resolve();
  7928. };
  7929. LocalPdfManager.prototype.requestLoadedStream =
  7930. function LocalPdfManager_requestLoadedStream() {
  7931. };
  7932. LocalPdfManager.prototype.onLoadedStream =
  7933. function LocalPdfManager_getLoadedStream() {
  7934. return this._loadedStreamCapability.promise;
  7935. };
  7936. LocalPdfManager.prototype.terminate =
  7937. function LocalPdfManager_terminate() {
  7938. return;
  7939. };
  7940. return LocalPdfManager;
  7941. })();
  7942. var NetworkPdfManager = (function NetworkPdfManagerClosure() {
  7943. function NetworkPdfManager(args, msgHandler) {
  7944. this.msgHandler = msgHandler;
  7945. var params = {
  7946. msgHandler: msgHandler,
  7947. httpHeaders: args.httpHeaders,
  7948. withCredentials: args.withCredentials,
  7949. chunkedViewerLoading: args.chunkedViewerLoading,
  7950. disableAutoFetch: args.disableAutoFetch,
  7951. initialData: args.initialData
  7952. };
  7953. this.streamManager = new ChunkedStreamManager(args.length, RANGE_CHUNK_SIZE,
  7954. args.url, params);
  7955. this.pdfDocument = new PDFDocument(this, this.streamManager.getStream(),
  7956. args.password);
  7957. }
  7958. NetworkPdfManager.prototype = Object.create(BasePdfManager.prototype);
  7959. NetworkPdfManager.prototype.constructor = NetworkPdfManager;
  7960. NetworkPdfManager.prototype.ensure =
  7961. function NetworkPdfManager_ensure(obj, prop, args) {
  7962. var pdfManager = this;
  7963. return new Promise(function (resolve, reject) {
  7964. function ensureHelper() {
  7965. try {
  7966. var result;
  7967. var value = obj[prop];
  7968. if (typeof value === 'function') {
  7969. result = value.apply(obj, args);
  7970. } else {
  7971. result = value;
  7972. }
  7973. resolve(result);
  7974. } catch(e) {
  7975. if (!(e instanceof MissingDataException)) {
  7976. reject(e);
  7977. return;
  7978. }
  7979. pdfManager.streamManager.requestRange(e.begin, e.end, ensureHelper);
  7980. }
  7981. }
  7982. ensureHelper();
  7983. });
  7984. };
  7985. NetworkPdfManager.prototype.requestRange =
  7986. function NetworkPdfManager_requestRange(begin, end) {
  7987. return new Promise(function (resolve) {
  7988. this.streamManager.requestRange(begin, end, function() {
  7989. resolve();
  7990. });
  7991. }.bind(this));
  7992. };
  7993. NetworkPdfManager.prototype.requestLoadedStream =
  7994. function NetworkPdfManager_requestLoadedStream() {
  7995. this.streamManager.requestAllChunks();
  7996. };
  7997. NetworkPdfManager.prototype.sendProgressiveData =
  7998. function NetworkPdfManager_sendProgressiveData(chunk) {
  7999. this.streamManager.onReceiveData({ chunk: chunk });
  8000. };
  8001. NetworkPdfManager.prototype.onLoadedStream =
  8002. function NetworkPdfManager_getLoadedStream() {
  8003. return this.streamManager.onLoadedStream();
  8004. };
  8005. NetworkPdfManager.prototype.terminate =
  8006. function NetworkPdfManager_terminate() {
  8007. this.streamManager.networkManager.abortAllRequests();
  8008. };
  8009. return NetworkPdfManager;
  8010. })();
  8011. var Page = (function PageClosure() {
  8012. var LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
  8013. function Page(pdfManager, xref, pageIndex, pageDict, ref, fontCache) {
  8014. this.pdfManager = pdfManager;
  8015. this.pageIndex = pageIndex;
  8016. this.pageDict = pageDict;
  8017. this.xref = xref;
  8018. this.ref = ref;
  8019. this.fontCache = fontCache;
  8020. this.idCounters = {
  8021. obj: 0
  8022. };
  8023. this.resourcesPromise = null;
  8024. }
  8025. Page.prototype = {
  8026. getPageProp: function Page_getPageProp(key) {
  8027. return this.pageDict.get(key);
  8028. },
  8029. getInheritedPageProp: function Page_getInheritedPageProp(key) {
  8030. var dict = this.pageDict, valueArray = null, loopCount = 0;
  8031. var MAX_LOOP_COUNT = 100;
  8032. // Always walk up the entire parent chain, to be able to find
  8033. // e.g. \Resources placed on multiple levels of the tree.
  8034. while (dict) {
  8035. var value = dict.get(key);
  8036. if (value) {
  8037. if (!valueArray) {
  8038. valueArray = [];
  8039. }
  8040. valueArray.push(value);
  8041. }
  8042. if (++loopCount > MAX_LOOP_COUNT) {
  8043. warn('Page_getInheritedPageProp: maximum loop count exceeded.');
  8044. break;
  8045. }
  8046. dict = dict.get('Parent');
  8047. }
  8048. if (!valueArray) {
  8049. return Dict.empty;
  8050. }
  8051. if (valueArray.length === 1 || !isDict(valueArray[0]) ||
  8052. loopCount > MAX_LOOP_COUNT) {
  8053. return valueArray[0];
  8054. }
  8055. return Dict.merge(this.xref, valueArray);
  8056. },
  8057. get content() {
  8058. return this.getPageProp('Contents');
  8059. },
  8060. get resources() {
  8061. // For robustness: The spec states that a \Resources entry has to be
  8062. // present, but can be empty. Some document omit it still, in this case
  8063. // we return an empty dictionary.
  8064. return shadow(this, 'resources', this.getInheritedPageProp('Resources'));
  8065. },
  8066. get mediaBox() {
  8067. var obj = this.getInheritedPageProp('MediaBox');
  8068. // Reset invalid media box to letter size.
  8069. if (!isArray(obj) || obj.length !== 4) {
  8070. obj = LETTER_SIZE_MEDIABOX;
  8071. }
  8072. return shadow(this, 'mediaBox', obj);
  8073. },
  8074. get view() {
  8075. var mediaBox = this.mediaBox;
  8076. var cropBox = this.getInheritedPageProp('CropBox');
  8077. if (!isArray(cropBox) || cropBox.length !== 4) {
  8078. return shadow(this, 'view', mediaBox);
  8079. }
  8080. // From the spec, 6th ed., p.963:
  8081. // "The crop, bleed, trim, and art boxes should not ordinarily
  8082. // extend beyond the boundaries of the media box. If they do, they are
  8083. // effectively reduced to their intersection with the media box."
  8084. cropBox = Util.intersect(cropBox, mediaBox);
  8085. if (!cropBox) {
  8086. return shadow(this, 'view', mediaBox);
  8087. }
  8088. return shadow(this, 'view', cropBox);
  8089. },
  8090. get rotate() {
  8091. var rotate = this.getInheritedPageProp('Rotate') || 0;
  8092. // Normalize rotation so it's a multiple of 90 and between 0 and 270
  8093. if (rotate % 90 !== 0) {
  8094. rotate = 0;
  8095. } else if (rotate >= 360) {
  8096. rotate = rotate % 360;
  8097. } else if (rotate < 0) {
  8098. // The spec doesn't cover negatives, assume its counterclockwise
  8099. // rotation. The following is the other implementation of modulo.
  8100. rotate = ((rotate % 360) + 360) % 360;
  8101. }
  8102. return shadow(this, 'rotate', rotate);
  8103. },
  8104. getContentStream: function Page_getContentStream() {
  8105. var content = this.content;
  8106. var stream;
  8107. if (isArray(content)) {
  8108. // fetching items
  8109. var xref = this.xref;
  8110. var i, n = content.length;
  8111. var streams = [];
  8112. for (i = 0; i < n; ++i) {
  8113. streams.push(xref.fetchIfRef(content[i]));
  8114. }
  8115. stream = new StreamsSequenceStream(streams);
  8116. } else if (isStream(content)) {
  8117. stream = content;
  8118. } else {
  8119. // replacing non-existent page content with empty one
  8120. stream = new NullStream();
  8121. }
  8122. return stream;
  8123. },
  8124. loadResources: function Page_loadResources(keys) {
  8125. if (!this.resourcesPromise) {
  8126. // TODO: add async getInheritedPageProp and remove this.
  8127. this.resourcesPromise = this.pdfManager.ensure(this, 'resources');
  8128. }
  8129. return this.resourcesPromise.then(function resourceSuccess() {
  8130. var objectLoader = new ObjectLoader(this.resources.map,
  8131. keys,
  8132. this.xref);
  8133. return objectLoader.load();
  8134. }.bind(this));
  8135. },
  8136. getOperatorList: function Page_getOperatorList(handler, intent) {
  8137. var self = this;
  8138. var pdfManager = this.pdfManager;
  8139. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',
  8140. []);
  8141. var resourcesPromise = this.loadResources([
  8142. 'ExtGState',
  8143. 'ColorSpace',
  8144. 'Pattern',
  8145. 'Shading',
  8146. 'XObject',
  8147. 'Font'
  8148. // ProcSet
  8149. // Properties
  8150. ]);
  8151. var partialEvaluator = new PartialEvaluator(pdfManager, this.xref,
  8152. handler, this.pageIndex,
  8153. 'p' + this.pageIndex + '_',
  8154. this.idCounters,
  8155. this.fontCache);
  8156. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  8157. var pageListPromise = dataPromises.then(function(data) {
  8158. var contentStream = data[0];
  8159. var opList = new OperatorList(intent, handler, self.pageIndex);
  8160. handler.send('StartRenderPage', {
  8161. transparency: partialEvaluator.hasBlendModes(self.resources),
  8162. pageIndex: self.pageIndex,
  8163. intent: intent
  8164. });
  8165. return partialEvaluator.getOperatorList(contentStream, self.resources,
  8166. opList).then(function () {
  8167. return opList;
  8168. });
  8169. });
  8170. var annotationsPromise = pdfManager.ensure(this, 'annotations');
  8171. return Promise.all([pageListPromise, annotationsPromise]).then(
  8172. function(datas) {
  8173. var pageOpList = datas[0];
  8174. var annotations = datas[1];
  8175. if (annotations.length === 0) {
  8176. pageOpList.flush(true);
  8177. return pageOpList;
  8178. }
  8179. var annotationsReadyPromise = Annotation.appendToOperatorList(
  8180. annotations, pageOpList, pdfManager, partialEvaluator, intent);
  8181. return annotationsReadyPromise.then(function () {
  8182. pageOpList.flush(true);
  8183. return pageOpList;
  8184. });
  8185. });
  8186. },
  8187. extractTextContent: function Page_extractTextContent() {
  8188. var handler = {
  8189. on: function nullHandlerOn() {},
  8190. send: function nullHandlerSend() {}
  8191. };
  8192. var self = this;
  8193. var pdfManager = this.pdfManager;
  8194. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',
  8195. []);
  8196. var resourcesPromise = this.loadResources([
  8197. 'ExtGState',
  8198. 'XObject',
  8199. 'Font'
  8200. ]);
  8201. var dataPromises = Promise.all([contentStreamPromise,
  8202. resourcesPromise]);
  8203. return dataPromises.then(function(data) {
  8204. var contentStream = data[0];
  8205. var partialEvaluator = new PartialEvaluator(pdfManager, self.xref,
  8206. handler, self.pageIndex,
  8207. 'p' + self.pageIndex + '_',
  8208. self.idCounters,
  8209. self.fontCache);
  8210. return partialEvaluator.getTextContent(contentStream,
  8211. self.resources);
  8212. });
  8213. },
  8214. getAnnotationsData: function Page_getAnnotationsData() {
  8215. var annotations = this.annotations;
  8216. var annotationsData = [];
  8217. for (var i = 0, n = annotations.length; i < n; ++i) {
  8218. annotationsData.push(annotations[i].data);
  8219. }
  8220. return annotationsData;
  8221. },
  8222. get annotations() {
  8223. var annotations = [];
  8224. var annotationRefs = this.getInheritedPageProp('Annots') || [];
  8225. var annotationFactory = new AnnotationFactory();
  8226. for (var i = 0, n = annotationRefs.length; i < n; ++i) {
  8227. var annotationRef = annotationRefs[i];
  8228. var annotation = annotationFactory.create(this.xref, annotationRef);
  8229. if (annotation &&
  8230. (annotation.isViewable() || annotation.isPrintable())) {
  8231. annotations.push(annotation);
  8232. }
  8233. }
  8234. return shadow(this, 'annotations', annotations);
  8235. }
  8236. };
  8237. return Page;
  8238. })();
  8239. /**
  8240. * The `PDFDocument` holds all the data of the PDF file. Compared to the
  8241. * `PDFDoc`, this one doesn't have any job management code.
  8242. * Right now there exists one PDFDocument on the main thread + one object
  8243. * for each worker. If there is no worker support enabled, there are two
  8244. * `PDFDocument` objects on the main thread created.
  8245. */
  8246. var PDFDocument = (function PDFDocumentClosure() {
  8247. var FINGERPRINT_FIRST_BYTES = 1024;
  8248. var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' +
  8249. '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
  8250. function PDFDocument(pdfManager, arg, password) {
  8251. if (isStream(arg)) {
  8252. init.call(this, pdfManager, arg, password);
  8253. } else if (isArrayBuffer(arg)) {
  8254. init.call(this, pdfManager, new Stream(arg), password);
  8255. } else {
  8256. error('PDFDocument: Unknown argument type');
  8257. }
  8258. }
  8259. function init(pdfManager, stream, password) {
  8260. assert(stream.length > 0, 'stream must have data');
  8261. this.pdfManager = pdfManager;
  8262. this.stream = stream;
  8263. var xref = new XRef(this.stream, password, pdfManager);
  8264. this.xref = xref;
  8265. }
  8266. function find(stream, needle, limit, backwards) {
  8267. var pos = stream.pos;
  8268. var end = stream.end;
  8269. var strBuf = [];
  8270. if (pos + limit > end) {
  8271. limit = end - pos;
  8272. }
  8273. for (var n = 0; n < limit; ++n) {
  8274. strBuf.push(String.fromCharCode(stream.getByte()));
  8275. }
  8276. var str = strBuf.join('');
  8277. stream.pos = pos;
  8278. var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
  8279. if (index === -1) {
  8280. return false; /* not found */
  8281. }
  8282. stream.pos += index;
  8283. return true; /* found */
  8284. }
  8285. var DocumentInfoValidators = {
  8286. get entries() {
  8287. // Lazily build this since all the validation functions below are not
  8288. // defined until after this file loads.
  8289. return shadow(this, 'entries', {
  8290. Title: isString,
  8291. Author: isString,
  8292. Subject: isString,
  8293. Keywords: isString,
  8294. Creator: isString,
  8295. Producer: isString,
  8296. CreationDate: isString,
  8297. ModDate: isString,
  8298. Trapped: isName
  8299. });
  8300. }
  8301. };
  8302. PDFDocument.prototype = {
  8303. parse: function PDFDocument_parse(recoveryMode) {
  8304. this.setup(recoveryMode);
  8305. var version = this.catalog.catDict.get('Version');
  8306. if (isName(version)) {
  8307. this.pdfFormatVersion = version.name;
  8308. }
  8309. try {
  8310. // checking if AcroForm is present
  8311. this.acroForm = this.catalog.catDict.get('AcroForm');
  8312. if (this.acroForm) {
  8313. this.xfa = this.acroForm.get('XFA');
  8314. var fields = this.acroForm.get('Fields');
  8315. if ((!fields || !isArray(fields) || fields.length === 0) &&
  8316. !this.xfa) {
  8317. // no fields and no XFA -- not a form (?)
  8318. this.acroForm = null;
  8319. }
  8320. }
  8321. } catch (ex) {
  8322. info('Something wrong with AcroForm entry');
  8323. this.acroForm = null;
  8324. }
  8325. },
  8326. get linearization() {
  8327. var linearization = null;
  8328. if (this.stream.length) {
  8329. try {
  8330. linearization = Linearization.create(this.stream);
  8331. } catch (err) {
  8332. if (err instanceof MissingDataException) {
  8333. throw err;
  8334. }
  8335. info(err);
  8336. }
  8337. }
  8338. // shadow the prototype getter with a data property
  8339. return shadow(this, 'linearization', linearization);
  8340. },
  8341. get startXRef() {
  8342. var stream = this.stream;
  8343. var startXRef = 0;
  8344. var linearization = this.linearization;
  8345. if (linearization) {
  8346. // Find end of first obj.
  8347. stream.reset();
  8348. if (find(stream, 'endobj', 1024)) {
  8349. startXRef = stream.pos + 6;
  8350. }
  8351. } else {
  8352. // Find startxref by jumping backward from the end of the file.
  8353. var step = 1024;
  8354. var found = false, pos = stream.end;
  8355. while (!found && pos > 0) {
  8356. pos -= step - 'startxref'.length;
  8357. if (pos < 0) {
  8358. pos = 0;
  8359. }
  8360. stream.pos = pos;
  8361. found = find(stream, 'startxref', step, true);
  8362. }
  8363. if (found) {
  8364. stream.skip(9);
  8365. var ch;
  8366. do {
  8367. ch = stream.getByte();
  8368. } while (Lexer.isSpace(ch));
  8369. var str = '';
  8370. while (ch >= 0x20 && ch <= 0x39) { // < '9'
  8371. str += String.fromCharCode(ch);
  8372. ch = stream.getByte();
  8373. }
  8374. startXRef = parseInt(str, 10);
  8375. if (isNaN(startXRef)) {
  8376. startXRef = 0;
  8377. }
  8378. }
  8379. }
  8380. // shadow the prototype getter with a data property
  8381. return shadow(this, 'startXRef', startXRef);
  8382. },
  8383. get mainXRefEntriesOffset() {
  8384. var mainXRefEntriesOffset = 0;
  8385. var linearization = this.linearization;
  8386. if (linearization) {
  8387. mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
  8388. }
  8389. // shadow the prototype getter with a data property
  8390. return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
  8391. },
  8392. // Find the header, remove leading garbage and setup the stream
  8393. // starting from the header.
  8394. checkHeader: function PDFDocument_checkHeader() {
  8395. var stream = this.stream;
  8396. stream.reset();
  8397. if (find(stream, '%PDF-', 1024)) {
  8398. // Found the header, trim off any garbage before it.
  8399. stream.moveStart();
  8400. // Reading file format version
  8401. var MAX_VERSION_LENGTH = 12;
  8402. var version = '', ch;
  8403. while ((ch = stream.getByte()) > 0x20) { // SPACE
  8404. if (version.length >= MAX_VERSION_LENGTH) {
  8405. break;
  8406. }
  8407. version += String.fromCharCode(ch);
  8408. }
  8409. if (!this.pdfFormatVersion) {
  8410. // removing "%PDF-"-prefix
  8411. this.pdfFormatVersion = version.substring(5);
  8412. }
  8413. return;
  8414. }
  8415. // May not be a PDF file, continue anyway.
  8416. },
  8417. parseStartXRef: function PDFDocument_parseStartXRef() {
  8418. var startXRef = this.startXRef;
  8419. this.xref.setStartXRef(startXRef);
  8420. },
  8421. setup: function PDFDocument_setup(recoveryMode) {
  8422. this.xref.parse(recoveryMode);
  8423. this.catalog = new Catalog(this.pdfManager, this.xref);
  8424. },
  8425. get numPages() {
  8426. var linearization = this.linearization;
  8427. var num = linearization ? linearization.numPages : this.catalog.numPages;
  8428. // shadow the prototype getter
  8429. return shadow(this, 'numPages', num);
  8430. },
  8431. get documentInfo() {
  8432. var docInfo = {
  8433. PDFFormatVersion: this.pdfFormatVersion,
  8434. IsAcroFormPresent: !!this.acroForm,
  8435. IsXFAPresent: !!this.xfa
  8436. };
  8437. var infoDict;
  8438. try {
  8439. infoDict = this.xref.trailer.get('Info');
  8440. } catch (err) {
  8441. info('The document information dictionary is invalid.');
  8442. }
  8443. if (infoDict) {
  8444. var validEntries = DocumentInfoValidators.entries;
  8445. // Only fill the document info with valid entries from the spec.
  8446. for (var key in validEntries) {
  8447. if (infoDict.has(key)) {
  8448. var value = infoDict.get(key);
  8449. // Make sure the value conforms to the spec.
  8450. if (validEntries[key](value)) {
  8451. docInfo[key] = (typeof value !== 'string' ?
  8452. value : stringToPDFString(value));
  8453. } else {
  8454. info('Bad value in document info for "' + key + '"');
  8455. }
  8456. }
  8457. }
  8458. }
  8459. return shadow(this, 'documentInfo', docInfo);
  8460. },
  8461. get fingerprint() {
  8462. var xref = this.xref, hash, fileID = '';
  8463. var idArray = xref.trailer.get('ID');
  8464. if (idArray && isArray(idArray) && idArray[0] && isString(idArray[0]) &&
  8465. idArray[0] !== EMPTY_FINGERPRINT) {
  8466. hash = stringToBytes(idArray[0]);
  8467. } else {
  8468. if (this.stream.ensureRange) {
  8469. this.stream.ensureRange(0,
  8470. Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
  8471. }
  8472. hash = calculateMD5(this.stream.bytes.subarray(0,
  8473. FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  8474. }
  8475. for (var i = 0, n = hash.length; i < n; i++) {
  8476. var hex = hash[i].toString(16);
  8477. fileID += hex.length === 1 ? '0' + hex : hex;
  8478. }
  8479. return shadow(this, 'fingerprint', fileID);
  8480. },
  8481. getPage: function PDFDocument_getPage(pageIndex) {
  8482. return this.catalog.getPage(pageIndex);
  8483. },
  8484. cleanup: function PDFDocument_cleanup() {
  8485. return this.catalog.cleanup();
  8486. }
  8487. };
  8488. return PDFDocument;
  8489. })();
  8490. var Name = (function NameClosure() {
  8491. function Name(name) {
  8492. this.name = name;
  8493. }
  8494. Name.prototype = {};
  8495. var nameCache = {};
  8496. Name.get = function Name_get(name) {
  8497. var nameValue = nameCache[name];
  8498. return (nameValue ? nameValue : (nameCache[name] = new Name(name)));
  8499. };
  8500. return Name;
  8501. })();
  8502. var Cmd = (function CmdClosure() {
  8503. function Cmd(cmd) {
  8504. this.cmd = cmd;
  8505. }
  8506. Cmd.prototype = {};
  8507. var cmdCache = {};
  8508. Cmd.get = function Cmd_get(cmd) {
  8509. var cmdValue = cmdCache[cmd];
  8510. return (cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd)));
  8511. };
  8512. return Cmd;
  8513. })();
  8514. var Dict = (function DictClosure() {
  8515. var nonSerializable = function nonSerializableClosure() {
  8516. return nonSerializable; // creating closure on some variable
  8517. };
  8518. var GETALL_DICTIONARY_TYPES_WHITELIST = {
  8519. 'Background': true,
  8520. 'ExtGState': true,
  8521. 'Halftone': true,
  8522. 'Layout': true,
  8523. 'Mask': true,
  8524. 'Pagination': true,
  8525. 'Printing': true
  8526. };
  8527. function isRecursionAllowedFor(dict) {
  8528. if (!isName(dict.Type)) {
  8529. return true;
  8530. }
  8531. var dictType = dict.Type.name;
  8532. return GETALL_DICTIONARY_TYPES_WHITELIST[dictType] === true;
  8533. }
  8534. // xref is optional
  8535. function Dict(xref) {
  8536. // Map should only be used internally, use functions below to access.
  8537. this.map = Object.create(null);
  8538. this.xref = xref;
  8539. this.objId = null;
  8540. this.__nonSerializable__ = nonSerializable; // disable cloning of the Dict
  8541. }
  8542. Dict.prototype = {
  8543. assignXref: function Dict_assignXref(newXref) {
  8544. this.xref = newXref;
  8545. },
  8546. // automatically dereferences Ref objects
  8547. get: function Dict_get(key1, key2, key3) {
  8548. var value;
  8549. var xref = this.xref;
  8550. if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
  8551. typeof key2 === 'undefined') {
  8552. return xref ? xref.fetchIfRef(value) : value;
  8553. }
  8554. if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
  8555. typeof key3 === 'undefined') {
  8556. return xref ? xref.fetchIfRef(value) : value;
  8557. }
  8558. value = this.map[key3] || null;
  8559. return xref ? xref.fetchIfRef(value) : value;
  8560. },
  8561. // Same as get(), but returns a promise and uses fetchIfRefAsync().
  8562. getAsync: function Dict_getAsync(key1, key2, key3) {
  8563. var value;
  8564. var xref = this.xref;
  8565. if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
  8566. typeof key2 === 'undefined') {
  8567. if (xref) {
  8568. return xref.fetchIfRefAsync(value);
  8569. }
  8570. return Promise.resolve(value);
  8571. }
  8572. if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
  8573. typeof key3 === 'undefined') {
  8574. if (xref) {
  8575. return xref.fetchIfRefAsync(value);
  8576. }
  8577. return Promise.resolve(value);
  8578. }
  8579. value = this.map[key3] || null;
  8580. if (xref) {
  8581. return xref.fetchIfRefAsync(value);
  8582. }
  8583. return Promise.resolve(value);
  8584. },
  8585. // Same as get(), but dereferences all elements if the result is an Array.
  8586. getArray: function Dict_getArray(key1, key2, key3) {
  8587. var value = this.get(key1, key2, key3);
  8588. var xref = this.xref;
  8589. if (!isArray(value) || !xref) {
  8590. return value;
  8591. }
  8592. value = value.slice(); // Ensure that we don't modify the Dict data.
  8593. for (var i = 0, ii = value.length; i < ii; i++) {
  8594. if (!isRef(value[i])) {
  8595. continue;
  8596. }
  8597. value[i] = xref.fetch(value[i]);
  8598. }
  8599. return value;
  8600. },
  8601. // no dereferencing
  8602. getRaw: function Dict_getRaw(key) {
  8603. return this.map[key];
  8604. },
  8605. // creates new map and dereferences all Refs
  8606. getAll: function Dict_getAll() {
  8607. var all = Object.create(null);
  8608. var queue = null;
  8609. var key, obj;
  8610. for (key in this.map) {
  8611. obj = this.get(key);
  8612. if (obj instanceof Dict) {
  8613. if (isRecursionAllowedFor(obj)) {
  8614. (queue || (queue = [])).push({target: all, key: key, obj: obj});
  8615. } else {
  8616. all[key] = this.getRaw(key);
  8617. }
  8618. } else {
  8619. all[key] = obj;
  8620. }
  8621. }
  8622. if (!queue) {
  8623. return all;
  8624. }
  8625. // trying to take cyclic references into the account
  8626. var processed = Object.create(null);
  8627. while (queue.length > 0) {
  8628. var item = queue.shift();
  8629. var itemObj = item.obj;
  8630. var objId = itemObj.objId;
  8631. if (objId && objId in processed) {
  8632. item.target[item.key] = processed[objId];
  8633. continue;
  8634. }
  8635. var dereferenced = Object.create(null);
  8636. for (key in itemObj.map) {
  8637. obj = itemObj.get(key);
  8638. if (obj instanceof Dict) {
  8639. if (isRecursionAllowedFor(obj)) {
  8640. queue.push({target: dereferenced, key: key, obj: obj});
  8641. } else {
  8642. dereferenced[key] = itemObj.getRaw(key);
  8643. }
  8644. } else {
  8645. dereferenced[key] = obj;
  8646. }
  8647. }
  8648. if (objId) {
  8649. processed[objId] = dereferenced;
  8650. }
  8651. item.target[item.key] = dereferenced;
  8652. }
  8653. return all;
  8654. },
  8655. getKeys: function Dict_getKeys() {
  8656. return Object.keys(this.map);
  8657. },
  8658. set: function Dict_set(key, value) {
  8659. this.map[key] = value;
  8660. },
  8661. has: function Dict_has(key) {
  8662. return key in this.map;
  8663. },
  8664. forEach: function Dict_forEach(callback) {
  8665. for (var key in this.map) {
  8666. callback(key, this.get(key));
  8667. }
  8668. }
  8669. };
  8670. Dict.empty = new Dict(null);
  8671. Dict.merge = function Dict_merge(xref, dictArray) {
  8672. var mergedDict = new Dict(xref);
  8673. for (var i = 0, ii = dictArray.length; i < ii; i++) {
  8674. var dict = dictArray[i];
  8675. if (!isDict(dict)) {
  8676. continue;
  8677. }
  8678. for (var keyName in dict.map) {
  8679. if (mergedDict.map[keyName]) {
  8680. continue;
  8681. }
  8682. mergedDict.map[keyName] = dict.map[keyName];
  8683. }
  8684. }
  8685. return mergedDict;
  8686. };
  8687. return Dict;
  8688. })();
  8689. var Ref = (function RefClosure() {
  8690. function Ref(num, gen) {
  8691. this.num = num;
  8692. this.gen = gen;
  8693. }
  8694. Ref.prototype = {
  8695. toString: function Ref_toString() {
  8696. // This function is hot, so we make the string as compact as possible.
  8697. // |this.gen| is almost always zero, so we treat that case specially.
  8698. var str = this.num + 'R';
  8699. if (this.gen !== 0) {
  8700. str += this.gen;
  8701. }
  8702. return str;
  8703. }
  8704. };
  8705. return Ref;
  8706. })();
  8707. // The reference is identified by number and generation.
  8708. // This structure stores only one instance of the reference.
  8709. var RefSet = (function RefSetClosure() {
  8710. function RefSet() {
  8711. this.dict = {};
  8712. }
  8713. RefSet.prototype = {
  8714. has: function RefSet_has(ref) {
  8715. return ref.toString() in this.dict;
  8716. },
  8717. put: function RefSet_put(ref) {
  8718. this.dict[ref.toString()] = true;
  8719. },
  8720. remove: function RefSet_remove(ref) {
  8721. delete this.dict[ref.toString()];
  8722. }
  8723. };
  8724. return RefSet;
  8725. })();
  8726. var RefSetCache = (function RefSetCacheClosure() {
  8727. function RefSetCache() {
  8728. this.dict = Object.create(null);
  8729. }
  8730. RefSetCache.prototype = {
  8731. get: function RefSetCache_get(ref) {
  8732. return this.dict[ref.toString()];
  8733. },
  8734. has: function RefSetCache_has(ref) {
  8735. return ref.toString() in this.dict;
  8736. },
  8737. put: function RefSetCache_put(ref, obj) {
  8738. this.dict[ref.toString()] = obj;
  8739. },
  8740. putAlias: function RefSetCache_putAlias(ref, aliasRef) {
  8741. this.dict[ref.toString()] = this.get(aliasRef);
  8742. },
  8743. forEach: function RefSetCache_forEach(fn, thisArg) {
  8744. for (var i in this.dict) {
  8745. fn.call(thisArg, this.dict[i]);
  8746. }
  8747. },
  8748. clear: function RefSetCache_clear() {
  8749. this.dict = Object.create(null);
  8750. }
  8751. };
  8752. return RefSetCache;
  8753. })();
  8754. var Catalog = (function CatalogClosure() {
  8755. function Catalog(pdfManager, xref) {
  8756. this.pdfManager = pdfManager;
  8757. this.xref = xref;
  8758. this.catDict = xref.getCatalogObj();
  8759. this.fontCache = new RefSetCache();
  8760. assert(isDict(this.catDict),
  8761. 'catalog object is not a dictionary');
  8762. this.pagePromises = [];
  8763. }
  8764. Catalog.prototype = {
  8765. get metadata() {
  8766. var streamRef = this.catDict.getRaw('Metadata');
  8767. if (!isRef(streamRef)) {
  8768. return shadow(this, 'metadata', null);
  8769. }
  8770. var encryptMetadata = (!this.xref.encrypt ? false :
  8771. this.xref.encrypt.encryptMetadata);
  8772. var stream = this.xref.fetch(streamRef, !encryptMetadata);
  8773. var metadata;
  8774. if (stream && isDict(stream.dict)) {
  8775. var type = stream.dict.get('Type');
  8776. var subtype = stream.dict.get('Subtype');
  8777. if (isName(type) && isName(subtype) &&
  8778. type.name === 'Metadata' && subtype.name === 'XML') {
  8779. // XXX: This should examine the charset the XML document defines,
  8780. // however since there are currently no real means to decode
  8781. // arbitrary charsets, let's just hope that the author of the PDF
  8782. // was reasonable enough to stick with the XML default charset,
  8783. // which is UTF-8.
  8784. try {
  8785. metadata = stringToUTF8String(bytesToString(stream.getBytes()));
  8786. } catch (e) {
  8787. info('Skipping invalid metadata.');
  8788. }
  8789. }
  8790. }
  8791. return shadow(this, 'metadata', metadata);
  8792. },
  8793. get toplevelPagesDict() {
  8794. var pagesObj = this.catDict.get('Pages');
  8795. assert(isDict(pagesObj), 'invalid top-level pages dictionary');
  8796. // shadow the prototype getter
  8797. return shadow(this, 'toplevelPagesDict', pagesObj);
  8798. },
  8799. get documentOutline() {
  8800. var obj = null;
  8801. try {
  8802. obj = this.readDocumentOutline();
  8803. } catch (ex) {
  8804. if (ex instanceof MissingDataException) {
  8805. throw ex;
  8806. }
  8807. warn('Unable to read document outline');
  8808. }
  8809. return shadow(this, 'documentOutline', obj);
  8810. },
  8811. readDocumentOutline: function Catalog_readDocumentOutline() {
  8812. var xref = this.xref;
  8813. var obj = this.catDict.get('Outlines');
  8814. var root = { items: [] };
  8815. if (isDict(obj)) {
  8816. obj = obj.getRaw('First');
  8817. var processed = new RefSet();
  8818. if (isRef(obj)) {
  8819. var queue = [{obj: obj, parent: root}];
  8820. // to avoid recursion keeping track of the items
  8821. // in the processed dictionary
  8822. processed.put(obj);
  8823. while (queue.length > 0) {
  8824. var i = queue.shift();
  8825. var outlineDict = xref.fetchIfRef(i.obj);
  8826. if (outlineDict === null) {
  8827. continue;
  8828. }
  8829. if (!outlineDict.has('Title')) {
  8830. error('Invalid outline item');
  8831. }
  8832. var dest = outlineDict.get('A');
  8833. if (dest) {
  8834. dest = dest.get('D');
  8835. } else if (outlineDict.has('Dest')) {
  8836. dest = outlineDict.getRaw('Dest');
  8837. if (isName(dest)) {
  8838. dest = dest.name;
  8839. }
  8840. }
  8841. var title = outlineDict.get('Title');
  8842. var outlineItem = {
  8843. dest: dest,
  8844. title: stringToPDFString(title),
  8845. color: outlineDict.get('C') || [0, 0, 0],
  8846. count: outlineDict.get('Count'),
  8847. bold: !!(outlineDict.get('F') & 2),
  8848. italic: !!(outlineDict.get('F') & 1),
  8849. items: []
  8850. };
  8851. i.parent.items.push(outlineItem);
  8852. obj = outlineDict.getRaw('First');
  8853. if (isRef(obj) && !processed.has(obj)) {
  8854. queue.push({obj: obj, parent: outlineItem});
  8855. processed.put(obj);
  8856. }
  8857. obj = outlineDict.getRaw('Next');
  8858. if (isRef(obj) && !processed.has(obj)) {
  8859. queue.push({obj: obj, parent: i.parent});
  8860. processed.put(obj);
  8861. }
  8862. }
  8863. }
  8864. }
  8865. return (root.items.length > 0 ? root.items : null);
  8866. },
  8867. get numPages() {
  8868. var obj = this.toplevelPagesDict.get('Count');
  8869. assert(
  8870. isInt(obj),
  8871. 'page count in top level pages object is not an integer'
  8872. );
  8873. // shadow the prototype getter
  8874. return shadow(this, 'num', obj);
  8875. },
  8876. get destinations() {
  8877. function fetchDestination(dest) {
  8878. return isDict(dest) ? dest.get('D') : dest;
  8879. }
  8880. var xref = this.xref;
  8881. var dests = {}, nameTreeRef, nameDictionaryRef;
  8882. var obj = this.catDict.get('Names');
  8883. if (obj && obj.has('Dests')) {
  8884. nameTreeRef = obj.getRaw('Dests');
  8885. } else if (this.catDict.has('Dests')) {
  8886. nameDictionaryRef = this.catDict.get('Dests');
  8887. }
  8888. if (nameDictionaryRef) {
  8889. // reading simple destination dictionary
  8890. obj = nameDictionaryRef;
  8891. obj.forEach(function catalogForEach(key, value) {
  8892. if (!value) {
  8893. return;
  8894. }
  8895. dests[key] = fetchDestination(value);
  8896. });
  8897. }
  8898. if (nameTreeRef) {
  8899. var nameTree = new NameTree(nameTreeRef, xref);
  8900. var names = nameTree.getAll();
  8901. for (var name in names) {
  8902. if (!names.hasOwnProperty(name)) {
  8903. continue;
  8904. }
  8905. dests[name] = fetchDestination(names[name]);
  8906. }
  8907. }
  8908. return shadow(this, 'destinations', dests);
  8909. },
  8910. getDestination: function Catalog_getDestination(destinationId) {
  8911. function fetchDestination(dest) {
  8912. return isDict(dest) ? dest.get('D') : dest;
  8913. }
  8914. var xref = this.xref;
  8915. var dest = null, nameTreeRef, nameDictionaryRef;
  8916. var obj = this.catDict.get('Names');
  8917. if (obj && obj.has('Dests')) {
  8918. nameTreeRef = obj.getRaw('Dests');
  8919. } else if (this.catDict.has('Dests')) {
  8920. nameDictionaryRef = this.catDict.get('Dests');
  8921. }
  8922. if (nameDictionaryRef) { // Simple destination dictionary.
  8923. var value = nameDictionaryRef.get(destinationId);
  8924. if (value) {
  8925. dest = fetchDestination(value);
  8926. }
  8927. }
  8928. if (nameTreeRef) {
  8929. var nameTree = new NameTree(nameTreeRef, xref);
  8930. dest = fetchDestination(nameTree.get(destinationId));
  8931. }
  8932. return dest;
  8933. },
  8934. get attachments() {
  8935. var xref = this.xref;
  8936. var attachments = null, nameTreeRef;
  8937. var obj = this.catDict.get('Names');
  8938. if (obj) {
  8939. nameTreeRef = obj.getRaw('EmbeddedFiles');
  8940. }
  8941. if (nameTreeRef) {
  8942. var nameTree = new NameTree(nameTreeRef, xref);
  8943. var names = nameTree.getAll();
  8944. for (var name in names) {
  8945. if (!names.hasOwnProperty(name)) {
  8946. continue;
  8947. }
  8948. var fs = new FileSpec(names[name], xref);
  8949. if (!attachments) {
  8950. attachments = {};
  8951. }
  8952. attachments[stringToPDFString(name)] = fs.serializable;
  8953. }
  8954. }
  8955. return shadow(this, 'attachments', attachments);
  8956. },
  8957. get javaScript() {
  8958. var xref = this.xref;
  8959. var obj = this.catDict.get('Names');
  8960. var javaScript = [];
  8961. function appendIfJavaScriptDict(jsDict) {
  8962. var type = jsDict.get('S');
  8963. if (!isName(type) || type.name !== 'JavaScript') {
  8964. return;
  8965. }
  8966. var js = jsDict.get('JS');
  8967. if (isStream(js)) {
  8968. js = bytesToString(js.getBytes());
  8969. } else if (!isString(js)) {
  8970. return;
  8971. }
  8972. javaScript.push(stringToPDFString(js));
  8973. }
  8974. if (obj && obj.has('JavaScript')) {
  8975. var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);
  8976. var names = nameTree.getAll();
  8977. for (var name in names) {
  8978. if (!names.hasOwnProperty(name)) {
  8979. continue;
  8980. }
  8981. // We don't really use the JavaScript right now. This code is
  8982. // defensive so we don't cause errors on document load.
  8983. var jsDict = names[name];
  8984. if (isDict(jsDict)) {
  8985. appendIfJavaScriptDict(jsDict);
  8986. }
  8987. }
  8988. }
  8989. // Append OpenAction actions to javaScript array
  8990. var openactionDict = this.catDict.get('OpenAction');
  8991. if (isDict(openactionDict, 'Action')) {
  8992. var actionType = openactionDict.get('S');
  8993. if (isName(actionType) && actionType.name === 'Named') {
  8994. // The named Print action is not a part of the PDF 1.7 specification,
  8995. // but is supported by many PDF readers/writers (including Adobe's).
  8996. var action = openactionDict.get('N');
  8997. if (isName(action) && action.name === 'Print') {
  8998. javaScript.push('print({});');
  8999. }
  9000. } else {
  9001. appendIfJavaScriptDict(openactionDict);
  9002. }
  9003. }
  9004. return shadow(this, 'javaScript', javaScript);
  9005. },
  9006. cleanup: function Catalog_cleanup() {
  9007. var promises = [];
  9008. this.fontCache.forEach(function (promise) {
  9009. promises.push(promise);
  9010. });
  9011. return Promise.all(promises).then(function (translatedFonts) {
  9012. for (var i = 0, ii = translatedFonts.length; i < ii; i++) {
  9013. var font = translatedFonts[i].dict;
  9014. delete font.translated;
  9015. }
  9016. this.fontCache.clear();
  9017. }.bind(this));
  9018. },
  9019. getPage: function Catalog_getPage(pageIndex) {
  9020. if (!(pageIndex in this.pagePromises)) {
  9021. this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(
  9022. function (a) {
  9023. var dict = a[0];
  9024. var ref = a[1];
  9025. return new Page(this.pdfManager, this.xref, pageIndex, dict, ref,
  9026. this.fontCache);
  9027. }.bind(this)
  9028. );
  9029. }
  9030. return this.pagePromises[pageIndex];
  9031. },
  9032. getPageDict: function Catalog_getPageDict(pageIndex) {
  9033. var capability = createPromiseCapability();
  9034. var nodesToVisit = [this.catDict.getRaw('Pages')];
  9035. var currentPageIndex = 0;
  9036. var xref = this.xref;
  9037. var checkAllKids = false;
  9038. function next() {
  9039. while (nodesToVisit.length) {
  9040. var currentNode = nodesToVisit.pop();
  9041. if (isRef(currentNode)) {
  9042. xref.fetchAsync(currentNode).then(function (obj) {
  9043. if (isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids'))) {
  9044. if (pageIndex === currentPageIndex) {
  9045. capability.resolve([obj, currentNode]);
  9046. } else {
  9047. currentPageIndex++;
  9048. next();
  9049. }
  9050. return;
  9051. }
  9052. nodesToVisit.push(obj);
  9053. next();
  9054. }, capability.reject);
  9055. return;
  9056. }
  9057. // Must be a child page dictionary.
  9058. assert(
  9059. isDict(currentNode),
  9060. 'page dictionary kid reference points to wrong type of object'
  9061. );
  9062. var count = currentNode.get('Count');
  9063. // If the current node doesn't have any children, avoid getting stuck
  9064. // in an empty node further down in the tree (see issue5644.pdf).
  9065. if (count === 0) {
  9066. checkAllKids = true;
  9067. }
  9068. // Skip nodes where the page can't be.
  9069. if (currentPageIndex + count <= pageIndex) {
  9070. currentPageIndex += count;
  9071. continue;
  9072. }
  9073. var kids = currentNode.get('Kids');
  9074. assert(isArray(kids), 'page dictionary kids object is not an array');
  9075. if (!checkAllKids && count === kids.length) {
  9076. // Nodes that don't have the page have been skipped and this is the
  9077. // bottom of the tree which means the page requested must be a
  9078. // descendant of this pages node. Ideally we would just resolve the
  9079. // promise with the page ref here, but there is the case where more
  9080. // pages nodes could link to single a page (see issue 3666 pdf). To
  9081. // handle this push it back on the queue so if it is a pages node it
  9082. // will be descended into.
  9083. nodesToVisit = [kids[pageIndex - currentPageIndex]];
  9084. currentPageIndex = pageIndex;
  9085. continue;
  9086. } else {
  9087. for (var last = kids.length - 1; last >= 0; last--) {
  9088. nodesToVisit.push(kids[last]);
  9089. }
  9090. }
  9091. }
  9092. capability.reject('Page index ' + pageIndex + ' not found.');
  9093. }
  9094. next();
  9095. return capability.promise;
  9096. },
  9097. getPageIndex: function Catalog_getPageIndex(ref) {
  9098. // The page tree nodes have the count of all the leaves below them. To get
  9099. // how many pages are before we just have to walk up the tree and keep
  9100. // adding the count of siblings to the left of the node.
  9101. var xref = this.xref;
  9102. function pagesBeforeRef(kidRef) {
  9103. var total = 0;
  9104. var parentRef;
  9105. return xref.fetchAsync(kidRef).then(function (node) {
  9106. if (!node) {
  9107. return null;
  9108. }
  9109. parentRef = node.getRaw('Parent');
  9110. return node.getAsync('Parent');
  9111. }).then(function (parent) {
  9112. if (!parent) {
  9113. return null;
  9114. }
  9115. return parent.getAsync('Kids');
  9116. }).then(function (kids) {
  9117. if (!kids) {
  9118. return null;
  9119. }
  9120. var kidPromises = [];
  9121. var found = false;
  9122. for (var i = 0; i < kids.length; i++) {
  9123. var kid = kids[i];
  9124. assert(isRef(kid), 'kids must be a ref');
  9125. if (kid.num === kidRef.num) {
  9126. found = true;
  9127. break;
  9128. }
  9129. kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
  9130. if (kid.has('Count')) {
  9131. var count = kid.get('Count');
  9132. total += count;
  9133. } else { // page leaf node
  9134. total++;
  9135. }
  9136. }));
  9137. }
  9138. if (!found) {
  9139. error('kid ref not found in parents kids');
  9140. }
  9141. return Promise.all(kidPromises).then(function () {
  9142. return [total, parentRef];
  9143. });
  9144. });
  9145. }
  9146. var total = 0;
  9147. function next(ref) {
  9148. return pagesBeforeRef(ref).then(function (args) {
  9149. if (!args) {
  9150. return total;
  9151. }
  9152. var count = args[0];
  9153. var parentRef = args[1];
  9154. total += count;
  9155. return next(parentRef);
  9156. });
  9157. }
  9158. return next(ref);
  9159. }
  9160. };
  9161. return Catalog;
  9162. })();
  9163. var XRef = (function XRefClosure() {
  9164. function XRef(stream, password) {
  9165. this.stream = stream;
  9166. this.entries = [];
  9167. this.xrefstms = {};
  9168. // prepare the XRef cache
  9169. this.cache = [];
  9170. this.password = password;
  9171. this.stats = {
  9172. streamTypes: [],
  9173. fontTypes: []
  9174. };
  9175. }
  9176. XRef.prototype = {
  9177. setStartXRef: function XRef_setStartXRef(startXRef) {
  9178. // Store the starting positions of xref tables as we process them
  9179. // so we can recover from missing data errors
  9180. this.startXRefQueue = [startXRef];
  9181. },
  9182. parse: function XRef_parse(recoveryMode) {
  9183. var trailerDict;
  9184. if (!recoveryMode) {
  9185. trailerDict = this.readXRef();
  9186. } else {
  9187. warn('Indexing all PDF objects');
  9188. trailerDict = this.indexObjects();
  9189. }
  9190. trailerDict.assignXref(this);
  9191. this.trailer = trailerDict;
  9192. var encrypt = trailerDict.get('Encrypt');
  9193. if (encrypt) {
  9194. var ids = trailerDict.get('ID');
  9195. var fileId = (ids && ids.length) ? ids[0] : '';
  9196. this.encrypt = new CipherTransformFactory(encrypt, fileId,
  9197. this.password);
  9198. }
  9199. // get the root dictionary (catalog) object
  9200. if (!(this.root = trailerDict.get('Root'))) {
  9201. error('Invalid root reference');
  9202. }
  9203. },
  9204. processXRefTable: function XRef_processXRefTable(parser) {
  9205. if (!('tableState' in this)) {
  9206. // Stores state of the table as we process it so we can resume
  9207. // from middle of table in case of missing data error
  9208. this.tableState = {
  9209. entryNum: 0,
  9210. streamPos: parser.lexer.stream.pos,
  9211. parserBuf1: parser.buf1,
  9212. parserBuf2: parser.buf2
  9213. };
  9214. }
  9215. var obj = this.readXRefTable(parser);
  9216. // Sanity check
  9217. if (!isCmd(obj, 'trailer')) {
  9218. error('Invalid XRef table: could not find trailer dictionary');
  9219. }
  9220. // Read trailer dictionary, e.g.
  9221. // trailer
  9222. // << /Size 22
  9223. // /Root 20R
  9224. // /Info 10R
  9225. // /ID [ <81b14aafa313db63dbd6f981e49f94f4> ]
  9226. // >>
  9227. // The parser goes through the entire stream << ... >> and provides
  9228. // a getter interface for the key-value table
  9229. var dict = parser.getObj();
  9230. // The pdflib PDF generator can generate a nested trailer dictionary
  9231. if (!isDict(dict) && dict.dict) {
  9232. dict = dict.dict;
  9233. }
  9234. if (!isDict(dict)) {
  9235. error('Invalid XRef table: could not parse trailer dictionary');
  9236. }
  9237. delete this.tableState;
  9238. return dict;
  9239. },
  9240. readXRefTable: function XRef_readXRefTable(parser) {
  9241. // Example of cross-reference table:
  9242. // xref
  9243. // 0 1 <-- subsection header (first obj #, obj count)
  9244. // 0000000000 65535 f <-- actual object (offset, generation #, f/n)
  9245. // 23 2 <-- subsection header ... and so on ...
  9246. // 0000025518 00002 n
  9247. // 0000025635 00000 n
  9248. // trailer
  9249. // ...
  9250. var stream = parser.lexer.stream;
  9251. var tableState = this.tableState;
  9252. stream.pos = tableState.streamPos;
  9253. parser.buf1 = tableState.parserBuf1;
  9254. parser.buf2 = tableState.parserBuf2;
  9255. // Outer loop is over subsection headers
  9256. var obj;
  9257. while (true) {
  9258. if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {
  9259. if (isCmd(obj = parser.getObj(), 'trailer')) {
  9260. break;
  9261. }
  9262. tableState.firstEntryNum = obj;
  9263. tableState.entryCount = parser.getObj();
  9264. }
  9265. var first = tableState.firstEntryNum;
  9266. var count = tableState.entryCount;
  9267. if (!isInt(first) || !isInt(count)) {
  9268. error('Invalid XRef table: wrong types in subsection header');
  9269. }
  9270. // Inner loop is over objects themselves
  9271. for (var i = tableState.entryNum; i < count; i++) {
  9272. tableState.streamPos = stream.pos;
  9273. tableState.entryNum = i;
  9274. tableState.parserBuf1 = parser.buf1;
  9275. tableState.parserBuf2 = parser.buf2;
  9276. var entry = {};
  9277. entry.offset = parser.getObj();
  9278. entry.gen = parser.getObj();
  9279. var type = parser.getObj();
  9280. if (isCmd(type, 'f')) {
  9281. entry.free = true;
  9282. } else if (isCmd(type, 'n')) {
  9283. entry.uncompressed = true;
  9284. }
  9285. // Validate entry obj
  9286. if (!isInt(entry.offset) || !isInt(entry.gen) ||
  9287. !(entry.free || entry.uncompressed)) {
  9288. error('Invalid entry in XRef subsection: ' + first + ', ' + count);
  9289. }
  9290. if (!this.entries[i + first]) {
  9291. this.entries[i + first] = entry;
  9292. }
  9293. }
  9294. tableState.entryNum = 0;
  9295. tableState.streamPos = stream.pos;
  9296. tableState.parserBuf1 = parser.buf1;
  9297. tableState.parserBuf2 = parser.buf2;
  9298. delete tableState.firstEntryNum;
  9299. delete tableState.entryCount;
  9300. }
  9301. // Per issue 3248: hp scanners generate bad XRef
  9302. if (first === 1 && this.entries[1] && this.entries[1].free) {
  9303. // shifting the entries
  9304. this.entries.shift();
  9305. }
  9306. // Sanity check: as per spec, first object must be free
  9307. if (this.entries[0] && !this.entries[0].free) {
  9308. error('Invalid XRef table: unexpected first object');
  9309. }
  9310. return obj;
  9311. },
  9312. processXRefStream: function XRef_processXRefStream(stream) {
  9313. if (!('streamState' in this)) {
  9314. // Stores state of the stream as we process it so we can resume
  9315. // from middle of stream in case of missing data error
  9316. var streamParameters = stream.dict;
  9317. var byteWidths = streamParameters.get('W');
  9318. var range = streamParameters.get('Index');
  9319. if (!range) {
  9320. range = [0, streamParameters.get('Size')];
  9321. }
  9322. this.streamState = {
  9323. entryRanges: range,
  9324. byteWidths: byteWidths,
  9325. entryNum: 0,
  9326. streamPos: stream.pos
  9327. };
  9328. }
  9329. this.readXRefStream(stream);
  9330. delete this.streamState;
  9331. return stream.dict;
  9332. },
  9333. readXRefStream: function XRef_readXRefStream(stream) {
  9334. var i, j;
  9335. var streamState = this.streamState;
  9336. stream.pos = streamState.streamPos;
  9337. var byteWidths = streamState.byteWidths;
  9338. var typeFieldWidth = byteWidths[0];
  9339. var offsetFieldWidth = byteWidths[1];
  9340. var generationFieldWidth = byteWidths[2];
  9341. var entryRanges = streamState.entryRanges;
  9342. while (entryRanges.length > 0) {
  9343. var first = entryRanges[0];
  9344. var n = entryRanges[1];
  9345. if (!isInt(first) || !isInt(n)) {
  9346. error('Invalid XRef range fields: ' + first + ', ' + n);
  9347. }
  9348. if (!isInt(typeFieldWidth) || !isInt(offsetFieldWidth) ||
  9349. !isInt(generationFieldWidth)) {
  9350. error('Invalid XRef entry fields length: ' + first + ', ' + n);
  9351. }
  9352. for (i = streamState.entryNum; i < n; ++i) {
  9353. streamState.entryNum = i;
  9354. streamState.streamPos = stream.pos;
  9355. var type = 0, offset = 0, generation = 0;
  9356. for (j = 0; j < typeFieldWidth; ++j) {
  9357. type = (type << 8) | stream.getByte();
  9358. }
  9359. // if type field is absent, its default value is 1
  9360. if (typeFieldWidth === 0) {
  9361. type = 1;
  9362. }
  9363. for (j = 0; j < offsetFieldWidth; ++j) {
  9364. offset = (offset << 8) | stream.getByte();
  9365. }
  9366. for (j = 0; j < generationFieldWidth; ++j) {
  9367. generation = (generation << 8) | stream.getByte();
  9368. }
  9369. var entry = {};
  9370. entry.offset = offset;
  9371. entry.gen = generation;
  9372. switch (type) {
  9373. case 0:
  9374. entry.free = true;
  9375. break;
  9376. case 1:
  9377. entry.uncompressed = true;
  9378. break;
  9379. case 2:
  9380. break;
  9381. default:
  9382. error('Invalid XRef entry type: ' + type);
  9383. }
  9384. if (!this.entries[first + i]) {
  9385. this.entries[first + i] = entry;
  9386. }
  9387. }
  9388. streamState.entryNum = 0;
  9389. streamState.streamPos = stream.pos;
  9390. entryRanges.splice(0, 2);
  9391. }
  9392. },
  9393. indexObjects: function XRef_indexObjects() {
  9394. // Simple scan through the PDF content to find objects,
  9395. // trailers and XRef streams.
  9396. var TAB = 0x9, LF = 0xA, CR = 0xD, SPACE = 0x20;
  9397. var PERCENT = 0x25, LT = 0x3C;
  9398. function readToken(data, offset) {
  9399. var token = '', ch = data[offset];
  9400. while (ch !== LF && ch !== CR && ch !== LT) {
  9401. if (++offset >= data.length) {
  9402. break;
  9403. }
  9404. token += String.fromCharCode(ch);
  9405. ch = data[offset];
  9406. }
  9407. return token;
  9408. }
  9409. function skipUntil(data, offset, what) {
  9410. var length = what.length, dataLength = data.length;
  9411. var skipped = 0;
  9412. // finding byte sequence
  9413. while (offset < dataLength) {
  9414. var i = 0;
  9415. while (i < length && data[offset + i] === what[i]) {
  9416. ++i;
  9417. }
  9418. if (i >= length) {
  9419. break; // sequence found
  9420. }
  9421. offset++;
  9422. skipped++;
  9423. }
  9424. return skipped;
  9425. }
  9426. var objRegExp = /^(\d+)\s+(\d+)\s+obj\b/;
  9427. var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
  9428. var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114,
  9429. 101, 102]);
  9430. var endobjBytes = new Uint8Array([101, 110, 100, 111, 98, 106]);
  9431. var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
  9432. // Clear out any existing entries, since they may be bogus.
  9433. this.entries.length = 0;
  9434. var stream = this.stream;
  9435. stream.pos = 0;
  9436. var buffer = stream.getBytes();
  9437. var position = stream.start, length = buffer.length;
  9438. var trailers = [], xrefStms = [];
  9439. while (position < length) {
  9440. var ch = buffer[position];
  9441. if (ch === TAB || ch === LF || ch === CR || ch === SPACE) {
  9442. ++position;
  9443. continue;
  9444. }
  9445. if (ch === PERCENT) { // %-comment
  9446. do {
  9447. ++position;
  9448. if (position >= length) {
  9449. break;
  9450. }
  9451. ch = buffer[position];
  9452. } while (ch !== LF && ch !== CR);
  9453. continue;
  9454. }
  9455. var token = readToken(buffer, position);
  9456. var m;
  9457. if (token.indexOf('xref') === 0 &&
  9458. (token.length === 4 || /\s/.test(token[4]))) {
  9459. position += skipUntil(buffer, position, trailerBytes);
  9460. trailers.push(position);
  9461. position += skipUntil(buffer, position, startxrefBytes);
  9462. } else if ((m = objRegExp.exec(token))) {
  9463. if (typeof this.entries[m[1]] === 'undefined') {
  9464. this.entries[m[1]] = {
  9465. offset: position - stream.start,
  9466. gen: m[2] | 0,
  9467. uncompressed: true
  9468. };
  9469. }
  9470. var contentLength = skipUntil(buffer, position, endobjBytes) + 7;
  9471. var content = buffer.subarray(position, position + contentLength);
  9472. // checking XRef stream suspect
  9473. // (it shall have '/XRef' and next char is not a letter)
  9474. var xrefTagOffset = skipUntil(content, 0, xrefBytes);
  9475. if (xrefTagOffset < contentLength &&
  9476. content[xrefTagOffset + 5] < 64) {
  9477. xrefStms.push(position - stream.start);
  9478. this.xrefstms[position - stream.start] = 1; // Avoid recursion
  9479. }
  9480. position += contentLength;
  9481. } else if (token.indexOf('trailer') === 0 &&
  9482. (token.length === 7 || /\s/.test(token[7]))) {
  9483. trailers.push(position);
  9484. position += skipUntil(buffer, position, startxrefBytes);
  9485. } else {
  9486. position += token.length + 1;
  9487. }
  9488. }
  9489. // reading XRef streams
  9490. var i, ii;
  9491. for (i = 0, ii = xrefStms.length; i < ii; ++i) {
  9492. this.startXRefQueue.push(xrefStms[i]);
  9493. this.readXRef(/* recoveryMode */ true);
  9494. }
  9495. // finding main trailer
  9496. var dict;
  9497. for (i = 0, ii = trailers.length; i < ii; ++i) {
  9498. stream.pos = trailers[i];
  9499. var parser = new Parser(new Lexer(stream), true, this);
  9500. var obj = parser.getObj();
  9501. if (!isCmd(obj, 'trailer')) {
  9502. continue;
  9503. }
  9504. // read the trailer dictionary
  9505. if (!isDict(dict = parser.getObj())) {
  9506. continue;
  9507. }
  9508. // taking the first one with 'ID'
  9509. if (dict.has('ID')) {
  9510. return dict;
  9511. }
  9512. }
  9513. // no tailer with 'ID', taking last one (if exists)
  9514. if (dict) {
  9515. return dict;
  9516. }
  9517. // nothing helps
  9518. // calling error() would reject worker with an UnknownErrorException.
  9519. throw new InvalidPDFException('Invalid PDF structure');
  9520. },
  9521. readXRef: function XRef_readXRef(recoveryMode) {
  9522. var stream = this.stream;
  9523. try {
  9524. while (this.startXRefQueue.length) {
  9525. var startXRef = this.startXRefQueue[0];
  9526. stream.pos = startXRef + stream.start;
  9527. var parser = new Parser(new Lexer(stream), true, this);
  9528. var obj = parser.getObj();
  9529. var dict;
  9530. // Get dictionary
  9531. if (isCmd(obj, 'xref')) {
  9532. // Parse end-of-file XRef
  9533. dict = this.processXRefTable(parser);
  9534. if (!this.topDict) {
  9535. this.topDict = dict;
  9536. }
  9537. // Recursively get other XRefs 'XRefStm', if any
  9538. obj = dict.get('XRefStm');
  9539. if (isInt(obj)) {
  9540. var pos = obj;
  9541. // ignore previously loaded xref streams
  9542. // (possible infinite recursion)
  9543. if (!(pos in this.xrefstms)) {
  9544. this.xrefstms[pos] = 1;
  9545. this.startXRefQueue.push(pos);
  9546. }
  9547. }
  9548. } else if (isInt(obj)) {
  9549. // Parse in-stream XRef
  9550. if (!isInt(parser.getObj()) ||
  9551. !isCmd(parser.getObj(), 'obj') ||
  9552. !isStream(obj = parser.getObj())) {
  9553. error('Invalid XRef stream');
  9554. }
  9555. dict = this.processXRefStream(obj);
  9556. if (!this.topDict) {
  9557. this.topDict = dict;
  9558. }
  9559. if (!dict) {
  9560. error('Failed to read XRef stream');
  9561. }
  9562. } else {
  9563. error('Invalid XRef stream header');
  9564. }
  9565. // Recursively get previous dictionary, if any
  9566. obj = dict.get('Prev');
  9567. if (isInt(obj)) {
  9568. this.startXRefQueue.push(obj);
  9569. } else if (isRef(obj)) {
  9570. // The spec says Prev must not be a reference, i.e. "/Prev NNN"
  9571. // This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R"
  9572. this.startXRefQueue.push(obj.num);
  9573. }
  9574. this.startXRefQueue.shift();
  9575. }
  9576. return this.topDict;
  9577. } catch (e) {
  9578. if (e instanceof MissingDataException) {
  9579. throw e;
  9580. }
  9581. info('(while reading XRef): ' + e);
  9582. }
  9583. if (recoveryMode) {
  9584. return;
  9585. }
  9586. throw new XRefParseException();
  9587. },
  9588. getEntry: function XRef_getEntry(i) {
  9589. var xrefEntry = this.entries[i];
  9590. if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
  9591. return xrefEntry;
  9592. }
  9593. return null;
  9594. },
  9595. fetchIfRef: function XRef_fetchIfRef(obj) {
  9596. if (!isRef(obj)) {
  9597. return obj;
  9598. }
  9599. return this.fetch(obj);
  9600. },
  9601. fetch: function XRef_fetch(ref, suppressEncryption) {
  9602. assert(isRef(ref), 'ref object is not a reference');
  9603. var num = ref.num;
  9604. if (num in this.cache) {
  9605. var cacheEntry = this.cache[num];
  9606. return cacheEntry;
  9607. }
  9608. var xrefEntry = this.getEntry(num);
  9609. // the referenced entry can be free
  9610. if (xrefEntry === null) {
  9611. return (this.cache[num] = null);
  9612. }
  9613. if (xrefEntry.uncompressed) {
  9614. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  9615. } else {
  9616. xrefEntry = this.fetchCompressed(xrefEntry, suppressEncryption);
  9617. }
  9618. if (isDict(xrefEntry)){
  9619. xrefEntry.objId = ref.toString();
  9620. } else if (isStream(xrefEntry)) {
  9621. xrefEntry.dict.objId = ref.toString();
  9622. }
  9623. return xrefEntry;
  9624. },
  9625. fetchUncompressed: function XRef_fetchUncompressed(ref, xrefEntry,
  9626. suppressEncryption) {
  9627. var gen = ref.gen;
  9628. var num = ref.num;
  9629. if (xrefEntry.gen !== gen) {
  9630. error('inconsistent generation in XRef');
  9631. }
  9632. var stream = this.stream.makeSubStream(xrefEntry.offset +
  9633. this.stream.start);
  9634. var parser = new Parser(new Lexer(stream), true, this);
  9635. var obj1 = parser.getObj();
  9636. var obj2 = parser.getObj();
  9637. var obj3 = parser.getObj();
  9638. if (!isInt(obj1) || parseInt(obj1, 10) !== num ||
  9639. !isInt(obj2) || parseInt(obj2, 10) !== gen ||
  9640. !isCmd(obj3)) {
  9641. error('bad XRef entry');
  9642. }
  9643. if (!isCmd(obj3, 'obj')) {
  9644. // some bad PDFs use "obj1234" and really mean 1234
  9645. if (obj3.cmd.indexOf('obj') === 0) {
  9646. num = parseInt(obj3.cmd.substring(3), 10);
  9647. if (!isNaN(num)) {
  9648. return num;
  9649. }
  9650. }
  9651. error('bad XRef entry');
  9652. }
  9653. if (this.encrypt && !suppressEncryption) {
  9654. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  9655. } else {
  9656. xrefEntry = parser.getObj();
  9657. }
  9658. if (!isStream(xrefEntry)) {
  9659. this.cache[num] = xrefEntry;
  9660. }
  9661. return xrefEntry;
  9662. },
  9663. fetchCompressed: function XRef_fetchCompressed(xrefEntry,
  9664. suppressEncryption) {
  9665. var tableOffset = xrefEntry.offset;
  9666. var stream = this.fetch(new Ref(tableOffset, 0));
  9667. if (!isStream(stream)) {
  9668. error('bad ObjStm stream');
  9669. }
  9670. var first = stream.dict.get('First');
  9671. var n = stream.dict.get('N');
  9672. if (!isInt(first) || !isInt(n)) {
  9673. error('invalid first and n parameters for ObjStm stream');
  9674. }
  9675. var parser = new Parser(new Lexer(stream), false, this);
  9676. parser.allowStreams = true;
  9677. var i, entries = [], num, nums = [];
  9678. // read the object numbers to populate cache
  9679. for (i = 0; i < n; ++i) {
  9680. num = parser.getObj();
  9681. if (!isInt(num)) {
  9682. error('invalid object number in the ObjStm stream: ' + num);
  9683. }
  9684. nums.push(num);
  9685. var offset = parser.getObj();
  9686. if (!isInt(offset)) {
  9687. error('invalid object offset in the ObjStm stream: ' + offset);
  9688. }
  9689. }
  9690. // read stream objects for cache
  9691. for (i = 0; i < n; ++i) {
  9692. entries.push(parser.getObj());
  9693. num = nums[i];
  9694. var entry = this.entries[num];
  9695. if (entry && entry.offset === tableOffset && entry.gen === i) {
  9696. this.cache[num] = entries[i];
  9697. }
  9698. }
  9699. xrefEntry = entries[xrefEntry.gen];
  9700. if (xrefEntry === undefined) {
  9701. error('bad XRef entry for compressed object');
  9702. }
  9703. return xrefEntry;
  9704. },
  9705. fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) {
  9706. if (!isRef(obj)) {
  9707. return Promise.resolve(obj);
  9708. }
  9709. return this.fetchAsync(obj);
  9710. },
  9711. fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
  9712. var streamManager = this.stream.manager;
  9713. var xref = this;
  9714. return new Promise(function tryFetch(resolve, reject) {
  9715. try {
  9716. resolve(xref.fetch(ref, suppressEncryption));
  9717. } catch (e) {
  9718. if (e instanceof MissingDataException) {
  9719. streamManager.requestRange(e.begin, e.end, function () {
  9720. tryFetch(resolve, reject);
  9721. });
  9722. return;
  9723. }
  9724. reject(e);
  9725. }
  9726. });
  9727. },
  9728. getCatalogObj: function XRef_getCatalogObj() {
  9729. return this.root;
  9730. }
  9731. };
  9732. return XRef;
  9733. })();
  9734. /**
  9735. * A NameTree is like a Dict but has some advantageous properties, see the
  9736. * spec (7.9.6) for more details.
  9737. * TODO: implement all the Dict functions and make this more efficent.
  9738. */
  9739. var NameTree = (function NameTreeClosure() {
  9740. function NameTree(root, xref) {
  9741. this.root = root;
  9742. this.xref = xref;
  9743. }
  9744. NameTree.prototype = {
  9745. getAll: function NameTree_getAll() {
  9746. var dict = {};
  9747. if (!this.root) {
  9748. return dict;
  9749. }
  9750. var xref = this.xref;
  9751. // reading name tree
  9752. var processed = new RefSet();
  9753. processed.put(this.root);
  9754. var queue = [this.root];
  9755. while (queue.length > 0) {
  9756. var i, n;
  9757. var obj = xref.fetchIfRef(queue.shift());
  9758. if (!isDict(obj)) {
  9759. continue;
  9760. }
  9761. if (obj.has('Kids')) {
  9762. var kids = obj.get('Kids');
  9763. for (i = 0, n = kids.length; i < n; i++) {
  9764. var kid = kids[i];
  9765. if (processed.has(kid)) {
  9766. error('invalid destinations');
  9767. }
  9768. queue.push(kid);
  9769. processed.put(kid);
  9770. }
  9771. continue;
  9772. }
  9773. var names = obj.get('Names');
  9774. if (names) {
  9775. for (i = 0, n = names.length; i < n; i += 2) {
  9776. dict[xref.fetchIfRef(names[i])] = xref.fetchIfRef(names[i + 1]);
  9777. }
  9778. }
  9779. }
  9780. return dict;
  9781. },
  9782. get: function NameTree_get(destinationId) {
  9783. if (!this.root) {
  9784. return null;
  9785. }
  9786. var xref = this.xref;
  9787. var kidsOrNames = xref.fetchIfRef(this.root);
  9788. var loopCount = 0;
  9789. var MAX_NAMES_LEVELS = 10;
  9790. var l, r, m;
  9791. // Perform a binary search to quickly find the entry that
  9792. // contains the named destination we are looking for.
  9793. while (kidsOrNames.has('Kids')) {
  9794. loopCount++;
  9795. if (loopCount > MAX_NAMES_LEVELS) {
  9796. warn('Search depth limit for named destionations has been reached.');
  9797. return null;
  9798. }
  9799. var kids = kidsOrNames.get('Kids');
  9800. if (!isArray(kids)) {
  9801. return null;
  9802. }
  9803. l = 0;
  9804. r = kids.length - 1;
  9805. while (l <= r) {
  9806. m = (l + r) >> 1;
  9807. var kid = xref.fetchIfRef(kids[m]);
  9808. var limits = kid.get('Limits');
  9809. if (destinationId < xref.fetchIfRef(limits[0])) {
  9810. r = m - 1;
  9811. } else if (destinationId > xref.fetchIfRef(limits[1])) {
  9812. l = m + 1;
  9813. } else {
  9814. kidsOrNames = xref.fetchIfRef(kids[m]);
  9815. break;
  9816. }
  9817. }
  9818. if (l > r) {
  9819. return null;
  9820. }
  9821. }
  9822. // If we get here, then we have found the right entry. Now
  9823. // go through the named destinations in the Named dictionary
  9824. // until we find the exact destination we're looking for.
  9825. var names = kidsOrNames.get('Names');
  9826. if (isArray(names)) {
  9827. // Perform a binary search to reduce the lookup time.
  9828. l = 0;
  9829. r = names.length - 2;
  9830. while (l <= r) {
  9831. // Check only even indices (0, 2, 4, ...) because the
  9832. // odd indices contain the actual D array.
  9833. m = (l + r) & ~1;
  9834. if (destinationId < xref.fetchIfRef(names[m])) {
  9835. r = m - 2;
  9836. } else if (destinationId > xref.fetchIfRef(names[m])) {
  9837. l = m + 2;
  9838. } else {
  9839. return xref.fetchIfRef(names[m + 1]);
  9840. }
  9841. }
  9842. }
  9843. return null;
  9844. }
  9845. };
  9846. return NameTree;
  9847. })();
  9848. /**
  9849. * "A PDF file can refer to the contents of another file by using a File
  9850. * Specification (PDF 1.1)", see the spec (7.11) for more details.
  9851. * NOTE: Only embedded files are supported (as part of the attachments support)
  9852. * TODO: support the 'URL' file system (with caching if !/V), portable
  9853. * collections attributes and related files (/RF)
  9854. */
  9855. var FileSpec = (function FileSpecClosure() {
  9856. function FileSpec(root, xref) {
  9857. if (!root || !isDict(root)) {
  9858. return;
  9859. }
  9860. this.xref = xref;
  9861. this.root = root;
  9862. if (root.has('FS')) {
  9863. this.fs = root.get('FS');
  9864. }
  9865. this.description = root.has('Desc') ?
  9866. stringToPDFString(root.get('Desc')) :
  9867. '';
  9868. if (root.has('RF')) {
  9869. warn('Related file specifications are not supported');
  9870. }
  9871. this.contentAvailable = true;
  9872. if (!root.has('EF')) {
  9873. this.contentAvailable = false;
  9874. warn('Non-embedded file specifications are not supported');
  9875. }
  9876. }
  9877. function pickPlatformItem(dict) {
  9878. // Look for the filename in this order:
  9879. // UF, F, Unix, Mac, DOS
  9880. if (dict.has('UF')) {
  9881. return dict.get('UF');
  9882. } else if (dict.has('F')) {
  9883. return dict.get('F');
  9884. } else if (dict.has('Unix')) {
  9885. return dict.get('Unix');
  9886. } else if (dict.has('Mac')) {
  9887. return dict.get('Mac');
  9888. } else if (dict.has('DOS')) {
  9889. return dict.get('DOS');
  9890. } else {
  9891. return null;
  9892. }
  9893. }
  9894. FileSpec.prototype = {
  9895. get filename() {
  9896. if (!this._filename && this.root) {
  9897. var filename = pickPlatformItem(this.root) || 'unnamed';
  9898. this._filename = stringToPDFString(filename).
  9899. replace(/\\\\/g, '\\').
  9900. replace(/\\\//g, '/').
  9901. replace(/\\/g, '/');
  9902. }
  9903. return this._filename;
  9904. },
  9905. get content() {
  9906. if (!this.contentAvailable) {
  9907. return null;
  9908. }
  9909. if (!this.contentRef && this.root) {
  9910. this.contentRef = pickPlatformItem(this.root.get('EF'));
  9911. }
  9912. var content = null;
  9913. if (this.contentRef) {
  9914. var xref = this.xref;
  9915. var fileObj = xref.fetchIfRef(this.contentRef);
  9916. if (fileObj && isStream(fileObj)) {
  9917. content = fileObj.getBytes();
  9918. } else {
  9919. warn('Embedded file specification points to non-existing/invalid ' +
  9920. 'content');
  9921. }
  9922. } else {
  9923. warn('Embedded file specification does not have a content');
  9924. }
  9925. return content;
  9926. },
  9927. get serializable() {
  9928. return {
  9929. filename: this.filename,
  9930. content: this.content
  9931. };
  9932. }
  9933. };
  9934. return FileSpec;
  9935. })();
  9936. /**
  9937. * A helper for loading missing data in object graphs. It traverses the graph
  9938. * depth first and queues up any objects that have missing data. Once it has
  9939. * has traversed as many objects that are available it attempts to bundle the
  9940. * missing data requests and then resume from the nodes that weren't ready.
  9941. *
  9942. * NOTE: It provides protection from circular references by keeping track of
  9943. * of loaded references. However, you must be careful not to load any graphs
  9944. * that have references to the catalog or other pages since that will cause the
  9945. * entire PDF document object graph to be traversed.
  9946. */
  9947. var ObjectLoader = (function() {
  9948. function mayHaveChildren(value) {
  9949. return isRef(value) || isDict(value) || isArray(value) || isStream(value);
  9950. }
  9951. function addChildren(node, nodesToVisit) {
  9952. var value;
  9953. if (isDict(node) || isStream(node)) {
  9954. var map;
  9955. if (isDict(node)) {
  9956. map = node.map;
  9957. } else {
  9958. map = node.dict.map;
  9959. }
  9960. for (var key in map) {
  9961. value = map[key];
  9962. if (mayHaveChildren(value)) {
  9963. nodesToVisit.push(value);
  9964. }
  9965. }
  9966. } else if (isArray(node)) {
  9967. for (var i = 0, ii = node.length; i < ii; i++) {
  9968. value = node[i];
  9969. if (mayHaveChildren(value)) {
  9970. nodesToVisit.push(value);
  9971. }
  9972. }
  9973. }
  9974. }
  9975. function ObjectLoader(obj, keys, xref) {
  9976. this.obj = obj;
  9977. this.keys = keys;
  9978. this.xref = xref;
  9979. this.refSet = null;
  9980. }
  9981. ObjectLoader.prototype = {
  9982. load: function ObjectLoader_load() {
  9983. var keys = this.keys;
  9984. this.capability = createPromiseCapability();
  9985. // Don't walk the graph if all the data is already loaded.
  9986. if (!(this.xref.stream instanceof ChunkedStream) ||
  9987. this.xref.stream.getMissingChunks().length === 0) {
  9988. this.capability.resolve();
  9989. return this.capability.promise;
  9990. }
  9991. this.refSet = new RefSet();
  9992. // Setup the initial nodes to visit.
  9993. var nodesToVisit = [];
  9994. for (var i = 0; i < keys.length; i++) {
  9995. nodesToVisit.push(this.obj[keys[i]]);
  9996. }
  9997. this.walk(nodesToVisit);
  9998. return this.capability.promise;
  9999. },
  10000. walk: function ObjectLoader_walk(nodesToVisit) {
  10001. var nodesToRevisit = [];
  10002. var pendingRequests = [];
  10003. // DFS walk of the object graph.
  10004. while (nodesToVisit.length) {
  10005. var currentNode = nodesToVisit.pop();
  10006. // Only references or chunked streams can cause missing data exceptions.
  10007. if (isRef(currentNode)) {
  10008. // Skip nodes that have already been visited.
  10009. if (this.refSet.has(currentNode)) {
  10010. continue;
  10011. }
  10012. try {
  10013. var ref = currentNode;
  10014. this.refSet.put(ref);
  10015. currentNode = this.xref.fetch(currentNode);
  10016. } catch (e) {
  10017. if (!(e instanceof MissingDataException)) {
  10018. throw e;
  10019. }
  10020. nodesToRevisit.push(currentNode);
  10021. pendingRequests.push({ begin: e.begin, end: e.end });
  10022. }
  10023. }
  10024. if (currentNode && currentNode.getBaseStreams) {
  10025. var baseStreams = currentNode.getBaseStreams();
  10026. var foundMissingData = false;
  10027. for (var i = 0; i < baseStreams.length; i++) {
  10028. var stream = baseStreams[i];
  10029. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  10030. foundMissingData = true;
  10031. pendingRequests.push({
  10032. begin: stream.start,
  10033. end: stream.end
  10034. });
  10035. }
  10036. }
  10037. if (foundMissingData) {
  10038. nodesToRevisit.push(currentNode);
  10039. }
  10040. }
  10041. addChildren(currentNode, nodesToVisit);
  10042. }
  10043. if (pendingRequests.length) {
  10044. this.xref.stream.manager.requestRanges(pendingRequests,
  10045. function pendingRequestCallback() {
  10046. nodesToVisit = nodesToRevisit;
  10047. for (var i = 0; i < nodesToRevisit.length; i++) {
  10048. var node = nodesToRevisit[i];
  10049. // Remove any reference nodes from the currrent refset so they
  10050. // aren't skipped when we revist them.
  10051. if (isRef(node)) {
  10052. this.refSet.remove(node);
  10053. }
  10054. }
  10055. this.walk(nodesToVisit);
  10056. }.bind(this));
  10057. return;
  10058. }
  10059. // Everything is loaded.
  10060. this.refSet = null;
  10061. this.capability.resolve();
  10062. }
  10063. };
  10064. return ObjectLoader;
  10065. })();
  10066. var ISOAdobeCharset = [
  10067. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar',
  10068. 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright',
  10069. 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero',
  10070. 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
  10071. 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question',
  10072. 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  10073. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  10074. 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
  10075. 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  10076. 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  10077. 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
  10078. 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  10079. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  10080. 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
  10081. 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase',
  10082. 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
  10083. 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde',
  10084. 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla',
  10085. 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine',
  10086. 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash',
  10087. 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu',
  10088. 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter',
  10089. 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior',
  10090. 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright',
  10091. 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde',
  10092. 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute',
  10093. 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex',
  10094. 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex',
  10095. 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute',
  10096. 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla',
  10097. 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex',
  10098. 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis',
  10099. 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis',
  10100. 'ugrave', 'yacute', 'ydieresis', 'zcaron'
  10101. ];
  10102. var ExpertCharset = [
  10103. '.notdef', 'space', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle',
  10104. 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
  10105. 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
  10106. 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
  10107. 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
  10108. 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle',
  10109. 'colon', 'semicolon', 'commasuperior', 'threequartersemdash',
  10110. 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior',
  10111. 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  10112. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  10113. 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
  10114. 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
  10115. 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
  10116. 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
  10117. 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
  10118. 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
  10119. 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle',
  10120. 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall',
  10121. 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall',
  10122. 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall',
  10123. 'Cedillasmall', 'onequarter', 'onehalf', 'threequarters',
  10124. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
  10125. 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
  10126. 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  10127. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  10128. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
  10129. 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
  10130. 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
  10131. 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall',
  10132. 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall',
  10133. 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
  10134. 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  10135. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
  10136. 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
  10137. 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  10138. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
  10139. 'Ydieresissmall'
  10140. ];
  10141. var ExpertSubsetCharset = [
  10142. '.notdef', 'space', 'dollaroldstyle', 'dollarsuperior',
  10143. 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  10144. 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction',
  10145. 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle',
  10146. 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle',
  10147. 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior',
  10148. 'threequartersemdash', 'periodsuperior', 'asuperior', 'bsuperior',
  10149. 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  10150. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  10151. 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
  10152. 'parenrightinferior', 'hyphensuperior', 'colonmonetary', 'onefitted',
  10153. 'rupiah', 'centoldstyle', 'figuredash', 'hypheninferior', 'onequarter',
  10154. 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
  10155. 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
  10156. 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  10157. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  10158. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
  10159. 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
  10160. 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
  10161. 'periodinferior', 'commainferior'
  10162. ];
  10163. var DEFAULT_ICON_SIZE = 22; // px
  10164. /**
  10165. * @constructor
  10166. */
  10167. function AnnotationFactory() {}
  10168. AnnotationFactory.prototype = {
  10169. /**
  10170. * @param {XRef} xref
  10171. * @param {Object} ref
  10172. * @returns {Annotation}
  10173. */
  10174. create: function AnnotationFactory_create(xref, ref) {
  10175. var dict = xref.fetchIfRef(ref);
  10176. if (!isDict(dict)) {
  10177. return;
  10178. }
  10179. // Determine the annotation's subtype.
  10180. var subtype = dict.get('Subtype');
  10181. subtype = isName(subtype) ? subtype.name : '';
  10182. // Return the right annotation object based on the subtype and field type.
  10183. var parameters = {
  10184. dict: dict,
  10185. ref: ref
  10186. };
  10187. switch (subtype) {
  10188. case 'Link':
  10189. return new LinkAnnotation(parameters);
  10190. case 'Text':
  10191. return new TextAnnotation(parameters);
  10192. case 'Widget':
  10193. var fieldType = Util.getInheritableProperty(dict, 'FT');
  10194. if (isName(fieldType) && fieldType.name === 'Tx') {
  10195. return new TextWidgetAnnotation(parameters);
  10196. }
  10197. return new WidgetAnnotation(parameters);
  10198. default:
  10199. warn('Unimplemented annotation type "' + subtype + '", ' +
  10200. 'falling back to base annotation');
  10201. return new Annotation(parameters);
  10202. }
  10203. }
  10204. };
  10205. var Annotation = (function AnnotationClosure() {
  10206. // 12.5.5: Algorithm: Appearance streams
  10207. function getTransformMatrix(rect, bbox, matrix) {
  10208. var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);
  10209. var minX = bounds[0];
  10210. var minY = bounds[1];
  10211. var maxX = bounds[2];
  10212. var maxY = bounds[3];
  10213. if (minX === maxX || minY === maxY) {
  10214. // From real-life file, bbox was [0, 0, 0, 0]. In this case,
  10215. // just apply the transform for rect
  10216. return [1, 0, 0, 1, rect[0], rect[1]];
  10217. }
  10218. var xRatio = (rect[2] - rect[0]) / (maxX - minX);
  10219. var yRatio = (rect[3] - rect[1]) / (maxY - minY);
  10220. return [
  10221. xRatio,
  10222. 0,
  10223. 0,
  10224. yRatio,
  10225. rect[0] - minX * xRatio,
  10226. rect[1] - minY * yRatio
  10227. ];
  10228. }
  10229. function getDefaultAppearance(dict) {
  10230. var appearanceState = dict.get('AP');
  10231. if (!isDict(appearanceState)) {
  10232. return;
  10233. }
  10234. var appearance;
  10235. var appearances = appearanceState.get('N');
  10236. if (isDict(appearances)) {
  10237. var as = dict.get('AS');
  10238. if (as && appearances.has(as.name)) {
  10239. appearance = appearances.get(as.name);
  10240. }
  10241. } else {
  10242. appearance = appearances;
  10243. }
  10244. return appearance;
  10245. }
  10246. function Annotation(params) {
  10247. var dict = params.dict;
  10248. var data = this.data = {};
  10249. data.subtype = dict.get('Subtype').name;
  10250. data.annotationFlags = dict.get('F');
  10251. this.setRectangle(dict.get('Rect'));
  10252. data.rect = this.rectangle;
  10253. this.setColor(dict.get('C'));
  10254. data.color = this.color;
  10255. this.borderStyle = data.borderStyle = new AnnotationBorderStyle();
  10256. this.setBorderStyle(dict);
  10257. this.appearance = getDefaultAppearance(dict);
  10258. data.hasAppearance = !!this.appearance;
  10259. data.id = params.ref.num;
  10260. }
  10261. Annotation.prototype = {
  10262. /**
  10263. * Set the rectangle.
  10264. *
  10265. * @public
  10266. * @memberof Annotation
  10267. * @param {Array} rectangle - The rectangle array with exactly four entries
  10268. */
  10269. setRectangle: function Annotation_setRectangle(rectangle) {
  10270. if (isArray(rectangle) && rectangle.length === 4) {
  10271. this.rectangle = Util.normalizeRect(rectangle);
  10272. } else {
  10273. this.rectangle = [0, 0, 0, 0];
  10274. }
  10275. },
  10276. /**
  10277. * Set the color and take care of color space conversion.
  10278. *
  10279. * @public
  10280. * @memberof Annotation
  10281. * @param {Array} color - The color array containing either 0
  10282. * (transparent), 1 (grayscale), 3 (RGB) or
  10283. * 4 (CMYK) elements
  10284. */
  10285. setColor: function Annotation_setColor(color) {
  10286. var rgbColor = new Uint8Array(3); // Black in RGB color space (default)
  10287. if (!isArray(color)) {
  10288. this.color = rgbColor;
  10289. return;
  10290. }
  10291. switch (color.length) {
  10292. case 0: // Transparent, which we indicate with a null value
  10293. this.color = null;
  10294. break;
  10295. case 1: // Convert grayscale to RGB
  10296. ColorSpace.singletons.gray.getRgbItem(color, 0, rgbColor, 0);
  10297. this.color = rgbColor;
  10298. break;
  10299. case 3: // Convert RGB percentages to RGB
  10300. ColorSpace.singletons.rgb.getRgbItem(color, 0, rgbColor, 0);
  10301. this.color = rgbColor;
  10302. break;
  10303. case 4: // Convert CMYK to RGB
  10304. ColorSpace.singletons.cmyk.getRgbItem(color, 0, rgbColor, 0);
  10305. this.color = rgbColor;
  10306. break;
  10307. default:
  10308. this.color = rgbColor;
  10309. break;
  10310. }
  10311. },
  10312. /**
  10313. * Set the border style (as AnnotationBorderStyle object).
  10314. *
  10315. * @public
  10316. * @memberof Annotation
  10317. * @param {Dict} borderStyle - The border style dictionary
  10318. */
  10319. setBorderStyle: function Annotation_setBorderStyle(borderStyle) {
  10320. if (!isDict(borderStyle)) {
  10321. return;
  10322. }
  10323. if (borderStyle.has('BS')) {
  10324. var dict = borderStyle.get('BS');
  10325. var dictType;
  10326. if (!dict.has('Type') || (isName(dictType = dict.get('Type')) &&
  10327. dictType.name === 'Border')) {
  10328. this.borderStyle.setWidth(dict.get('W'));
  10329. this.borderStyle.setStyle(dict.get('S'));
  10330. this.borderStyle.setDashArray(dict.get('D'));
  10331. }
  10332. } else if (borderStyle.has('Border')) {
  10333. var array = borderStyle.get('Border');
  10334. if (isArray(array) && array.length >= 3) {
  10335. this.borderStyle.setHorizontalCornerRadius(array[0]);
  10336. this.borderStyle.setVerticalCornerRadius(array[1]);
  10337. this.borderStyle.setWidth(array[2]);
  10338. if (array.length === 4) { // Dash array available
  10339. this.borderStyle.setDashArray(array[3]);
  10340. }
  10341. }
  10342. } else {
  10343. // There are no border entries in the dictionary. According to the
  10344. // specification, we should draw a solid border of width 1 in that
  10345. // case, but Adobe Reader did not implement that part of the
  10346. // specification and instead draws no border at all, so we do the same.
  10347. // See also https://github.com/mozilla/pdf.js/issues/6179.
  10348. this.borderStyle.setWidth(0);
  10349. }
  10350. },
  10351. isInvisible: function Annotation_isInvisible() {
  10352. var data = this.data;
  10353. return !!(data &&
  10354. data.annotationFlags && // Default: not invisible
  10355. data.annotationFlags & 0x1); // Invisible
  10356. },
  10357. isViewable: function Annotation_isViewable() {
  10358. var data = this.data;
  10359. return !!(!this.isInvisible() &&
  10360. data &&
  10361. (!data.annotationFlags ||
  10362. !(data.annotationFlags & 0x22)) && // Hidden or NoView
  10363. data.rect); // rectangle is necessary
  10364. },
  10365. isPrintable: function Annotation_isPrintable() {
  10366. var data = this.data;
  10367. return !!(!this.isInvisible() &&
  10368. data &&
  10369. data.annotationFlags && // Default: not printable
  10370. data.annotationFlags & 0x4 && // Print
  10371. !(data.annotationFlags & 0x2) && // Hidden
  10372. data.rect); // rectangle is necessary
  10373. },
  10374. loadResources: function Annotation_loadResources(keys) {
  10375. return new Promise(function (resolve, reject) {
  10376. this.appearance.dict.getAsync('Resources').then(function (resources) {
  10377. if (!resources) {
  10378. resolve();
  10379. return;
  10380. }
  10381. var objectLoader = new ObjectLoader(resources.map,
  10382. keys,
  10383. resources.xref);
  10384. objectLoader.load().then(function() {
  10385. resolve(resources);
  10386. }, reject);
  10387. }, reject);
  10388. }.bind(this));
  10389. },
  10390. getOperatorList: function Annotation_getOperatorList(evaluator) {
  10391. if (!this.appearance) {
  10392. return Promise.resolve(new OperatorList());
  10393. }
  10394. var data = this.data;
  10395. var appearanceDict = this.appearance.dict;
  10396. var resourcesPromise = this.loadResources([
  10397. 'ExtGState',
  10398. 'ColorSpace',
  10399. 'Pattern',
  10400. 'Shading',
  10401. 'XObject',
  10402. 'Font'
  10403. // ProcSet
  10404. // Properties
  10405. ]);
  10406. var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];
  10407. var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];
  10408. var transform = getTransformMatrix(data.rect, bbox, matrix);
  10409. var self = this;
  10410. return resourcesPromise.then(function(resources) {
  10411. var opList = new OperatorList();
  10412. opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
  10413. return evaluator.getOperatorList(self.appearance, resources, opList).
  10414. then(function () {
  10415. opList.addOp(OPS.endAnnotation, []);
  10416. self.appearance.reset();
  10417. return opList;
  10418. });
  10419. });
  10420. }
  10421. };
  10422. Annotation.appendToOperatorList = function Annotation_appendToOperatorList(
  10423. annotations, opList, pdfManager, partialEvaluator, intent) {
  10424. function reject(e) {
  10425. annotationsReadyCapability.reject(e);
  10426. }
  10427. var annotationsReadyCapability = createPromiseCapability();
  10428. var annotationPromises = [];
  10429. for (var i = 0, n = annotations.length; i < n; ++i) {
  10430. if (intent === 'display' && annotations[i].isViewable() ||
  10431. intent === 'print' && annotations[i].isPrintable()) {
  10432. annotationPromises.push(
  10433. annotations[i].getOperatorList(partialEvaluator));
  10434. }
  10435. }
  10436. Promise.all(annotationPromises).then(function(datas) {
  10437. opList.addOp(OPS.beginAnnotations, []);
  10438. for (var i = 0, n = datas.length; i < n; ++i) {
  10439. var annotOpList = datas[i];
  10440. opList.addOpList(annotOpList);
  10441. }
  10442. opList.addOp(OPS.endAnnotations, []);
  10443. annotationsReadyCapability.resolve();
  10444. }, reject);
  10445. return annotationsReadyCapability.promise;
  10446. };
  10447. return Annotation;
  10448. })();
  10449. /**
  10450. * Contains all data regarding an annotation's border style.
  10451. *
  10452. * @class
  10453. */
  10454. var AnnotationBorderStyle = (function AnnotationBorderStyleClosure() {
  10455. /**
  10456. * @constructor
  10457. * @private
  10458. */
  10459. function AnnotationBorderStyle() {
  10460. this.width = 1;
  10461. this.style = AnnotationBorderStyleType.SOLID;
  10462. this.dashArray = [3];
  10463. this.horizontalCornerRadius = 0;
  10464. this.verticalCornerRadius = 0;
  10465. }
  10466. AnnotationBorderStyle.prototype = {
  10467. /**
  10468. * Set the width.
  10469. *
  10470. * @public
  10471. * @memberof AnnotationBorderStyle
  10472. * @param {integer} width - The width
  10473. */
  10474. setWidth: function AnnotationBorderStyle_setWidth(width) {
  10475. if (width === (width | 0)) {
  10476. this.width = width;
  10477. }
  10478. },
  10479. /**
  10480. * Set the style.
  10481. *
  10482. * @public
  10483. * @memberof AnnotationBorderStyle
  10484. * @param {Object} style - The style object
  10485. * @see {@link shared/util.js}
  10486. */
  10487. setStyle: function AnnotationBorderStyle_setStyle(style) {
  10488. if (!style) {
  10489. return;
  10490. }
  10491. switch (style.name) {
  10492. case 'S':
  10493. this.style = AnnotationBorderStyleType.SOLID;
  10494. break;
  10495. case 'D':
  10496. this.style = AnnotationBorderStyleType.DASHED;
  10497. break;
  10498. case 'B':
  10499. this.style = AnnotationBorderStyleType.BEVELED;
  10500. break;
  10501. case 'I':
  10502. this.style = AnnotationBorderStyleType.INSET;
  10503. break;
  10504. case 'U':
  10505. this.style = AnnotationBorderStyleType.UNDERLINE;
  10506. break;
  10507. default:
  10508. break;
  10509. }
  10510. },
  10511. /**
  10512. * Set the dash array.
  10513. *
  10514. * @public
  10515. * @memberof AnnotationBorderStyle
  10516. * @param {Array} dashArray - The dash array with at least one element
  10517. */
  10518. setDashArray: function AnnotationBorderStyle_setDashArray(dashArray) {
  10519. // We validate the dash array, but we do not use it because CSS does not
  10520. // allow us to change spacing of dashes. For more information, visit
  10521. // http://www.w3.org/TR/css3-background/#the-border-style.
  10522. if (isArray(dashArray) && dashArray.length > 0) {
  10523. // According to the PDF specification: the elements in a dashArray
  10524. // shall be numbers that are nonnegative and not all equal to zero.
  10525. var isValid = true;
  10526. var allZeros = true;
  10527. for (var i = 0, len = dashArray.length; i < len; i++) {
  10528. var element = dashArray[i];
  10529. var validNumber = (+element >= 0);
  10530. if (!validNumber) {
  10531. isValid = false;
  10532. break;
  10533. } else if (element > 0) {
  10534. allZeros = false;
  10535. }
  10536. }
  10537. if (isValid && !allZeros) {
  10538. this.dashArray = dashArray;
  10539. } else {
  10540. this.width = 0; // Adobe behavior when the array is invalid.
  10541. }
  10542. } else if (dashArray) {
  10543. this.width = 0; // Adobe behavior when the array is invalid.
  10544. }
  10545. },
  10546. /**
  10547. * Set the horizontal corner radius (from a Border dictionary).
  10548. *
  10549. * @public
  10550. * @memberof AnnotationBorderStyle
  10551. * @param {integer} radius - The horizontal corner radius
  10552. */
  10553. setHorizontalCornerRadius:
  10554. function AnnotationBorderStyle_setHorizontalCornerRadius(radius) {
  10555. if (radius === (radius | 0)) {
  10556. this.horizontalCornerRadius = radius;
  10557. }
  10558. },
  10559. /**
  10560. * Set the vertical corner radius (from a Border dictionary).
  10561. *
  10562. * @public
  10563. * @memberof AnnotationBorderStyle
  10564. * @param {integer} radius - The vertical corner radius
  10565. */
  10566. setVerticalCornerRadius:
  10567. function AnnotationBorderStyle_setVerticalCornerRadius(radius) {
  10568. if (radius === (radius | 0)) {
  10569. this.verticalCornerRadius = radius;
  10570. }
  10571. }
  10572. };
  10573. return AnnotationBorderStyle;
  10574. })();
  10575. var WidgetAnnotation = (function WidgetAnnotationClosure() {
  10576. function WidgetAnnotation(params) {
  10577. Annotation.call(this, params);
  10578. var dict = params.dict;
  10579. var data = this.data;
  10580. data.fieldValue = stringToPDFString(
  10581. Util.getInheritableProperty(dict, 'V') || '');
  10582. data.alternativeText = stringToPDFString(dict.get('TU') || '');
  10583. data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';
  10584. var fieldType = Util.getInheritableProperty(dict, 'FT');
  10585. data.fieldType = isName(fieldType) ? fieldType.name : '';
  10586. data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;
  10587. this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;
  10588. // Building the full field name by collecting the field and
  10589. // its ancestors 'T' data and joining them using '.'.
  10590. var fieldName = [];
  10591. var namedItem = dict;
  10592. var ref = params.ref;
  10593. while (namedItem) {
  10594. var parent = namedItem.get('Parent');
  10595. var parentRef = namedItem.getRaw('Parent');
  10596. var name = namedItem.get('T');
  10597. if (name) {
  10598. fieldName.unshift(stringToPDFString(name));
  10599. } else if (parent && ref) {
  10600. // The field name is absent, that means more than one field
  10601. // with the same name may exist. Replacing the empty name
  10602. // with the '`' plus index in the parent's 'Kids' array.
  10603. // This is not in the PDF spec but necessary to id the
  10604. // the input controls.
  10605. var kids = parent.get('Kids');
  10606. var j, jj;
  10607. for (j = 0, jj = kids.length; j < jj; j++) {
  10608. var kidRef = kids[j];
  10609. if (kidRef.num === ref.num && kidRef.gen === ref.gen) {
  10610. break;
  10611. }
  10612. }
  10613. fieldName.unshift('`' + j);
  10614. }
  10615. namedItem = parent;
  10616. ref = parentRef;
  10617. }
  10618. data.fullName = fieldName.join('.');
  10619. }
  10620. var parent = Annotation.prototype;
  10621. Util.inherit(WidgetAnnotation, Annotation, {
  10622. isViewable: function WidgetAnnotation_isViewable() {
  10623. if (this.data.fieldType === 'Sig') {
  10624. warn('unimplemented annotation type: Widget signature');
  10625. return false;
  10626. }
  10627. return parent.isViewable.call(this);
  10628. }
  10629. });
  10630. return WidgetAnnotation;
  10631. })();
  10632. var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
  10633. function TextWidgetAnnotation(params) {
  10634. WidgetAnnotation.call(this, params);
  10635. this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');
  10636. this.data.annotationType = AnnotationType.WIDGET;
  10637. this.data.hasHtml = !this.data.hasAppearance && !!this.data.fieldValue;
  10638. }
  10639. Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
  10640. getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {
  10641. if (this.appearance) {
  10642. return Annotation.prototype.getOperatorList.call(this, evaluator);
  10643. }
  10644. var opList = new OperatorList();
  10645. var data = this.data;
  10646. // Even if there is an appearance stream, ignore it. This is the
  10647. // behaviour used by Adobe Reader.
  10648. if (!data.defaultAppearance) {
  10649. return Promise.resolve(opList);
  10650. }
  10651. var stream = new Stream(stringToBytes(data.defaultAppearance));
  10652. return evaluator.getOperatorList(stream, this.fieldResources, opList).
  10653. then(function () {
  10654. return opList;
  10655. });
  10656. }
  10657. });
  10658. return TextWidgetAnnotation;
  10659. })();
  10660. var TextAnnotation = (function TextAnnotationClosure() {
  10661. function TextAnnotation(params) {
  10662. Annotation.call(this, params);
  10663. var dict = params.dict;
  10664. var data = this.data;
  10665. var content = dict.get('Contents');
  10666. var title = dict.get('T');
  10667. data.annotationType = AnnotationType.TEXT;
  10668. data.content = stringToPDFString(content || '');
  10669. data.title = stringToPDFString(title || '');
  10670. data.hasHtml = true;
  10671. if (data.hasAppearance) {
  10672. data.name = 'NoIcon';
  10673. } else {
  10674. data.rect[1] = data.rect[3] - DEFAULT_ICON_SIZE;
  10675. data.rect[2] = data.rect[0] + DEFAULT_ICON_SIZE;
  10676. data.name = dict.has('Name') ? dict.get('Name').name : 'Note';
  10677. }
  10678. if (dict.has('C')) {
  10679. data.hasBgColor = true;
  10680. }
  10681. }
  10682. Util.inherit(TextAnnotation, Annotation, { });
  10683. return TextAnnotation;
  10684. })();
  10685. var LinkAnnotation = (function LinkAnnotationClosure() {
  10686. function LinkAnnotation(params) {
  10687. Annotation.call(this, params);
  10688. var dict = params.dict;
  10689. var data = this.data;
  10690. data.annotationType = AnnotationType.LINK;
  10691. data.hasHtml = true;
  10692. var action = dict.get('A');
  10693. if (action && isDict(action)) {
  10694. var linkType = action.get('S').name;
  10695. if (linkType === 'URI') {
  10696. var url = action.get('URI');
  10697. if (isName(url)) {
  10698. // Some bad PDFs do not put parentheses around relative URLs.
  10699. url = '/' + url.name;
  10700. } else if (url) {
  10701. url = addDefaultProtocolToUrl(url);
  10702. }
  10703. // TODO: pdf spec mentions urls can be relative to a Base
  10704. // entry in the dictionary.
  10705. if (!isValidUrl(url, false)) {
  10706. url = '';
  10707. }
  10708. // According to ISO 32000-1:2008, section 12.6.4.7,
  10709. // URI should to be encoded in 7-bit ASCII.
  10710. // Some bad PDFs may have URIs in UTF-8 encoding, see Bugzilla 1122280.
  10711. try {
  10712. data.url = stringToUTF8String(url);
  10713. } catch (e) {
  10714. // Fall back to a simple copy.
  10715. data.url = url;
  10716. }
  10717. } else if (linkType === 'GoTo') {
  10718. data.dest = action.get('D');
  10719. } else if (linkType === 'GoToR') {
  10720. var urlDict = action.get('F');
  10721. if (isDict(urlDict)) {
  10722. // We assume that the 'url' is a Filspec dictionary
  10723. // and fetch the url without checking any further
  10724. url = urlDict.get('F') || '';
  10725. }
  10726. // TODO: pdf reference says that GoToR
  10727. // can also have 'NewWindow' attribute
  10728. if (!isValidUrl(url, false)) {
  10729. url = '';
  10730. }
  10731. data.url = url;
  10732. data.dest = action.get('D');
  10733. } else if (linkType === 'Named') {
  10734. data.action = action.get('N').name;
  10735. } else {
  10736. warn('unrecognized link type: ' + linkType);
  10737. }
  10738. } else if (dict.has('Dest')) {
  10739. // simple destination link
  10740. var dest = dict.get('Dest');
  10741. data.dest = isName(dest) ? dest.name : dest;
  10742. }
  10743. }
  10744. // Lets URLs beginning with 'www.' default to using the 'http://' protocol.
  10745. function addDefaultProtocolToUrl(url) {
  10746. if (url && url.indexOf('www.') === 0) {
  10747. return ('http://' + url);
  10748. }
  10749. return url;
  10750. }
  10751. Util.inherit(LinkAnnotation, Annotation, { });
  10752. return LinkAnnotation;
  10753. })();
  10754. var PDFFunction = (function PDFFunctionClosure() {
  10755. var CONSTRUCT_SAMPLED = 0;
  10756. var CONSTRUCT_INTERPOLATED = 2;
  10757. var CONSTRUCT_STICHED = 3;
  10758. var CONSTRUCT_POSTSCRIPT = 4;
  10759. return {
  10760. getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,
  10761. str) {
  10762. var i, ii;
  10763. var length = 1;
  10764. for (i = 0, ii = size.length; i < ii; i++) {
  10765. length *= size[i];
  10766. }
  10767. length *= outputSize;
  10768. var array = new Array(length);
  10769. var codeSize = 0;
  10770. var codeBuf = 0;
  10771. // 32 is a valid bps so shifting won't work
  10772. var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);
  10773. var strBytes = str.getBytes((length * bps + 7) / 8);
  10774. var strIdx = 0;
  10775. for (i = 0; i < length; i++) {
  10776. while (codeSize < bps) {
  10777. codeBuf <<= 8;
  10778. codeBuf |= strBytes[strIdx++];
  10779. codeSize += 8;
  10780. }
  10781. codeSize -= bps;
  10782. array[i] = (codeBuf >> codeSize) * sampleMul;
  10783. codeBuf &= (1 << codeSize) - 1;
  10784. }
  10785. return array;
  10786. },
  10787. getIR: function PDFFunction_getIR(xref, fn) {
  10788. var dict = fn.dict;
  10789. if (!dict) {
  10790. dict = fn;
  10791. }
  10792. var types = [this.constructSampled,
  10793. null,
  10794. this.constructInterpolated,
  10795. this.constructStiched,
  10796. this.constructPostScript];
  10797. var typeNum = dict.get('FunctionType');
  10798. var typeFn = types[typeNum];
  10799. if (!typeFn) {
  10800. error('Unknown type of function');
  10801. }
  10802. return typeFn.call(this, fn, dict, xref);
  10803. },
  10804. fromIR: function PDFFunction_fromIR(IR) {
  10805. var type = IR[0];
  10806. switch (type) {
  10807. case CONSTRUCT_SAMPLED:
  10808. return this.constructSampledFromIR(IR);
  10809. case CONSTRUCT_INTERPOLATED:
  10810. return this.constructInterpolatedFromIR(IR);
  10811. case CONSTRUCT_STICHED:
  10812. return this.constructStichedFromIR(IR);
  10813. //case CONSTRUCT_POSTSCRIPT:
  10814. default:
  10815. return this.constructPostScriptFromIR(IR);
  10816. }
  10817. },
  10818. parse: function PDFFunction_parse(xref, fn) {
  10819. var IR = this.getIR(xref, fn);
  10820. return this.fromIR(IR);
  10821. },
  10822. parseArray: function PDFFunction_parseArray(xref, fnObj) {
  10823. if (!isArray(fnObj)) {
  10824. // not an array -- parsing as regular function
  10825. return this.parse(xref, fnObj);
  10826. }
  10827. var fnArray = [];
  10828. for (var j = 0, jj = fnObj.length; j < jj; j++) {
  10829. var obj = xref.fetchIfRef(fnObj[j]);
  10830. fnArray.push(PDFFunction.parse(xref, obj));
  10831. }
  10832. return function (src, srcOffset, dest, destOffset) {
  10833. for (var i = 0, ii = fnArray.length; i < ii; i++) {
  10834. fnArray[i](src, srcOffset, dest, destOffset + i);
  10835. }
  10836. };
  10837. },
  10838. constructSampled: function PDFFunction_constructSampled(str, dict) {
  10839. function toMultiArray(arr) {
  10840. var inputLength = arr.length;
  10841. var out = [];
  10842. var index = 0;
  10843. for (var i = 0; i < inputLength; i += 2) {
  10844. out[index] = [arr[i], arr[i + 1]];
  10845. ++index;
  10846. }
  10847. return out;
  10848. }
  10849. var domain = dict.get('Domain');
  10850. var range = dict.get('Range');
  10851. if (!domain || !range) {
  10852. error('No domain or range');
  10853. }
  10854. var inputSize = domain.length / 2;
  10855. var outputSize = range.length / 2;
  10856. domain = toMultiArray(domain);
  10857. range = toMultiArray(range);
  10858. var size = dict.get('Size');
  10859. var bps = dict.get('BitsPerSample');
  10860. var order = dict.get('Order') || 1;
  10861. if (order !== 1) {
  10862. // No description how cubic spline interpolation works in PDF32000:2008
  10863. // As in poppler, ignoring order, linear interpolation may work as good
  10864. info('No support for cubic spline interpolation: ' + order);
  10865. }
  10866. var encode = dict.get('Encode');
  10867. if (!encode) {
  10868. encode = [];
  10869. for (var i = 0; i < inputSize; ++i) {
  10870. encode.push(0);
  10871. encode.push(size[i] - 1);
  10872. }
  10873. }
  10874. encode = toMultiArray(encode);
  10875. var decode = dict.get('Decode');
  10876. if (!decode) {
  10877. decode = range;
  10878. } else {
  10879. decode = toMultiArray(decode);
  10880. }
  10881. var samples = this.getSampleArray(size, outputSize, bps, str);
  10882. return [
  10883. CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,
  10884. outputSize, Math.pow(2, bps) - 1, range
  10885. ];
  10886. },
  10887. constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {
  10888. // See chapter 3, page 109 of the PDF reference
  10889. function interpolate(x, xmin, xmax, ymin, ymax) {
  10890. return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));
  10891. }
  10892. return function constructSampledFromIRResult(src, srcOffset,
  10893. dest, destOffset) {
  10894. // See chapter 3, page 110 of the PDF reference.
  10895. var m = IR[1];
  10896. var domain = IR[2];
  10897. var encode = IR[3];
  10898. var decode = IR[4];
  10899. var samples = IR[5];
  10900. var size = IR[6];
  10901. var n = IR[7];
  10902. //var mask = IR[8];
  10903. var range = IR[9];
  10904. // Building the cube vertices: its part and sample index
  10905. // http://rjwagner49.com/Mathematics/Interpolation.pdf
  10906. var cubeVertices = 1 << m;
  10907. var cubeN = new Float64Array(cubeVertices);
  10908. var cubeVertex = new Uint32Array(cubeVertices);
  10909. var i, j;
  10910. for (j = 0; j < cubeVertices; j++) {
  10911. cubeN[j] = 1;
  10912. }
  10913. var k = n, pos = 1;
  10914. // Map x_i to y_j for 0 <= i < m using the sampled function.
  10915. for (i = 0; i < m; ++i) {
  10916. // x_i' = min(max(x_i, Domain_2i), Domain_2i+1)
  10917. var domain_2i = domain[i][0];
  10918. var domain_2i_1 = domain[i][1];
  10919. var xi = Math.min(Math.max(src[srcOffset +i], domain_2i),
  10920. domain_2i_1);
  10921. // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,
  10922. // Encode_2i, Encode_2i+1)
  10923. var e = interpolate(xi, domain_2i, domain_2i_1,
  10924. encode[i][0], encode[i][1]);
  10925. // e_i' = min(max(e_i, 0), Size_i - 1)
  10926. var size_i = size[i];
  10927. e = Math.min(Math.max(e, 0), size_i - 1);
  10928. // Adjusting the cube: N and vertex sample index
  10929. var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;
  10930. var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);
  10931. var n1 = e - e0; // (e - e0) / (e1 - e0);
  10932. var offset0 = e0 * k;
  10933. var offset1 = offset0 + k; // e1 * k
  10934. for (j = 0; j < cubeVertices; j++) {
  10935. if (j & pos) {
  10936. cubeN[j] *= n1;
  10937. cubeVertex[j] += offset1;
  10938. } else {
  10939. cubeN[j] *= n0;
  10940. cubeVertex[j] += offset0;
  10941. }
  10942. }
  10943. k *= size_i;
  10944. pos <<= 1;
  10945. }
  10946. for (j = 0; j < n; ++j) {
  10947. // Sum all cube vertices' samples portions
  10948. var rj = 0;
  10949. for (i = 0; i < cubeVertices; i++) {
  10950. rj += samples[cubeVertex[i] + j] * cubeN[i];
  10951. }
  10952. // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,
  10953. // Decode_2j, Decode_2j+1)
  10954. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  10955. // y_j = min(max(r_j, range_2j), range_2j+1)
  10956. dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]),
  10957. range[j][1]);
  10958. }
  10959. };
  10960. },
  10961. constructInterpolated: function PDFFunction_constructInterpolated(str,
  10962. dict) {
  10963. var c0 = dict.get('C0') || [0];
  10964. var c1 = dict.get('C1') || [1];
  10965. var n = dict.get('N');
  10966. if (!isArray(c0) || !isArray(c1)) {
  10967. error('Illegal dictionary for interpolated function');
  10968. }
  10969. var length = c0.length;
  10970. var diff = [];
  10971. for (var i = 0; i < length; ++i) {
  10972. diff.push(c1[i] - c0[i]);
  10973. }
  10974. return [CONSTRUCT_INTERPOLATED, c0, diff, n];
  10975. },
  10976. constructInterpolatedFromIR:
  10977. function PDFFunction_constructInterpolatedFromIR(IR) {
  10978. var c0 = IR[1];
  10979. var diff = IR[2];
  10980. var n = IR[3];
  10981. var length = diff.length;
  10982. return function constructInterpolatedFromIRResult(src, srcOffset,
  10983. dest, destOffset) {
  10984. var x = n === 1 ? src[srcOffset] : Math.pow(src[srcOffset], n);
  10985. for (var j = 0; j < length; ++j) {
  10986. dest[destOffset + j] = c0[j] + (x * diff[j]);
  10987. }
  10988. };
  10989. },
  10990. constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {
  10991. var domain = dict.get('Domain');
  10992. if (!domain) {
  10993. error('No domain');
  10994. }
  10995. var inputSize = domain.length / 2;
  10996. if (inputSize !== 1) {
  10997. error('Bad domain for stiched function');
  10998. }
  10999. var fnRefs = dict.get('Functions');
  11000. var fns = [];
  11001. for (var i = 0, ii = fnRefs.length; i < ii; ++i) {
  11002. fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));
  11003. }
  11004. var bounds = dict.get('Bounds');
  11005. var encode = dict.get('Encode');
  11006. return [CONSTRUCT_STICHED, domain, bounds, encode, fns];
  11007. },
  11008. constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {
  11009. var domain = IR[1];
  11010. var bounds = IR[2];
  11011. var encode = IR[3];
  11012. var fnsIR = IR[4];
  11013. var fns = [];
  11014. var tmpBuf = new Float32Array(1);
  11015. for (var i = 0, ii = fnsIR.length; i < ii; i++) {
  11016. fns.push(PDFFunction.fromIR(fnsIR[i]));
  11017. }
  11018. return function constructStichedFromIRResult(src, srcOffset,
  11019. dest, destOffset) {
  11020. var clip = function constructStichedFromIRClip(v, min, max) {
  11021. if (v > max) {
  11022. v = max;
  11023. } else if (v < min) {
  11024. v = min;
  11025. }
  11026. return v;
  11027. };
  11028. // clip to domain
  11029. var v = clip(src[srcOffset], domain[0], domain[1]);
  11030. // calulate which bound the value is in
  11031. for (var i = 0, ii = bounds.length; i < ii; ++i) {
  11032. if (v < bounds[i]) {
  11033. break;
  11034. }
  11035. }
  11036. // encode value into domain of function
  11037. var dmin = domain[0];
  11038. if (i > 0) {
  11039. dmin = bounds[i - 1];
  11040. }
  11041. var dmax = domain[1];
  11042. if (i < bounds.length) {
  11043. dmax = bounds[i];
  11044. }
  11045. var rmin = encode[2 * i];
  11046. var rmax = encode[2 * i + 1];
  11047. // Prevent the value from becoming NaN as a result
  11048. // of division by zero (fixes issue6113.pdf).
  11049. tmpBuf[0] = dmin === dmax ? rmin :
  11050. rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  11051. // call the appropriate function
  11052. fns[i](tmpBuf, 0, dest, destOffset);
  11053. };
  11054. },
  11055. constructPostScript: function PDFFunction_constructPostScript(fn, dict,
  11056. xref) {
  11057. var domain = dict.get('Domain');
  11058. var range = dict.get('Range');
  11059. if (!domain) {
  11060. error('No domain.');
  11061. }
  11062. if (!range) {
  11063. error('No range.');
  11064. }
  11065. var lexer = new PostScriptLexer(fn);
  11066. var parser = new PostScriptParser(lexer);
  11067. var code = parser.parse();
  11068. return [CONSTRUCT_POSTSCRIPT, domain, range, code];
  11069. },
  11070. constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(
  11071. IR) {
  11072. var domain = IR[1];
  11073. var range = IR[2];
  11074. var code = IR[3];
  11075. var compiled = (new PostScriptCompiler()).compile(code, domain, range);
  11076. if (compiled) {
  11077. // Compiled function consists of simple expressions such as addition,
  11078. // subtraction, Math.max, and also contains 'var' and 'return'
  11079. // statements. See the generation in the PostScriptCompiler below.
  11080. /*jshint -W054 */
  11081. return new Function('src', 'srcOffset', 'dest', 'destOffset', compiled);
  11082. }
  11083. info('Unable to compile PS function');
  11084. var numOutputs = range.length >> 1;
  11085. var numInputs = domain.length >> 1;
  11086. var evaluator = new PostScriptEvaluator(code);
  11087. // Cache the values for a big speed up, the cache size is limited though
  11088. // since the number of possible values can be huge from a PS function.
  11089. var cache = {};
  11090. // The MAX_CACHE_SIZE is set to ~4x the maximum number of distinct values
  11091. // seen in our tests.
  11092. var MAX_CACHE_SIZE = 2048 * 4;
  11093. var cache_available = MAX_CACHE_SIZE;
  11094. var tmpBuf = new Float32Array(numInputs);
  11095. return function constructPostScriptFromIRResult(src, srcOffset,
  11096. dest, destOffset) {
  11097. var i, value;
  11098. var key = '';
  11099. var input = tmpBuf;
  11100. for (i = 0; i < numInputs; i++) {
  11101. value = src[srcOffset + i];
  11102. input[i] = value;
  11103. key += value + '_';
  11104. }
  11105. var cachedValue = cache[key];
  11106. if (cachedValue !== undefined) {
  11107. dest.set(cachedValue, destOffset);
  11108. return;
  11109. }
  11110. var output = new Float32Array(numOutputs);
  11111. var stack = evaluator.execute(input);
  11112. var stackIndex = stack.length - numOutputs;
  11113. for (i = 0; i < numOutputs; i++) {
  11114. value = stack[stackIndex + i];
  11115. var bound = range[i * 2];
  11116. if (value < bound) {
  11117. value = bound;
  11118. } else {
  11119. bound = range[i * 2 +1];
  11120. if (value > bound) {
  11121. value = bound;
  11122. }
  11123. }
  11124. output[i] = value;
  11125. }
  11126. if (cache_available > 0) {
  11127. cache_available--;
  11128. cache[key] = output;
  11129. }
  11130. dest.set(output, destOffset);
  11131. };
  11132. }
  11133. };
  11134. })();
  11135. function isPDFFunction(v) {
  11136. var fnDict;
  11137. if (typeof v !== 'object') {
  11138. return false;
  11139. } else if (isDict(v)) {
  11140. fnDict = v;
  11141. } else if (isStream(v)) {
  11142. fnDict = v.dict;
  11143. } else {
  11144. return false;
  11145. }
  11146. return fnDict.has('FunctionType');
  11147. }
  11148. var PostScriptStack = (function PostScriptStackClosure() {
  11149. var MAX_STACK_SIZE = 100;
  11150. function PostScriptStack(initialStack) {
  11151. this.stack = !initialStack ? [] :
  11152. Array.prototype.slice.call(initialStack, 0);
  11153. }
  11154. PostScriptStack.prototype = {
  11155. push: function PostScriptStack_push(value) {
  11156. if (this.stack.length >= MAX_STACK_SIZE) {
  11157. error('PostScript function stack overflow.');
  11158. }
  11159. this.stack.push(value);
  11160. },
  11161. pop: function PostScriptStack_pop() {
  11162. if (this.stack.length <= 0) {
  11163. error('PostScript function stack underflow.');
  11164. }
  11165. return this.stack.pop();
  11166. },
  11167. copy: function PostScriptStack_copy(n) {
  11168. if (this.stack.length + n >= MAX_STACK_SIZE) {
  11169. error('PostScript function stack overflow.');
  11170. }
  11171. var stack = this.stack;
  11172. for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  11173. stack.push(stack[i]);
  11174. }
  11175. },
  11176. index: function PostScriptStack_index(n) {
  11177. this.push(this.stack[this.stack.length - n - 1]);
  11178. },
  11179. // rotate the last n stack elements p times
  11180. roll: function PostScriptStack_roll(n, p) {
  11181. var stack = this.stack;
  11182. var l = stack.length - n;
  11183. var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;
  11184. for (i = l, j = r; i < j; i++, j--) {
  11185. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  11186. }
  11187. for (i = l, j = c - 1; i < j; i++, j--) {
  11188. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  11189. }
  11190. for (i = c, j = r; i < j; i++, j--) {
  11191. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  11192. }
  11193. }
  11194. };
  11195. return PostScriptStack;
  11196. })();
  11197. var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {
  11198. function PostScriptEvaluator(operators) {
  11199. this.operators = operators;
  11200. }
  11201. PostScriptEvaluator.prototype = {
  11202. execute: function PostScriptEvaluator_execute(initialStack) {
  11203. var stack = new PostScriptStack(initialStack);
  11204. var counter = 0;
  11205. var operators = this.operators;
  11206. var length = operators.length;
  11207. var operator, a, b;
  11208. while (counter < length) {
  11209. operator = operators[counter++];
  11210. if (typeof operator === 'number') {
  11211. // Operator is really an operand and should be pushed to the stack.
  11212. stack.push(operator);
  11213. continue;
  11214. }
  11215. switch (operator) {
  11216. // non standard ps operators
  11217. case 'jz': // jump if false
  11218. b = stack.pop();
  11219. a = stack.pop();
  11220. if (!a) {
  11221. counter = b;
  11222. }
  11223. break;
  11224. case 'j': // jump
  11225. a = stack.pop();
  11226. counter = a;
  11227. break;
  11228. // all ps operators in alphabetical order (excluding if/ifelse)
  11229. case 'abs':
  11230. a = stack.pop();
  11231. stack.push(Math.abs(a));
  11232. break;
  11233. case 'add':
  11234. b = stack.pop();
  11235. a = stack.pop();
  11236. stack.push(a + b);
  11237. break;
  11238. case 'and':
  11239. b = stack.pop();
  11240. a = stack.pop();
  11241. if (isBool(a) && isBool(b)) {
  11242. stack.push(a && b);
  11243. } else {
  11244. stack.push(a & b);
  11245. }
  11246. break;
  11247. case 'atan':
  11248. a = stack.pop();
  11249. stack.push(Math.atan(a));
  11250. break;
  11251. case 'bitshift':
  11252. b = stack.pop();
  11253. a = stack.pop();
  11254. if (a > 0) {
  11255. stack.push(a << b);
  11256. } else {
  11257. stack.push(a >> b);
  11258. }
  11259. break;
  11260. case 'ceiling':
  11261. a = stack.pop();
  11262. stack.push(Math.ceil(a));
  11263. break;
  11264. case 'copy':
  11265. a = stack.pop();
  11266. stack.copy(a);
  11267. break;
  11268. case 'cos':
  11269. a = stack.pop();
  11270. stack.push(Math.cos(a));
  11271. break;
  11272. case 'cvi':
  11273. a = stack.pop() | 0;
  11274. stack.push(a);
  11275. break;
  11276. case 'cvr':
  11277. // noop
  11278. break;
  11279. case 'div':
  11280. b = stack.pop();
  11281. a = stack.pop();
  11282. stack.push(a / b);
  11283. break;
  11284. case 'dup':
  11285. stack.copy(1);
  11286. break;
  11287. case 'eq':
  11288. b = stack.pop();
  11289. a = stack.pop();
  11290. stack.push(a === b);
  11291. break;
  11292. case 'exch':
  11293. stack.roll(2, 1);
  11294. break;
  11295. case 'exp':
  11296. b = stack.pop();
  11297. a = stack.pop();
  11298. stack.push(Math.pow(a, b));
  11299. break;
  11300. case 'false':
  11301. stack.push(false);
  11302. break;
  11303. case 'floor':
  11304. a = stack.pop();
  11305. stack.push(Math.floor(a));
  11306. break;
  11307. case 'ge':
  11308. b = stack.pop();
  11309. a = stack.pop();
  11310. stack.push(a >= b);
  11311. break;
  11312. case 'gt':
  11313. b = stack.pop();
  11314. a = stack.pop();
  11315. stack.push(a > b);
  11316. break;
  11317. case 'idiv':
  11318. b = stack.pop();
  11319. a = stack.pop();
  11320. stack.push((a / b) | 0);
  11321. break;
  11322. case 'index':
  11323. a = stack.pop();
  11324. stack.index(a);
  11325. break;
  11326. case 'le':
  11327. b = stack.pop();
  11328. a = stack.pop();
  11329. stack.push(a <= b);
  11330. break;
  11331. case 'ln':
  11332. a = stack.pop();
  11333. stack.push(Math.log(a));
  11334. break;
  11335. case 'log':
  11336. a = stack.pop();
  11337. stack.push(Math.log(a) / Math.LN10);
  11338. break;
  11339. case 'lt':
  11340. b = stack.pop();
  11341. a = stack.pop();
  11342. stack.push(a < b);
  11343. break;
  11344. case 'mod':
  11345. b = stack.pop();
  11346. a = stack.pop();
  11347. stack.push(a % b);
  11348. break;
  11349. case 'mul':
  11350. b = stack.pop();
  11351. a = stack.pop();
  11352. stack.push(a * b);
  11353. break;
  11354. case 'ne':
  11355. b = stack.pop();
  11356. a = stack.pop();
  11357. stack.push(a !== b);
  11358. break;
  11359. case 'neg':
  11360. a = stack.pop();
  11361. stack.push(-a);
  11362. break;
  11363. case 'not':
  11364. a = stack.pop();
  11365. if (isBool(a)) {
  11366. stack.push(!a);
  11367. } else {
  11368. stack.push(~a);
  11369. }
  11370. break;
  11371. case 'or':
  11372. b = stack.pop();
  11373. a = stack.pop();
  11374. if (isBool(a) && isBool(b)) {
  11375. stack.push(a || b);
  11376. } else {
  11377. stack.push(a | b);
  11378. }
  11379. break;
  11380. case 'pop':
  11381. stack.pop();
  11382. break;
  11383. case 'roll':
  11384. b = stack.pop();
  11385. a = stack.pop();
  11386. stack.roll(a, b);
  11387. break;
  11388. case 'round':
  11389. a = stack.pop();
  11390. stack.push(Math.round(a));
  11391. break;
  11392. case 'sin':
  11393. a = stack.pop();
  11394. stack.push(Math.sin(a));
  11395. break;
  11396. case 'sqrt':
  11397. a = stack.pop();
  11398. stack.push(Math.sqrt(a));
  11399. break;
  11400. case 'sub':
  11401. b = stack.pop();
  11402. a = stack.pop();
  11403. stack.push(a - b);
  11404. break;
  11405. case 'true':
  11406. stack.push(true);
  11407. break;
  11408. case 'truncate':
  11409. a = stack.pop();
  11410. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  11411. stack.push(a);
  11412. break;
  11413. case 'xor':
  11414. b = stack.pop();
  11415. a = stack.pop();
  11416. if (isBool(a) && isBool(b)) {
  11417. stack.push(a !== b);
  11418. } else {
  11419. stack.push(a ^ b);
  11420. }
  11421. break;
  11422. default:
  11423. error('Unknown operator ' + operator);
  11424. break;
  11425. }
  11426. }
  11427. return stack.stack;
  11428. }
  11429. };
  11430. return PostScriptEvaluator;
  11431. })();
  11432. // Most of the PDFs functions consist of simple operations such as:
  11433. // roll, exch, sub, cvr, pop, index, dup, mul, if, gt, add.
  11434. //
  11435. // We can compile most of such programs, and at the same moment, we can
  11436. // optimize some expressions using basic math properties. Keeping track of
  11437. // min/max values will allow us to avoid extra Math.min/Math.max calls.
  11438. var PostScriptCompiler = (function PostScriptCompilerClosure() {
  11439. function AstNode(type) {
  11440. this.type = type;
  11441. }
  11442. AstNode.prototype.visit = function (visitor) {
  11443. throw new Error('abstract method');
  11444. };
  11445. function AstArgument(index, min, max) {
  11446. AstNode.call(this, 'args');
  11447. this.index = index;
  11448. this.min = min;
  11449. this.max = max;
  11450. }
  11451. AstArgument.prototype = Object.create(AstNode.prototype);
  11452. AstArgument.prototype.visit = function (visitor) {
  11453. visitor.visitArgument(this);
  11454. };
  11455. function AstLiteral(number) {
  11456. AstNode.call(this, 'literal');
  11457. this.number = number;
  11458. this.min = number;
  11459. this.max = number;
  11460. }
  11461. AstLiteral.prototype = Object.create(AstNode.prototype);
  11462. AstLiteral.prototype.visit = function (visitor) {
  11463. visitor.visitLiteral(this);
  11464. };
  11465. function AstBinaryOperation(op, arg1, arg2, min, max) {
  11466. AstNode.call(this, 'binary');
  11467. this.op = op;
  11468. this.arg1 = arg1;
  11469. this.arg2 = arg2;
  11470. this.min = min;
  11471. this.max = max;
  11472. }
  11473. AstBinaryOperation.prototype = Object.create(AstNode.prototype);
  11474. AstBinaryOperation.prototype.visit = function (visitor) {
  11475. visitor.visitBinaryOperation(this);
  11476. };
  11477. function AstMin(arg, max) {
  11478. AstNode.call(this, 'max');
  11479. this.arg = arg;
  11480. this.min = arg.min;
  11481. this.max = max;
  11482. }
  11483. AstMin.prototype = Object.create(AstNode.prototype);
  11484. AstMin.prototype.visit = function (visitor) {
  11485. visitor.visitMin(this);
  11486. };
  11487. function AstVariable(index, min, max) {
  11488. AstNode.call(this, 'var');
  11489. this.index = index;
  11490. this.min = min;
  11491. this.max = max;
  11492. }
  11493. AstVariable.prototype = Object.create(AstNode.prototype);
  11494. AstVariable.prototype.visit = function (visitor) {
  11495. visitor.visitVariable(this);
  11496. };
  11497. function AstVariableDefinition(variable, arg) {
  11498. AstNode.call(this, 'definition');
  11499. this.variable = variable;
  11500. this.arg = arg;
  11501. }
  11502. AstVariableDefinition.prototype = Object.create(AstNode.prototype);
  11503. AstVariableDefinition.prototype.visit = function (visitor) {
  11504. visitor.visitVariableDefinition(this);
  11505. };
  11506. function ExpressionBuilderVisitor() {
  11507. this.parts = [];
  11508. }
  11509. ExpressionBuilderVisitor.prototype = {
  11510. visitArgument: function (arg) {
  11511. this.parts.push('Math.max(', arg.min, ', Math.min(',
  11512. arg.max, ', src[srcOffset + ', arg.index, ']))');
  11513. },
  11514. visitVariable: function (variable) {
  11515. this.parts.push('v', variable.index);
  11516. },
  11517. visitLiteral: function (literal) {
  11518. this.parts.push(literal.number);
  11519. },
  11520. visitBinaryOperation: function (operation) {
  11521. this.parts.push('(');
  11522. operation.arg1.visit(this);
  11523. this.parts.push(' ', operation.op, ' ');
  11524. operation.arg2.visit(this);
  11525. this.parts.push(')');
  11526. },
  11527. visitVariableDefinition: function (definition) {
  11528. this.parts.push('var ');
  11529. definition.variable.visit(this);
  11530. this.parts.push(' = ');
  11531. definition.arg.visit(this);
  11532. this.parts.push(';');
  11533. },
  11534. visitMin: function (max) {
  11535. this.parts.push('Math.min(');
  11536. max.arg.visit(this);
  11537. this.parts.push(', ', max.max, ')');
  11538. },
  11539. toString: function () {
  11540. return this.parts.join('');
  11541. }
  11542. };
  11543. function buildAddOperation(num1, num2) {
  11544. if (num2.type === 'literal' && num2.number === 0) {
  11545. // optimization: second operand is 0
  11546. return num1;
  11547. }
  11548. if (num1.type === 'literal' && num1.number === 0) {
  11549. // optimization: first operand is 0
  11550. return num2;
  11551. }
  11552. if (num2.type === 'literal' && num1.type === 'literal') {
  11553. // optimization: operands operand are literals
  11554. return new AstLiteral(num1.number + num2.number);
  11555. }
  11556. return new AstBinaryOperation('+', num1, num2,
  11557. num1.min + num2.min, num1.max + num2.max);
  11558. }
  11559. function buildMulOperation(num1, num2) {
  11560. if (num2.type === 'literal') {
  11561. // optimization: second operands is a literal...
  11562. if (num2.number === 0) {
  11563. return new AstLiteral(0); // and it's 0
  11564. } else if (num2.number === 1) {
  11565. return num1; // and it's 1
  11566. } else if (num1.type === 'literal') {
  11567. // ... and first operands is a literal too
  11568. return new AstLiteral(num1.number * num2.number);
  11569. }
  11570. }
  11571. if (num1.type === 'literal') {
  11572. // optimization: first operands is a literal...
  11573. if (num1.number === 0) {
  11574. return new AstLiteral(0); // and it's 0
  11575. } else if (num1.number === 1) {
  11576. return num2; // and it's 1
  11577. }
  11578. }
  11579. var min = Math.min(num1.min * num2.min, num1.min * num2.max,
  11580. num1.max * num2.min, num1.max * num2.max);
  11581. var max = Math.max(num1.min * num2.min, num1.min * num2.max,
  11582. num1.max * num2.min, num1.max * num2.max);
  11583. return new AstBinaryOperation('*', num1, num2, min, max);
  11584. }
  11585. function buildSubOperation(num1, num2) {
  11586. if (num2.type === 'literal') {
  11587. // optimization: second operands is a literal...
  11588. if (num2.number === 0) {
  11589. return num1; // ... and it's 0
  11590. } else if (num1.type === 'literal') {
  11591. // ... and first operands is a literal too
  11592. return new AstLiteral(num1.number - num2.number);
  11593. }
  11594. }
  11595. if (num2.type === 'binary' && num2.op === '-' &&
  11596. num1.type === 'literal' && num1.number === 1 &&
  11597. num2.arg1.type === 'literal' && num2.arg1.number === 1) {
  11598. // optimization for case: 1 - (1 - x)
  11599. return num2.arg2;
  11600. }
  11601. return new AstBinaryOperation('-', num1, num2,
  11602. num1.min - num2.max, num1.max - num2.min);
  11603. }
  11604. function buildMinOperation(num1, max) {
  11605. if (num1.min >= max) {
  11606. // optimization: num1 min value is not less than required max
  11607. return new AstLiteral(max); // just returning max
  11608. } else if (num1.max <= max) {
  11609. // optimization: num1 max value is not greater than required max
  11610. return num1; // just returning an argument
  11611. }
  11612. return new AstMin(num1, max);
  11613. }
  11614. function PostScriptCompiler() {}
  11615. PostScriptCompiler.prototype = {
  11616. compile: function PostScriptCompiler_compile(code, domain, range) {
  11617. var stack = [];
  11618. var i, ii;
  11619. var instructions = [];
  11620. var inputSize = domain.length >> 1, outputSize = range.length >> 1;
  11621. var lastRegister = 0;
  11622. var n, j, min, max;
  11623. var num1, num2, ast1, ast2, tmpVar, item;
  11624. for (i = 0; i < inputSize; i++) {
  11625. stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
  11626. }
  11627. for (i = 0, ii = code.length; i < ii; i++) {
  11628. item = code[i];
  11629. if (typeof item === 'number') {
  11630. stack.push(new AstLiteral(item));
  11631. continue;
  11632. }
  11633. switch (item) {
  11634. case 'add':
  11635. if (stack.length < 2) {
  11636. return null;
  11637. }
  11638. num2 = stack.pop();
  11639. num1 = stack.pop();
  11640. stack.push(buildAddOperation(num1, num2));
  11641. break;
  11642. case 'cvr':
  11643. if (stack.length < 1) {
  11644. return null;
  11645. }
  11646. break;
  11647. case 'mul':
  11648. if (stack.length < 2) {
  11649. return null;
  11650. }
  11651. num2 = stack.pop();
  11652. num1 = stack.pop();
  11653. stack.push(buildMulOperation(num1, num2));
  11654. break;
  11655. case 'sub':
  11656. if (stack.length < 2) {
  11657. return null;
  11658. }
  11659. num2 = stack.pop();
  11660. num1 = stack.pop();
  11661. stack.push(buildSubOperation(num1, num2));
  11662. break;
  11663. case 'exch':
  11664. if (stack.length < 2) {
  11665. return null;
  11666. }
  11667. ast1 = stack.pop(); ast2 = stack.pop();
  11668. stack.push(ast1, ast2);
  11669. break;
  11670. case 'pop':
  11671. if (stack.length < 1) {
  11672. return null;
  11673. }
  11674. stack.pop();
  11675. break;
  11676. case 'index':
  11677. if (stack.length < 1) {
  11678. return null;
  11679. }
  11680. num1 = stack.pop();
  11681. if (num1.type !== 'literal') {
  11682. return null;
  11683. }
  11684. n = num1.number;
  11685. if (n < 0 || (n|0) !== n || stack.length < n) {
  11686. return null;
  11687. }
  11688. ast1 = stack[stack.length - n - 1];
  11689. if (ast1.type === 'literal' || ast1.type === 'var') {
  11690. stack.push(ast1);
  11691. break;
  11692. }
  11693. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  11694. stack[stack.length - n - 1] = tmpVar;
  11695. stack.push(tmpVar);
  11696. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  11697. break;
  11698. case 'dup':
  11699. if (stack.length < 1) {
  11700. return null;
  11701. }
  11702. if (typeof code[i + 1] === 'number' && code[i + 2] === 'gt' &&
  11703. code[i + 3] === i + 7 && code[i + 4] === 'jz' &&
  11704. code[i + 5] === 'pop' && code[i + 6] === code[i + 1]) {
  11705. // special case of the commands sequence for the min operation
  11706. num1 = stack.pop();
  11707. stack.push(buildMinOperation(num1, code[i + 1]));
  11708. i += 6;
  11709. break;
  11710. }
  11711. ast1 = stack[stack.length - 1];
  11712. if (ast1.type === 'literal' || ast1.type === 'var') {
  11713. // we don't have to save into intermediate variable a literal or
  11714. // variable.
  11715. stack.push(ast1);
  11716. break;
  11717. }
  11718. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  11719. stack[stack.length - 1] = tmpVar;
  11720. stack.push(tmpVar);
  11721. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  11722. break;
  11723. case 'roll':
  11724. if (stack.length < 2) {
  11725. return null;
  11726. }
  11727. num2 = stack.pop();
  11728. num1 = stack.pop();
  11729. if (num2.type !== 'literal' || num1.type !== 'literal') {
  11730. // both roll operands must be numbers
  11731. return null;
  11732. }
  11733. j = num2.number;
  11734. n = num1.number;
  11735. if (n <= 0 || (n|0) !== n || (j|0) !== j || stack.length < n) {
  11736. // ... and integers
  11737. return null;
  11738. }
  11739. j = ((j % n) + n) % n;
  11740. if (j === 0) {
  11741. break; // just skipping -- there are nothing to rotate
  11742. }
  11743. Array.prototype.push.apply(stack,
  11744. stack.splice(stack.length - n, n - j));
  11745. break;
  11746. default:
  11747. return null; // unsupported operator
  11748. }
  11749. }
  11750. if (stack.length !== outputSize) {
  11751. return null;
  11752. }
  11753. var result = [];
  11754. instructions.forEach(function (instruction) {
  11755. var statementBuilder = new ExpressionBuilderVisitor();
  11756. instruction.visit(statementBuilder);
  11757. result.push(statementBuilder.toString());
  11758. });
  11759. stack.forEach(function (expr, i) {
  11760. var statementBuilder = new ExpressionBuilderVisitor();
  11761. expr.visit(statementBuilder);
  11762. var min = range[i * 2], max = range[i * 2 + 1];
  11763. var out = [statementBuilder.toString()];
  11764. if (min > expr.min) {
  11765. out.unshift('Math.max(', min, ', ');
  11766. out.push(')');
  11767. }
  11768. if (max < expr.max) {
  11769. out.unshift('Math.min(', max, ', ');
  11770. out.push(')');
  11771. }
  11772. out.unshift('dest[destOffset + ', i, '] = ');
  11773. out.push(';');
  11774. result.push(out.join(''));
  11775. });
  11776. return result.join('\n');
  11777. }
  11778. };
  11779. return PostScriptCompiler;
  11780. })();
  11781. var ColorSpace = (function ColorSpaceClosure() {
  11782. // Constructor should define this.numComps, this.defaultColor, this.name
  11783. function ColorSpace() {
  11784. error('should not call ColorSpace constructor');
  11785. }
  11786. ColorSpace.prototype = {
  11787. /**
  11788. * Converts the color value to the RGB color. The color components are
  11789. * located in the src array starting from the srcOffset. Returns the array
  11790. * of the rgb components, each value ranging from [0,255].
  11791. */
  11792. getRgb: function ColorSpace_getRgb(src, srcOffset) {
  11793. var rgb = new Uint8Array(3);
  11794. this.getRgbItem(src, srcOffset, rgb, 0);
  11795. return rgb;
  11796. },
  11797. /**
  11798. * Converts the color value to the RGB color, similar to the getRgb method.
  11799. * The result placed into the dest array starting from the destOffset.
  11800. */
  11801. getRgbItem: function ColorSpace_getRgbItem(src, srcOffset,
  11802. dest, destOffset) {
  11803. error('Should not call ColorSpace.getRgbItem');
  11804. },
  11805. /**
  11806. * Converts the specified number of the color values to the RGB colors.
  11807. * The colors are located in the src array starting from the srcOffset.
  11808. * The result is placed into the dest array starting from the destOffset.
  11809. * The src array items shall be in [0,2^bits) range, the dest array items
  11810. * will be in [0,255] range. alpha01 indicates how many alpha components
  11811. * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA
  11812. * array).
  11813. */
  11814. getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,
  11815. dest, destOffset, bits,
  11816. alpha01) {
  11817. error('Should not call ColorSpace.getRgbBuffer');
  11818. },
  11819. /**
  11820. * Determines the number of bytes required to store the result of the
  11821. * conversion done by the getRgbBuffer method. As in getRgbBuffer,
  11822. * |alpha01| is either 0 (RGB output) or 1 (RGBA output).
  11823. */
  11824. getOutputLength: function ColorSpace_getOutputLength(inputLength,
  11825. alpha01) {
  11826. error('Should not call ColorSpace.getOutputLength');
  11827. },
  11828. /**
  11829. * Returns true if source data will be equal the result/output data.
  11830. */
  11831. isPassthrough: function ColorSpace_isPassthrough(bits) {
  11832. return false;
  11833. },
  11834. /**
  11835. * Fills in the RGB colors in the destination buffer. alpha01 indicates
  11836. * how many alpha components there are in the dest array; it will be either
  11837. * 0 (RGB array) or 1 (RGBA array).
  11838. */
  11839. fillRgb: function ColorSpace_fillRgb(dest, originalWidth,
  11840. originalHeight, width, height,
  11841. actualHeight, bpc, comps, alpha01) {
  11842. var count = originalWidth * originalHeight;
  11843. var rgbBuf = null;
  11844. var numComponentColors = 1 << bpc;
  11845. var needsResizing = originalHeight !== height || originalWidth !== width;
  11846. var i, ii;
  11847. if (this.isPassthrough(bpc)) {
  11848. rgbBuf = comps;
  11849. } else if (this.numComps === 1 && count > numComponentColors &&
  11850. this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {
  11851. // Optimization: create a color map when there is just one component and
  11852. // we are converting more colors than the size of the color map. We
  11853. // don't build the map if the colorspace is gray or rgb since those
  11854. // methods are faster than building a map. This mainly offers big speed
  11855. // ups for indexed and alternate colorspaces.
  11856. //
  11857. // TODO it may be worth while to cache the color map. While running
  11858. // testing I never hit a cache so I will leave that out for now (perhaps
  11859. // we are reparsing colorspaces too much?).
  11860. var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) :
  11861. new Uint16Array(numComponentColors);
  11862. var key;
  11863. for (i = 0; i < numComponentColors; i++) {
  11864. allColors[i] = i;
  11865. }
  11866. var colorMap = new Uint8Array(numComponentColors * 3);
  11867. this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,
  11868. /* alpha01 = */ 0);
  11869. var destPos, rgbPos;
  11870. if (!needsResizing) {
  11871. // Fill in the RGB values directly into |dest|.
  11872. destPos = 0;
  11873. for (i = 0; i < count; ++i) {
  11874. key = comps[i] * 3;
  11875. dest[destPos++] = colorMap[key];
  11876. dest[destPos++] = colorMap[key + 1];
  11877. dest[destPos++] = colorMap[key + 2];
  11878. destPos += alpha01;
  11879. }
  11880. } else {
  11881. rgbBuf = new Uint8Array(count * 3);
  11882. rgbPos = 0;
  11883. for (i = 0; i < count; ++i) {
  11884. key = comps[i] * 3;
  11885. rgbBuf[rgbPos++] = colorMap[key];
  11886. rgbBuf[rgbPos++] = colorMap[key + 1];
  11887. rgbBuf[rgbPos++] = colorMap[key + 2];
  11888. }
  11889. }
  11890. } else {
  11891. if (!needsResizing) {
  11892. // Fill in the RGB values directly into |dest|.
  11893. this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc,
  11894. alpha01);
  11895. } else {
  11896. rgbBuf = new Uint8Array(count * 3);
  11897. this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc,
  11898. /* alpha01 = */ 0);
  11899. }
  11900. }
  11901. if (rgbBuf) {
  11902. if (needsResizing) {
  11903. PDFImage.resize(rgbBuf, bpc, 3, originalWidth, originalHeight, width,
  11904. height, dest, alpha01);
  11905. } else {
  11906. rgbPos = 0;
  11907. destPos = 0;
  11908. for (i = 0, ii = width * actualHeight; i < ii; i++) {
  11909. dest[destPos++] = rgbBuf[rgbPos++];
  11910. dest[destPos++] = rgbBuf[rgbPos++];
  11911. dest[destPos++] = rgbBuf[rgbPos++];
  11912. destPos += alpha01;
  11913. }
  11914. }
  11915. }
  11916. },
  11917. /**
  11918. * True if the colorspace has components in the default range of [0, 1].
  11919. * This should be true for all colorspaces except for lab color spaces
  11920. * which are [0,100], [-128, 127], [-128, 127].
  11921. */
  11922. usesZeroToOneRange: true
  11923. };
  11924. ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {
  11925. var IR = ColorSpace.parseToIR(cs, xref, res);
  11926. if (IR instanceof AlternateCS) {
  11927. return IR;
  11928. }
  11929. return ColorSpace.fromIR(IR);
  11930. };
  11931. ColorSpace.fromIR = function ColorSpace_fromIR(IR) {
  11932. var name = isArray(IR) ? IR[0] : IR;
  11933. var whitePoint, blackPoint, gamma;
  11934. switch (name) {
  11935. case 'DeviceGrayCS':
  11936. return this.singletons.gray;
  11937. case 'DeviceRgbCS':
  11938. return this.singletons.rgb;
  11939. case 'DeviceCmykCS':
  11940. return this.singletons.cmyk;
  11941. case 'CalGrayCS':
  11942. whitePoint = IR[1].WhitePoint;
  11943. blackPoint = IR[1].BlackPoint;
  11944. gamma = IR[1].Gamma;
  11945. return new CalGrayCS(whitePoint, blackPoint, gamma);
  11946. case 'CalRGBCS':
  11947. whitePoint = IR[1].WhitePoint;
  11948. blackPoint = IR[1].BlackPoint;
  11949. gamma = IR[1].Gamma;
  11950. var matrix = IR[1].Matrix;
  11951. return new CalRGBCS(whitePoint, blackPoint, gamma, matrix);
  11952. case 'PatternCS':
  11953. var basePatternCS = IR[1];
  11954. if (basePatternCS) {
  11955. basePatternCS = ColorSpace.fromIR(basePatternCS);
  11956. }
  11957. return new PatternCS(basePatternCS);
  11958. case 'IndexedCS':
  11959. var baseIndexedCS = IR[1];
  11960. var hiVal = IR[2];
  11961. var lookup = IR[3];
  11962. return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);
  11963. case 'AlternateCS':
  11964. var numComps = IR[1];
  11965. var alt = IR[2];
  11966. var tintFnIR = IR[3];
  11967. return new AlternateCS(numComps, ColorSpace.fromIR(alt),
  11968. PDFFunction.fromIR(tintFnIR));
  11969. case 'LabCS':
  11970. whitePoint = IR[1].WhitePoint;
  11971. blackPoint = IR[1].BlackPoint;
  11972. var range = IR[1].Range;
  11973. return new LabCS(whitePoint, blackPoint, range);
  11974. default:
  11975. error('Unknown name ' + name);
  11976. }
  11977. return null;
  11978. };
  11979. ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
  11980. if (isName(cs)) {
  11981. var colorSpaces = res.get('ColorSpace');
  11982. if (isDict(colorSpaces)) {
  11983. var refcs = colorSpaces.get(cs.name);
  11984. if (refcs) {
  11985. cs = refcs;
  11986. }
  11987. }
  11988. }
  11989. cs = xref.fetchIfRef(cs);
  11990. var mode;
  11991. if (isName(cs)) {
  11992. mode = cs.name;
  11993. this.mode = mode;
  11994. switch (mode) {
  11995. case 'DeviceGray':
  11996. case 'G':
  11997. return 'DeviceGrayCS';
  11998. case 'DeviceRGB':
  11999. case 'RGB':
  12000. return 'DeviceRgbCS';
  12001. case 'DeviceCMYK':
  12002. case 'CMYK':
  12003. return 'DeviceCmykCS';
  12004. case 'Pattern':
  12005. return ['PatternCS', null];
  12006. default:
  12007. error('unrecognized colorspace ' + mode);
  12008. }
  12009. } else if (isArray(cs)) {
  12010. mode = xref.fetchIfRef(cs[0]).name;
  12011. this.mode = mode;
  12012. var numComps, params, alt;
  12013. switch (mode) {
  12014. case 'DeviceGray':
  12015. case 'G':
  12016. return 'DeviceGrayCS';
  12017. case 'DeviceRGB':
  12018. case 'RGB':
  12019. return 'DeviceRgbCS';
  12020. case 'DeviceCMYK':
  12021. case 'CMYK':
  12022. return 'DeviceCmykCS';
  12023. case 'CalGray':
  12024. params = xref.fetchIfRef(cs[1]).getAll();
  12025. return ['CalGrayCS', params];
  12026. case 'CalRGB':
  12027. params = xref.fetchIfRef(cs[1]).getAll();
  12028. return ['CalRGBCS', params];
  12029. case 'ICCBased':
  12030. var stream = xref.fetchIfRef(cs[1]);
  12031. var dict = stream.dict;
  12032. numComps = dict.get('N');
  12033. alt = dict.get('Alternate');
  12034. if (alt) {
  12035. var altIR = ColorSpace.parseToIR(alt, xref, res);
  12036. // Parse the /Alternate CS to ensure that the number of components
  12037. // are correct, and also (indirectly) that it is not a PatternCS.
  12038. var altCS = ColorSpace.fromIR(altIR);
  12039. if (altCS.numComps === numComps) {
  12040. return altIR;
  12041. }
  12042. warn('ICCBased color space: Ignoring incorrect /Alternate entry.');
  12043. }
  12044. if (numComps === 1) {
  12045. return 'DeviceGrayCS';
  12046. } else if (numComps === 3) {
  12047. return 'DeviceRgbCS';
  12048. } else if (numComps === 4) {
  12049. return 'DeviceCmykCS';
  12050. }
  12051. break;
  12052. case 'Pattern':
  12053. var basePatternCS = cs[1] || null;
  12054. if (basePatternCS) {
  12055. basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);
  12056. }
  12057. return ['PatternCS', basePatternCS];
  12058. case 'Indexed':
  12059. case 'I':
  12060. var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);
  12061. var hiVal = xref.fetchIfRef(cs[2]) + 1;
  12062. var lookup = xref.fetchIfRef(cs[3]);
  12063. if (isStream(lookup)) {
  12064. lookup = lookup.getBytes();
  12065. }
  12066. return ['IndexedCS', baseIndexedCS, hiVal, lookup];
  12067. case 'Separation':
  12068. case 'DeviceN':
  12069. var name = xref.fetchIfRef(cs[1]);
  12070. numComps = 1;
  12071. if (isName(name)) {
  12072. numComps = 1;
  12073. } else if (isArray(name)) {
  12074. numComps = name.length;
  12075. }
  12076. alt = ColorSpace.parseToIR(cs[2], xref, res);
  12077. var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));
  12078. return ['AlternateCS', numComps, alt, tintFnIR];
  12079. case 'Lab':
  12080. params = xref.fetchIfRef(cs[1]).getAll();
  12081. return ['LabCS', params];
  12082. default:
  12083. error('unimplemented color space object "' + mode + '"');
  12084. }
  12085. } else {
  12086. error('unrecognized color space object: "' + cs + '"');
  12087. }
  12088. return null;
  12089. };
  12090. /**
  12091. * Checks if a decode map matches the default decode map for a color space.
  12092. * This handles the general decode maps where there are two values per
  12093. * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color.
  12094. * This does not handle Lab, Indexed, or Pattern decode maps since they are
  12095. * slightly different.
  12096. * @param {Array} decode Decode map (usually from an image).
  12097. * @param {Number} n Number of components the color space has.
  12098. */
  12099. ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {
  12100. if (!isArray(decode)) {
  12101. return true;
  12102. }
  12103. if (n * 2 !== decode.length) {
  12104. warn('The decode map is not the correct length');
  12105. return true;
  12106. }
  12107. for (var i = 0, ii = decode.length; i < ii; i += 2) {
  12108. if (decode[i] !== 0 || decode[i + 1] !== 1) {
  12109. return false;
  12110. }
  12111. }
  12112. return true;
  12113. };
  12114. ColorSpace.singletons = {
  12115. get gray() {
  12116. return shadow(this, 'gray', new DeviceGrayCS());
  12117. },
  12118. get rgb() {
  12119. return shadow(this, 'rgb', new DeviceRgbCS());
  12120. },
  12121. get cmyk() {
  12122. return shadow(this, 'cmyk', new DeviceCmykCS());
  12123. }
  12124. };
  12125. return ColorSpace;
  12126. })();
  12127. /**
  12128. * Alternate color space handles both Separation and DeviceN color spaces. A
  12129. * Separation color space is actually just a DeviceN with one color component.
  12130. * Both color spaces use a tinting function to convert colors to a base color
  12131. * space.
  12132. */
  12133. var AlternateCS = (function AlternateCSClosure() {
  12134. function AlternateCS(numComps, base, tintFn) {
  12135. this.name = 'Alternate';
  12136. this.numComps = numComps;
  12137. this.defaultColor = new Float32Array(numComps);
  12138. for (var i = 0; i < numComps; ++i) {
  12139. this.defaultColor[i] = 1;
  12140. }
  12141. this.base = base;
  12142. this.tintFn = tintFn;
  12143. this.tmpBuf = new Float32Array(base.numComps);
  12144. }
  12145. AlternateCS.prototype = {
  12146. getRgb: ColorSpace.prototype.getRgb,
  12147. getRgbItem: function AlternateCS_getRgbItem(src, srcOffset,
  12148. dest, destOffset) {
  12149. var tmpBuf = this.tmpBuf;
  12150. this.tintFn(src, srcOffset, tmpBuf, 0);
  12151. this.base.getRgbItem(tmpBuf, 0, dest, destOffset);
  12152. },
  12153. getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count,
  12154. dest, destOffset, bits,
  12155. alpha01) {
  12156. var tintFn = this.tintFn;
  12157. var base = this.base;
  12158. var scale = 1 / ((1 << bits) - 1);
  12159. var baseNumComps = base.numComps;
  12160. var usesZeroToOneRange = base.usesZeroToOneRange;
  12161. var isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) &&
  12162. alpha01 === 0;
  12163. var pos = isPassthrough ? destOffset : 0;
  12164. var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count);
  12165. var numComps = this.numComps;
  12166. var scaled = new Float32Array(numComps);
  12167. var tinted = new Float32Array(baseNumComps);
  12168. var i, j;
  12169. if (usesZeroToOneRange) {
  12170. for (i = 0; i < count; i++) {
  12171. for (j = 0; j < numComps; j++) {
  12172. scaled[j] = src[srcOffset++] * scale;
  12173. }
  12174. tintFn(scaled, 0, tinted, 0);
  12175. for (j = 0; j < baseNumComps; j++) {
  12176. baseBuf[pos++] = tinted[j] * 255;
  12177. }
  12178. }
  12179. } else {
  12180. for (i = 0; i < count; i++) {
  12181. for (j = 0; j < numComps; j++) {
  12182. scaled[j] = src[srcOffset++] * scale;
  12183. }
  12184. tintFn(scaled, 0, tinted, 0);
  12185. base.getRgbItem(tinted, 0, baseBuf, pos);
  12186. pos += baseNumComps;
  12187. }
  12188. }
  12189. if (!isPassthrough) {
  12190. base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
  12191. }
  12192. },
  12193. getOutputLength: function AlternateCS_getOutputLength(inputLength,
  12194. alpha01) {
  12195. return this.base.getOutputLength(inputLength *
  12196. this.base.numComps / this.numComps,
  12197. alpha01);
  12198. },
  12199. isPassthrough: ColorSpace.prototype.isPassthrough,
  12200. fillRgb: ColorSpace.prototype.fillRgb,
  12201. isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {
  12202. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12203. },
  12204. usesZeroToOneRange: true
  12205. };
  12206. return AlternateCS;
  12207. })();
  12208. var PatternCS = (function PatternCSClosure() {
  12209. function PatternCS(baseCS) {
  12210. this.name = 'Pattern';
  12211. this.base = baseCS;
  12212. }
  12213. PatternCS.prototype = {};
  12214. return PatternCS;
  12215. })();
  12216. var IndexedCS = (function IndexedCSClosure() {
  12217. function IndexedCS(base, highVal, lookup) {
  12218. this.name = 'Indexed';
  12219. this.numComps = 1;
  12220. this.defaultColor = new Uint8Array([0]);
  12221. this.base = base;
  12222. this.highVal = highVal;
  12223. var baseNumComps = base.numComps;
  12224. var length = baseNumComps * highVal;
  12225. var lookupArray;
  12226. if (isStream(lookup)) {
  12227. lookupArray = new Uint8Array(length);
  12228. var bytes = lookup.getBytes(length);
  12229. lookupArray.set(bytes);
  12230. } else if (isString(lookup)) {
  12231. lookupArray = new Uint8Array(length);
  12232. for (var i = 0; i < length; ++i) {
  12233. lookupArray[i] = lookup.charCodeAt(i);
  12234. }
  12235. } else if (lookup instanceof Uint8Array || lookup instanceof Array) {
  12236. lookupArray = lookup;
  12237. } else {
  12238. error('Unrecognized lookup table: ' + lookup);
  12239. }
  12240. this.lookup = lookupArray;
  12241. }
  12242. IndexedCS.prototype = {
  12243. getRgb: ColorSpace.prototype.getRgb,
  12244. getRgbItem: function IndexedCS_getRgbItem(src, srcOffset,
  12245. dest, destOffset) {
  12246. var numComps = this.base.numComps;
  12247. var start = src[srcOffset] * numComps;
  12248. this.base.getRgbItem(this.lookup, start, dest, destOffset);
  12249. },
  12250. getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count,
  12251. dest, destOffset, bits,
  12252. alpha01) {
  12253. var base = this.base;
  12254. var numComps = base.numComps;
  12255. var outputDelta = base.getOutputLength(numComps, alpha01);
  12256. var lookup = this.lookup;
  12257. for (var i = 0; i < count; ++i) {
  12258. var lookupPos = src[srcOffset++] * numComps;
  12259. base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);
  12260. destOffset += outputDelta;
  12261. }
  12262. },
  12263. getOutputLength: function IndexedCS_getOutputLength(inputLength, alpha01) {
  12264. return this.base.getOutputLength(inputLength * this.base.numComps,
  12265. alpha01);
  12266. },
  12267. isPassthrough: ColorSpace.prototype.isPassthrough,
  12268. fillRgb: ColorSpace.prototype.fillRgb,
  12269. isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {
  12270. // indexed color maps shouldn't be changed
  12271. return true;
  12272. },
  12273. usesZeroToOneRange: true
  12274. };
  12275. return IndexedCS;
  12276. })();
  12277. var DeviceGrayCS = (function DeviceGrayCSClosure() {
  12278. function DeviceGrayCS() {
  12279. this.name = 'DeviceGray';
  12280. this.numComps = 1;
  12281. this.defaultColor = new Float32Array([0]);
  12282. }
  12283. DeviceGrayCS.prototype = {
  12284. getRgb: ColorSpace.prototype.getRgb,
  12285. getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset,
  12286. dest, destOffset) {
  12287. var c = (src[srcOffset] * 255) | 0;
  12288. c = c < 0 ? 0 : c > 255 ? 255 : c;
  12289. dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;
  12290. },
  12291. getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count,
  12292. dest, destOffset, bits,
  12293. alpha01) {
  12294. var scale = 255 / ((1 << bits) - 1);
  12295. var j = srcOffset, q = destOffset;
  12296. for (var i = 0; i < count; ++i) {
  12297. var c = (scale * src[j++]) | 0;
  12298. dest[q++] = c;
  12299. dest[q++] = c;
  12300. dest[q++] = c;
  12301. q += alpha01;
  12302. }
  12303. },
  12304. getOutputLength: function DeviceGrayCS_getOutputLength(inputLength,
  12305. alpha01) {
  12306. return inputLength * (3 + alpha01);
  12307. },
  12308. isPassthrough: ColorSpace.prototype.isPassthrough,
  12309. fillRgb: ColorSpace.prototype.fillRgb,
  12310. isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {
  12311. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12312. },
  12313. usesZeroToOneRange: true
  12314. };
  12315. return DeviceGrayCS;
  12316. })();
  12317. var DeviceRgbCS = (function DeviceRgbCSClosure() {
  12318. function DeviceRgbCS() {
  12319. this.name = 'DeviceRGB';
  12320. this.numComps = 3;
  12321. this.defaultColor = new Float32Array([0, 0, 0]);
  12322. }
  12323. DeviceRgbCS.prototype = {
  12324. getRgb: ColorSpace.prototype.getRgb,
  12325. getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset,
  12326. dest, destOffset) {
  12327. var r = (src[srcOffset] * 255) | 0;
  12328. var g = (src[srcOffset + 1] * 255) | 0;
  12329. var b = (src[srcOffset + 2] * 255) | 0;
  12330. dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r;
  12331. dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g;
  12332. dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b;
  12333. },
  12334. getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count,
  12335. dest, destOffset, bits,
  12336. alpha01) {
  12337. if (bits === 8 && alpha01 === 0) {
  12338. dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);
  12339. return;
  12340. }
  12341. var scale = 255 / ((1 << bits) - 1);
  12342. var j = srcOffset, q = destOffset;
  12343. for (var i = 0; i < count; ++i) {
  12344. dest[q++] = (scale * src[j++]) | 0;
  12345. dest[q++] = (scale * src[j++]) | 0;
  12346. dest[q++] = (scale * src[j++]) | 0;
  12347. q += alpha01;
  12348. }
  12349. },
  12350. getOutputLength: function DeviceRgbCS_getOutputLength(inputLength,
  12351. alpha01) {
  12352. return (inputLength * (3 + alpha01) / 3) | 0;
  12353. },
  12354. isPassthrough: function DeviceRgbCS_isPassthrough(bits) {
  12355. return bits === 8;
  12356. },
  12357. fillRgb: ColorSpace.prototype.fillRgb,
  12358. isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {
  12359. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12360. },
  12361. usesZeroToOneRange: true
  12362. };
  12363. return DeviceRgbCS;
  12364. })();
  12365. var DeviceCmykCS = (function DeviceCmykCSClosure() {
  12366. // The coefficients below was found using numerical analysis: the method of
  12367. // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,
  12368. // where color_value is the tabular value from the table of sampled RGB colors
  12369. // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding
  12370. // CMYK color conversion using the estimation below:
  12371. // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255
  12372. function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {
  12373. var c = src[srcOffset + 0] * srcScale;
  12374. var m = src[srcOffset + 1] * srcScale;
  12375. var y = src[srcOffset + 2] * srcScale;
  12376. var k = src[srcOffset + 3] * srcScale;
  12377. var r =
  12378. (c * (-4.387332384609988 * c + 54.48615194189176 * m +
  12379. 18.82290502165302 * y + 212.25662451639585 * k +
  12380. -285.2331026137004) +
  12381. m * (1.7149763477362134 * m - 5.6096736904047315 * y +
  12382. -17.873870861415444 * k - 5.497006427196366) +
  12383. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  12384. 17.5119270841813) +
  12385. k * (-21.86122147463605 * k - 189.48180835922747) + 255) | 0;
  12386. var g =
  12387. (c * (8.841041422036149 * c + 60.118027045597366 * m +
  12388. 6.871425592049007 * y + 31.159100130055922 * k +
  12389. -79.2970844816548) +
  12390. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  12391. 131.35250912493976 * k - 190.9453302588951) +
  12392. y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +
  12393. k * (-20.737325471181034 * k - 187.80453709719578) + 255) | 0;
  12394. var b =
  12395. (c * (0.8842522430003296 * c + 8.078677503112928 * m +
  12396. 30.89978309703729 * y - 0.23883238689178934 * k +
  12397. -14.183576799673286) +
  12398. m * (10.49593273432072 * m + 63.02378494754052 * y +
  12399. 50.606957656360734 * k - 112.23884253719248) +
  12400. y * (0.03296041114873217 * y + 115.60384449646641 * k +
  12401. -193.58209356861505) +
  12402. k * (-22.33816807309886 * k - 180.12613974708367) + 255) | 0;
  12403. dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r;
  12404. dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;
  12405. dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;
  12406. }
  12407. function DeviceCmykCS() {
  12408. this.name = 'DeviceCMYK';
  12409. this.numComps = 4;
  12410. this.defaultColor = new Float32Array([0, 0, 0, 1]);
  12411. }
  12412. DeviceCmykCS.prototype = {
  12413. getRgb: ColorSpace.prototype.getRgb,
  12414. getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset,
  12415. dest, destOffset) {
  12416. convertToRgb(src, srcOffset, 1, dest, destOffset);
  12417. },
  12418. getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count,
  12419. dest, destOffset, bits,
  12420. alpha01) {
  12421. var scale = 1 / ((1 << bits) - 1);
  12422. for (var i = 0; i < count; i++) {
  12423. convertToRgb(src, srcOffset, scale, dest, destOffset);
  12424. srcOffset += 4;
  12425. destOffset += 3 + alpha01;
  12426. }
  12427. },
  12428. getOutputLength: function DeviceCmykCS_getOutputLength(inputLength,
  12429. alpha01) {
  12430. return (inputLength / 4 * (3 + alpha01)) | 0;
  12431. },
  12432. isPassthrough: ColorSpace.prototype.isPassthrough,
  12433. fillRgb: ColorSpace.prototype.fillRgb,
  12434. isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {
  12435. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12436. },
  12437. usesZeroToOneRange: true
  12438. };
  12439. return DeviceCmykCS;
  12440. })();
  12441. //
  12442. // CalGrayCS: Based on "PDF Reference, Sixth Ed", p.245
  12443. //
  12444. var CalGrayCS = (function CalGrayCSClosure() {
  12445. function CalGrayCS(whitePoint, blackPoint, gamma) {
  12446. this.name = 'CalGray';
  12447. this.numComps = 1;
  12448. this.defaultColor = new Float32Array([0]);
  12449. if (!whitePoint) {
  12450. error('WhitePoint missing - required for color space CalGray');
  12451. }
  12452. blackPoint = blackPoint || [0, 0, 0];
  12453. gamma = gamma || 1;
  12454. // Translate arguments to spec variables.
  12455. this.XW = whitePoint[0];
  12456. this.YW = whitePoint[1];
  12457. this.ZW = whitePoint[2];
  12458. this.XB = blackPoint[0];
  12459. this.YB = blackPoint[1];
  12460. this.ZB = blackPoint[2];
  12461. this.G = gamma;
  12462. // Validate variables as per spec.
  12463. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  12464. error('Invalid WhitePoint components for ' + this.name +
  12465. ', no fallback available');
  12466. }
  12467. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  12468. info('Invalid BlackPoint for ' + this.name + ', falling back to default');
  12469. this.XB = this.YB = this.ZB = 0;
  12470. }
  12471. if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
  12472. warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB +
  12473. ', ZB: ' + this.ZB + ', only default values are supported.');
  12474. }
  12475. if (this.G < 1) {
  12476. info('Invalid Gamma: ' + this.G + ' for ' + this.name +
  12477. ', falling back to default');
  12478. this.G = 1;
  12479. }
  12480. }
  12481. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  12482. // A represents a gray component of a calibrated gray space.
  12483. // A <---> AG in the spec
  12484. var A = src[srcOffset] * scale;
  12485. var AG = Math.pow(A, cs.G);
  12486. // Computes L as per spec. ( = cs.YW * AG )
  12487. // Except if other than default BlackPoint values are used.
  12488. var L = cs.YW * AG;
  12489. // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4.
  12490. // Convert values to rgb range [0, 255].
  12491. var val = Math.max(295.8 * Math.pow(L, 0.333333333333333333) - 40.8, 0) | 0;
  12492. dest[destOffset] = val;
  12493. dest[destOffset + 1] = val;
  12494. dest[destOffset + 2] = val;
  12495. }
  12496. CalGrayCS.prototype = {
  12497. getRgb: ColorSpace.prototype.getRgb,
  12498. getRgbItem: function CalGrayCS_getRgbItem(src, srcOffset,
  12499. dest, destOffset) {
  12500. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  12501. },
  12502. getRgbBuffer: function CalGrayCS_getRgbBuffer(src, srcOffset, count,
  12503. dest, destOffset, bits,
  12504. alpha01) {
  12505. var scale = 1 / ((1 << bits) - 1);
  12506. for (var i = 0; i < count; ++i) {
  12507. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  12508. srcOffset += 1;
  12509. destOffset += 3 + alpha01;
  12510. }
  12511. },
  12512. getOutputLength: function CalGrayCS_getOutputLength(inputLength, alpha01) {
  12513. return inputLength * (3 + alpha01);
  12514. },
  12515. isPassthrough: ColorSpace.prototype.isPassthrough,
  12516. fillRgb: ColorSpace.prototype.fillRgb,
  12517. isDefaultDecode: function CalGrayCS_isDefaultDecode(decodeMap) {
  12518. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12519. },
  12520. usesZeroToOneRange: true
  12521. };
  12522. return CalGrayCS;
  12523. })();
  12524. //
  12525. // CalRGBCS: Based on "PDF Reference, Sixth Ed", p.247
  12526. //
  12527. var CalRGBCS = (function CalRGBCSClosure() {
  12528. // See http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html for these
  12529. // matrices.
  12530. var BRADFORD_SCALE_MATRIX = new Float32Array([
  12531. 0.8951, 0.2664, -0.1614,
  12532. -0.7502, 1.7135, 0.0367,
  12533. 0.0389, -0.0685, 1.0296]);
  12534. var BRADFORD_SCALE_INVERSE_MATRIX = new Float32Array([
  12535. 0.9869929, -0.1470543, 0.1599627,
  12536. 0.4323053, 0.5183603, 0.0492912,
  12537. -0.0085287, 0.0400428, 0.9684867]);
  12538. // See http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html.
  12539. var SRGB_D65_XYZ_TO_RGB_MATRIX = new Float32Array([
  12540. 3.2404542, -1.5371385, -0.4985314,
  12541. -0.9692660, 1.8760108, 0.0415560,
  12542. 0.0556434, -0.2040259, 1.0572252]);
  12543. var FLAT_WHITEPOINT_MATRIX = new Float32Array([1, 1, 1]);
  12544. var tempNormalizeMatrix = new Float32Array(3);
  12545. var tempConvertMatrix1 = new Float32Array(3);
  12546. var tempConvertMatrix2 = new Float32Array(3);
  12547. var DECODE_L_CONSTANT = Math.pow(((8 + 16) / 116), 3) / 8.0;
  12548. function CalRGBCS(whitePoint, blackPoint, gamma, matrix) {
  12549. this.name = 'CalRGB';
  12550. this.numComps = 3;
  12551. this.defaultColor = new Float32Array(3);
  12552. if (!whitePoint) {
  12553. error('WhitePoint missing - required for color space CalRGB');
  12554. }
  12555. blackPoint = blackPoint || new Float32Array(3);
  12556. gamma = gamma || new Float32Array([1, 1, 1]);
  12557. matrix = matrix || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  12558. // Translate arguments to spec variables.
  12559. var XW = whitePoint[0];
  12560. var YW = whitePoint[1];
  12561. var ZW = whitePoint[2];
  12562. this.whitePoint = whitePoint;
  12563. var XB = blackPoint[0];
  12564. var YB = blackPoint[1];
  12565. var ZB = blackPoint[2];
  12566. this.blackPoint = blackPoint;
  12567. this.GR = gamma[0];
  12568. this.GG = gamma[1];
  12569. this.GB = gamma[2];
  12570. this.MXA = matrix[0];
  12571. this.MYA = matrix[1];
  12572. this.MZA = matrix[2];
  12573. this.MXB = matrix[3];
  12574. this.MYB = matrix[4];
  12575. this.MZB = matrix[5];
  12576. this.MXC = matrix[6];
  12577. this.MYC = matrix[7];
  12578. this.MZC = matrix[8];
  12579. // Validate variables as per spec.
  12580. if (XW < 0 || ZW < 0 || YW !== 1) {
  12581. error('Invalid WhitePoint components for ' + this.name +
  12582. ', no fallback available');
  12583. }
  12584. if (XB < 0 || YB < 0 || ZB < 0) {
  12585. info('Invalid BlackPoint for ' + this.name + ' [' + XB + ', ' + YB +
  12586. ', ' + ZB + '], falling back to default');
  12587. this.blackPoint = new Float32Array(3);
  12588. }
  12589. if (this.GR < 0 || this.GG < 0 || this.GB < 0) {
  12590. info('Invalid Gamma [' + this.GR + ', ' + this.GG + ', ' + this.GB +
  12591. '] for ' + this.name + ', falling back to default');
  12592. this.GR = this.GG = this.GB = 1;
  12593. }
  12594. if (this.MXA < 0 || this.MYA < 0 || this.MZA < 0 ||
  12595. this.MXB < 0 || this.MYB < 0 || this.MZB < 0 ||
  12596. this.MXC < 0 || this.MYC < 0 || this.MZC < 0) {
  12597. info('Invalid Matrix for ' + this.name + ' [' +
  12598. this.MXA + ', ' + this.MYA + ', ' + this.MZA +
  12599. this.MXB + ', ' + this.MYB + ', ' + this.MZB +
  12600. this.MXC + ', ' + this.MYC + ', ' + this.MZC +
  12601. '], falling back to default');
  12602. this.MXA = this.MYB = this.MZC = 1;
  12603. this.MXB = this.MYA = this.MZA = this.MXC = this.MYC = this.MZB = 0;
  12604. }
  12605. }
  12606. function matrixProduct(a, b, result) {
  12607. result[0] = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  12608. result[1] = a[3] * b[0] + a[4] * b[1] + a[5] * b[2];
  12609. result[2] = a[6] * b[0] + a[7] * b[1] + a[8] * b[2];
  12610. }
  12611. function convertToFlat(sourceWhitePoint, LMS, result) {
  12612. result[0] = LMS[0] * 1 / sourceWhitePoint[0];
  12613. result[1] = LMS[1] * 1 / sourceWhitePoint[1];
  12614. result[2] = LMS[2] * 1 / sourceWhitePoint[2];
  12615. }
  12616. function convertToD65(sourceWhitePoint, LMS, result) {
  12617. var D65X = 0.95047;
  12618. var D65Y = 1;
  12619. var D65Z = 1.08883;
  12620. result[0] = LMS[0] * D65X / sourceWhitePoint[0];
  12621. result[1] = LMS[1] * D65Y / sourceWhitePoint[1];
  12622. result[2] = LMS[2] * D65Z / sourceWhitePoint[2];
  12623. }
  12624. function sRGBTransferFunction(color) {
  12625. // See http://en.wikipedia.org/wiki/SRGB.
  12626. if (color <= 0.0031308){
  12627. return adjustToRange(0, 1, 12.92 * color);
  12628. }
  12629. return adjustToRange(0, 1, (1 + 0.055) * Math.pow(color, 1 / 2.4) - 0.055);
  12630. }
  12631. function adjustToRange(min, max, value) {
  12632. return Math.max(min, Math.min(max, value));
  12633. }
  12634. function decodeL(L) {
  12635. if (L < 0) {
  12636. return -decodeL(-L);
  12637. }
  12638. if (L > 8.0) {
  12639. return Math.pow(((L + 16) / 116), 3);
  12640. }
  12641. return L * DECODE_L_CONSTANT;
  12642. }
  12643. function compensateBlackPoint(sourceBlackPoint, XYZ_Flat, result) {
  12644. // In case the blackPoint is already the default blackPoint then there is
  12645. // no need to do compensation.
  12646. if (sourceBlackPoint[0] === 0 &&
  12647. sourceBlackPoint[1] === 0 &&
  12648. sourceBlackPoint[2] === 0) {
  12649. result[0] = XYZ_Flat[0];
  12650. result[1] = XYZ_Flat[1];
  12651. result[2] = XYZ_Flat[2];
  12652. return;
  12653. }
  12654. // For the blackPoint calculation details, please see
  12655. // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
  12656. // AdobeBPC.pdf.
  12657. // The destination blackPoint is the default blackPoint [0, 0, 0].
  12658. var zeroDecodeL = decodeL(0);
  12659. var X_DST = zeroDecodeL;
  12660. var X_SRC = decodeL(sourceBlackPoint[0]);
  12661. var Y_DST = zeroDecodeL;
  12662. var Y_SRC = decodeL(sourceBlackPoint[1]);
  12663. var Z_DST = zeroDecodeL;
  12664. var Z_SRC = decodeL(sourceBlackPoint[2]);
  12665. var X_Scale = (1 - X_DST) / (1 - X_SRC);
  12666. var X_Offset = 1 - X_Scale;
  12667. var Y_Scale = (1 - Y_DST) / (1 - Y_SRC);
  12668. var Y_Offset = 1 - Y_Scale;
  12669. var Z_Scale = (1 - Z_DST) / (1 - Z_SRC);
  12670. var Z_Offset = 1 - Z_Scale;
  12671. result[0] = XYZ_Flat[0] * X_Scale + X_Offset;
  12672. result[1] = XYZ_Flat[1] * Y_Scale + Y_Offset;
  12673. result[2] = XYZ_Flat[2] * Z_Scale + Z_Offset;
  12674. }
  12675. function normalizeWhitePointToFlat(sourceWhitePoint, XYZ_In, result) {
  12676. // In case the whitePoint is already flat then there is no need to do
  12677. // normalization.
  12678. if (sourceWhitePoint[0] === 1 && sourceWhitePoint[2] === 1) {
  12679. result[0] = XYZ_In[0];
  12680. result[1] = XYZ_In[1];
  12681. result[2] = XYZ_In[2];
  12682. return;
  12683. }
  12684. var LMS = result;
  12685. matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
  12686. var LMS_Flat = tempNormalizeMatrix;
  12687. convertToFlat(sourceWhitePoint, LMS, LMS_Flat);
  12688. matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_Flat, result);
  12689. }
  12690. function normalizeWhitePointToD65(sourceWhitePoint, XYZ_In, result) {
  12691. var LMS = result;
  12692. matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
  12693. var LMS_D65 = tempNormalizeMatrix;
  12694. convertToD65(sourceWhitePoint, LMS, LMS_D65);
  12695. matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_D65, result);
  12696. }
  12697. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  12698. // A, B and C represent a red, green and blue components of a calibrated
  12699. // rgb space.
  12700. var A = adjustToRange(0, 1, src[srcOffset] * scale);
  12701. var B = adjustToRange(0, 1, src[srcOffset + 1] * scale);
  12702. var C = adjustToRange(0, 1, src[srcOffset + 2] * scale);
  12703. // A <---> AGR in the spec
  12704. // B <---> BGG in the spec
  12705. // C <---> CGB in the spec
  12706. var AGR = Math.pow(A, cs.GR);
  12707. var BGG = Math.pow(B, cs.GG);
  12708. var CGB = Math.pow(C, cs.GB);
  12709. // Computes intermediate variables L, M, N as per spec.
  12710. // To decode X, Y, Z values map L, M, N directly to them.
  12711. var X = cs.MXA * AGR + cs.MXB * BGG + cs.MXC * CGB;
  12712. var Y = cs.MYA * AGR + cs.MYB * BGG + cs.MYC * CGB;
  12713. var Z = cs.MZA * AGR + cs.MZB * BGG + cs.MZC * CGB;
  12714. // The following calculations are based on this document:
  12715. // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
  12716. // AdobeBPC.pdf.
  12717. var XYZ = tempConvertMatrix1;
  12718. XYZ[0] = X;
  12719. XYZ[1] = Y;
  12720. XYZ[2] = Z;
  12721. var XYZ_Flat = tempConvertMatrix2;
  12722. normalizeWhitePointToFlat(cs.whitePoint, XYZ, XYZ_Flat);
  12723. var XYZ_Black = tempConvertMatrix1;
  12724. compensateBlackPoint(cs.blackPoint, XYZ_Flat, XYZ_Black);
  12725. var XYZ_D65 = tempConvertMatrix2;
  12726. normalizeWhitePointToD65(FLAT_WHITEPOINT_MATRIX, XYZ_Black, XYZ_D65);
  12727. var SRGB = tempConvertMatrix1;
  12728. matrixProduct(SRGB_D65_XYZ_TO_RGB_MATRIX, XYZ_D65, SRGB);
  12729. var sR = sRGBTransferFunction(SRGB[0]);
  12730. var sG = sRGBTransferFunction(SRGB[1]);
  12731. var sB = sRGBTransferFunction(SRGB[2]);
  12732. // Convert the values to rgb range [0, 255].
  12733. dest[destOffset] = Math.round(sR * 255);
  12734. dest[destOffset + 1] = Math.round(sG * 255);
  12735. dest[destOffset + 2] = Math.round(sB * 255);
  12736. }
  12737. CalRGBCS.prototype = {
  12738. getRgb: function CalRGBCS_getRgb(src, srcOffset) {
  12739. var rgb = new Uint8Array(3);
  12740. this.getRgbItem(src, srcOffset, rgb, 0);
  12741. return rgb;
  12742. },
  12743. getRgbItem: function CalRGBCS_getRgbItem(src, srcOffset,
  12744. dest, destOffset) {
  12745. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  12746. },
  12747. getRgbBuffer: function CalRGBCS_getRgbBuffer(src, srcOffset, count,
  12748. dest, destOffset, bits,
  12749. alpha01) {
  12750. var scale = 1 / ((1 << bits) - 1);
  12751. for (var i = 0; i < count; ++i) {
  12752. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  12753. srcOffset += 3;
  12754. destOffset += 3 + alpha01;
  12755. }
  12756. },
  12757. getOutputLength: function CalRGBCS_getOutputLength(inputLength, alpha01) {
  12758. return (inputLength * (3 + alpha01) / 3) | 0;
  12759. },
  12760. isPassthrough: ColorSpace.prototype.isPassthrough,
  12761. fillRgb: ColorSpace.prototype.fillRgb,
  12762. isDefaultDecode: function CalRGBCS_isDefaultDecode(decodeMap) {
  12763. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12764. },
  12765. usesZeroToOneRange: true
  12766. };
  12767. return CalRGBCS;
  12768. })();
  12769. //
  12770. // LabCS: Based on "PDF Reference, Sixth Ed", p.250
  12771. //
  12772. var LabCS = (function LabCSClosure() {
  12773. function LabCS(whitePoint, blackPoint, range) {
  12774. this.name = 'Lab';
  12775. this.numComps = 3;
  12776. this.defaultColor = new Float32Array([0, 0, 0]);
  12777. if (!whitePoint) {
  12778. error('WhitePoint missing - required for color space Lab');
  12779. }
  12780. blackPoint = blackPoint || [0, 0, 0];
  12781. range = range || [-100, 100, -100, 100];
  12782. // Translate args to spec variables
  12783. this.XW = whitePoint[0];
  12784. this.YW = whitePoint[1];
  12785. this.ZW = whitePoint[2];
  12786. this.amin = range[0];
  12787. this.amax = range[1];
  12788. this.bmin = range[2];
  12789. this.bmax = range[3];
  12790. // These are here just for completeness - the spec doesn't offer any
  12791. // formulas that use BlackPoint in Lab
  12792. this.XB = blackPoint[0];
  12793. this.YB = blackPoint[1];
  12794. this.ZB = blackPoint[2];
  12795. // Validate vars as per spec
  12796. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  12797. error('Invalid WhitePoint components, no fallback available');
  12798. }
  12799. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  12800. info('Invalid BlackPoint, falling back to default');
  12801. this.XB = this.YB = this.ZB = 0;
  12802. }
  12803. if (this.amin > this.amax || this.bmin > this.bmax) {
  12804. info('Invalid Range, falling back to defaults');
  12805. this.amin = -100;
  12806. this.amax = 100;
  12807. this.bmin = -100;
  12808. this.bmax = 100;
  12809. }
  12810. }
  12811. // Function g(x) from spec
  12812. function fn_g(x) {
  12813. if (x >= 6 / 29) {
  12814. return x * x * x;
  12815. } else {
  12816. return (108 / 841) * (x - 4 / 29);
  12817. }
  12818. }
  12819. function decode(value, high1, low2, high2) {
  12820. return low2 + (value) * (high2 - low2) / (high1);
  12821. }
  12822. // If decoding is needed maxVal should be 2^bits per component - 1.
  12823. function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
  12824. // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]
  12825. // not the usual [0, 1]. If a command like setFillColor is used the src
  12826. // values will already be within the correct range. However, if we are
  12827. // converting an image we have to map the values to the correct range given
  12828. // above.
  12829. // Ls,as,bs <---> L*,a*,b* in the spec
  12830. var Ls = src[srcOffset];
  12831. var as = src[srcOffset + 1];
  12832. var bs = src[srcOffset + 2];
  12833. if (maxVal !== false) {
  12834. Ls = decode(Ls, maxVal, 0, 100);
  12835. as = decode(as, maxVal, cs.amin, cs.amax);
  12836. bs = decode(bs, maxVal, cs.bmin, cs.bmax);
  12837. }
  12838. // Adjust limits of 'as' and 'bs'
  12839. as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;
  12840. bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;
  12841. // Computes intermediate variables X,Y,Z as per spec
  12842. var M = (Ls + 16) / 116;
  12843. var L = M + (as / 500);
  12844. var N = M - (bs / 200);
  12845. var X = cs.XW * fn_g(L);
  12846. var Y = cs.YW * fn_g(M);
  12847. var Z = cs.ZW * fn_g(N);
  12848. var r, g, b;
  12849. // Using different conversions for D50 and D65 white points,
  12850. // per http://www.color.org/srgb.pdf
  12851. if (cs.ZW < 1) {
  12852. // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)
  12853. r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;
  12854. g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;
  12855. b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;
  12856. } else {
  12857. // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)
  12858. r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
  12859. g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
  12860. b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;
  12861. }
  12862. // clamp color values to [0,1] range then convert to [0,255] range.
  12863. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0;
  12864. dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0;
  12865. dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0;
  12866. }
  12867. LabCS.prototype = {
  12868. getRgb: ColorSpace.prototype.getRgb,
  12869. getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) {
  12870. convertToRgb(this, src, srcOffset, false, dest, destOffset);
  12871. },
  12872. getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count,
  12873. dest, destOffset, bits,
  12874. alpha01) {
  12875. var maxVal = (1 << bits) - 1;
  12876. for (var i = 0; i < count; i++) {
  12877. convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);
  12878. srcOffset += 3;
  12879. destOffset += 3 + alpha01;
  12880. }
  12881. },
  12882. getOutputLength: function LabCS_getOutputLength(inputLength, alpha01) {
  12883. return (inputLength * (3 + alpha01) / 3) | 0;
  12884. },
  12885. isPassthrough: ColorSpace.prototype.isPassthrough,
  12886. fillRgb: ColorSpace.prototype.fillRgb,
  12887. isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {
  12888. // XXX: Decoding is handled with the lab conversion because of the strange
  12889. // ranges that are used.
  12890. return true;
  12891. },
  12892. usesZeroToOneRange: false
  12893. };
  12894. return LabCS;
  12895. })();
  12896. var ARCFourCipher = (function ARCFourCipherClosure() {
  12897. function ARCFourCipher(key) {
  12898. this.a = 0;
  12899. this.b = 0;
  12900. var s = new Uint8Array(256);
  12901. var i, j = 0, tmp, keyLength = key.length;
  12902. for (i = 0; i < 256; ++i) {
  12903. s[i] = i;
  12904. }
  12905. for (i = 0; i < 256; ++i) {
  12906. tmp = s[i];
  12907. j = (j + tmp + key[i % keyLength]) & 0xFF;
  12908. s[i] = s[j];
  12909. s[j] = tmp;
  12910. }
  12911. this.s = s;
  12912. }
  12913. ARCFourCipher.prototype = {
  12914. encryptBlock: function ARCFourCipher_encryptBlock(data) {
  12915. var i, n = data.length, tmp, tmp2;
  12916. var a = this.a, b = this.b, s = this.s;
  12917. var output = new Uint8Array(n);
  12918. for (i = 0; i < n; ++i) {
  12919. a = (a + 1) & 0xFF;
  12920. tmp = s[a];
  12921. b = (b + tmp) & 0xFF;
  12922. tmp2 = s[b];
  12923. s[a] = tmp2;
  12924. s[b] = tmp;
  12925. output[i] = data[i] ^ s[(tmp + tmp2) & 0xFF];
  12926. }
  12927. this.a = a;
  12928. this.b = b;
  12929. return output;
  12930. }
  12931. };
  12932. ARCFourCipher.prototype.decryptBlock = ARCFourCipher.prototype.encryptBlock;
  12933. return ARCFourCipher;
  12934. })();
  12935. var calculateMD5 = (function calculateMD5Closure() {
  12936. var r = new Uint8Array([
  12937. 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  12938. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  12939. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  12940. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
  12941. var k = new Int32Array([
  12942. -680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426,
  12943. -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162,
  12944. 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632,
  12945. 643717713, -373897302, -701558691, 38016083, -660478335, -405537848,
  12946. 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784,
  12947. 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556,
  12948. -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222,
  12949. -722521979, 76029189, -640364487, -421815835, 530742520, -995338651,
  12950. -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606,
  12951. -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649,
  12952. -145523070, -1120210379, 718787259, -343485551]);
  12953. function hash(data, offset, length) {
  12954. var h0 = 1732584193, h1 = -271733879, h2 = -1732584194, h3 = 271733878;
  12955. // pre-processing
  12956. var paddedLength = (length + 72) & ~63; // data + 9 extra bytes
  12957. var padded = new Uint8Array(paddedLength);
  12958. var i, j, n;
  12959. for (i = 0; i < length; ++i) {
  12960. padded[i] = data[offset++];
  12961. }
  12962. padded[i++] = 0x80;
  12963. n = paddedLength - 8;
  12964. while (i < n) {
  12965. padded[i++] = 0;
  12966. }
  12967. padded[i++] = (length << 3) & 0xFF;
  12968. padded[i++] = (length >> 5) & 0xFF;
  12969. padded[i++] = (length >> 13) & 0xFF;
  12970. padded[i++] = (length >> 21) & 0xFF;
  12971. padded[i++] = (length >>> 29) & 0xFF;
  12972. padded[i++] = 0;
  12973. padded[i++] = 0;
  12974. padded[i++] = 0;
  12975. var w = new Int32Array(16);
  12976. for (i = 0; i < paddedLength;) {
  12977. for (j = 0; j < 16; ++j, i += 4) {
  12978. w[j] = (padded[i] | (padded[i + 1] << 8) |
  12979. (padded[i + 2] << 16) | (padded[i + 3] << 24));
  12980. }
  12981. var a = h0, b = h1, c = h2, d = h3, f, g;
  12982. for (j = 0; j < 64; ++j) {
  12983. if (j < 16) {
  12984. f = (b & c) | ((~b) & d);
  12985. g = j;
  12986. } else if (j < 32) {
  12987. f = (d & b) | ((~d) & c);
  12988. g = (5 * j + 1) & 15;
  12989. } else if (j < 48) {
  12990. f = b ^ c ^ d;
  12991. g = (3 * j + 5) & 15;
  12992. } else {
  12993. f = c ^ (b | (~d));
  12994. g = (7 * j) & 15;
  12995. }
  12996. var tmp = d, rotateArg = (a + f + k[j] + w[g]) | 0, rotate = r[j];
  12997. d = c;
  12998. c = b;
  12999. b = (b + ((rotateArg << rotate) | (rotateArg >>> (32 - rotate)))) | 0;
  13000. a = tmp;
  13001. }
  13002. h0 = (h0 + a) | 0;
  13003. h1 = (h1 + b) | 0;
  13004. h2 = (h2 + c) | 0;
  13005. h3 = (h3 + d) | 0;
  13006. }
  13007. return new Uint8Array([
  13008. h0 & 0xFF, (h0 >> 8) & 0xFF, (h0 >> 16) & 0xFF, (h0 >>> 24) & 0xFF,
  13009. h1 & 0xFF, (h1 >> 8) & 0xFF, (h1 >> 16) & 0xFF, (h1 >>> 24) & 0xFF,
  13010. h2 & 0xFF, (h2 >> 8) & 0xFF, (h2 >> 16) & 0xFF, (h2 >>> 24) & 0xFF,
  13011. h3 & 0xFF, (h3 >> 8) & 0xFF, (h3 >> 16) & 0xFF, (h3 >>> 24) & 0xFF
  13012. ]);
  13013. }
  13014. return hash;
  13015. })();
  13016. var Word64 = (function Word64Closure() {
  13017. function Word64(highInteger, lowInteger) {
  13018. this.high = highInteger | 0;
  13019. this.low = lowInteger | 0;
  13020. }
  13021. Word64.prototype = {
  13022. and: function Word64_and(word) {
  13023. this.high &= word.high;
  13024. this.low &= word.low;
  13025. },
  13026. xor: function Word64_xor(word) {
  13027. this.high ^= word.high;
  13028. this.low ^= word.low;
  13029. },
  13030. or: function Word64_or(word) {
  13031. this.high |= word.high;
  13032. this.low |= word.low;
  13033. },
  13034. shiftRight: function Word64_shiftRight(places) {
  13035. if (places >= 32) {
  13036. this.low = (this.high >>> (places - 32)) | 0;
  13037. this.high = 0;
  13038. } else {
  13039. this.low = (this.low >>> places) | (this.high << (32 - places));
  13040. this.high = (this.high >>> places) | 0;
  13041. }
  13042. },
  13043. shiftLeft: function Word64_shiftLeft(places) {
  13044. if (places >= 32) {
  13045. this.high = this.low << (places - 32);
  13046. this.low = 0;
  13047. } else {
  13048. this.high = (this.high << places) | (this.low >>> (32 - places));
  13049. this.low = this.low << places;
  13050. }
  13051. },
  13052. rotateRight: function Word64_rotateRight(places) {
  13053. var low, high;
  13054. if (places & 32) {
  13055. high = this.low;
  13056. low = this.high;
  13057. } else {
  13058. low = this.low;
  13059. high = this.high;
  13060. }
  13061. places &= 31;
  13062. this.low = (low >>> places) | (high << (32 - places));
  13063. this.high = (high >>> places) | (low << (32 - places));
  13064. },
  13065. not: function Word64_not() {
  13066. this.high = ~this.high;
  13067. this.low = ~this.low;
  13068. },
  13069. add: function Word64_add(word) {
  13070. var lowAdd = (this.low >>> 0) + (word.low >>> 0);
  13071. var highAdd = (this.high >>> 0) + (word.high >>> 0);
  13072. if (lowAdd > 0xFFFFFFFF) {
  13073. highAdd += 1;
  13074. }
  13075. this.low = lowAdd | 0;
  13076. this.high = highAdd | 0;
  13077. },
  13078. copyTo: function Word64_copyTo(bytes, offset) {
  13079. bytes[offset] = (this.high >>> 24) & 0xFF;
  13080. bytes[offset + 1] = (this.high >> 16) & 0xFF;
  13081. bytes[offset + 2] = (this.high >> 8) & 0xFF;
  13082. bytes[offset + 3] = this.high & 0xFF;
  13083. bytes[offset + 4] = (this.low >>> 24) & 0xFF;
  13084. bytes[offset + 5] = (this.low >> 16) & 0xFF;
  13085. bytes[offset + 6] = (this.low >> 8) & 0xFF;
  13086. bytes[offset + 7] = this.low & 0xFF;
  13087. },
  13088. assign: function Word64_assign(word) {
  13089. this.high = word.high;
  13090. this.low = word.low;
  13091. }
  13092. };
  13093. return Word64;
  13094. })();
  13095. var calculateSHA256 = (function calculateSHA256Closure() {
  13096. function rotr(x, n) {
  13097. return (x >>> n) | (x << 32 - n);
  13098. }
  13099. function ch(x, y, z) {
  13100. return (x & y) ^ (~x & z);
  13101. }
  13102. function maj(x, y, z) {
  13103. return (x & y) ^ (x & z) ^ (y & z);
  13104. }
  13105. function sigma(x) {
  13106. return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
  13107. }
  13108. function sigmaPrime(x) {
  13109. return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
  13110. }
  13111. function littleSigma(x) {
  13112. return rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3;
  13113. }
  13114. function littleSigmaPrime(x) {
  13115. return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10;
  13116. }
  13117. var k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  13118. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  13119. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  13120. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  13121. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  13122. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  13123. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  13124. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  13125. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  13126. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  13127. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  13128. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  13129. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  13130. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  13131. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  13132. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
  13133. function hash(data, offset, length) {
  13134. // initial hash values
  13135. var h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372,
  13136. h3 = 0xa54ff53a, h4 = 0x510e527f, h5 = 0x9b05688c,
  13137. h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
  13138. // pre-processing
  13139. var paddedLength = Math.ceil((length + 9) / 64) * 64;
  13140. var padded = new Uint8Array(paddedLength);
  13141. var i, j, n;
  13142. for (i = 0; i < length; ++i) {
  13143. padded[i] = data[offset++];
  13144. }
  13145. padded[i++] = 0x80;
  13146. n = paddedLength - 8;
  13147. while (i < n) {
  13148. padded[i++] = 0;
  13149. }
  13150. padded[i++] = 0;
  13151. padded[i++] = 0;
  13152. padded[i++] = 0;
  13153. padded[i++] = (length >>> 29) & 0xFF;
  13154. padded[i++] = (length >> 21) & 0xFF;
  13155. padded[i++] = (length >> 13) & 0xFF;
  13156. padded[i++] = (length >> 5) & 0xFF;
  13157. padded[i++] = (length << 3) & 0xFF;
  13158. var w = new Uint32Array(64);
  13159. // for each 512 bit block
  13160. for (i = 0; i < paddedLength;) {
  13161. for (j = 0; j < 16; ++j) {
  13162. w[j] = (padded[i] << 24 | (padded[i + 1] << 16) |
  13163. (padded[i + 2] << 8) | (padded[i + 3]));
  13164. i += 4;
  13165. }
  13166. for (j = 16; j < 64; ++j) {
  13167. w[j] = littleSigmaPrime(w[j - 2]) + w[j - 7] +
  13168. littleSigma(w[j - 15]) + w[j - 16] | 0;
  13169. }
  13170. var a = h0, b = h1, c = h2, d = h3, e = h4,
  13171. f = h5, g = h6, h = h7, t1, t2;
  13172. for (j = 0; j < 64; ++j) {
  13173. t1 = h + sigmaPrime(e) + ch(e, f, g) + k[j] + w[j];
  13174. t2 = sigma(a) + maj(a, b, c);
  13175. h = g;
  13176. g = f;
  13177. f = e;
  13178. e = (d + t1) | 0;
  13179. d = c;
  13180. c = b;
  13181. b = a;
  13182. a = (t1 + t2) | 0;
  13183. }
  13184. h0 = (h0 + a) | 0;
  13185. h1 = (h1 + b) | 0;
  13186. h2 = (h2 + c) | 0;
  13187. h3 = (h3 + d) | 0;
  13188. h4 = (h4 + e) | 0;
  13189. h5 = (h5 + f) | 0;
  13190. h6 = (h6 + g) | 0;
  13191. h7 = (h7 + h) | 0;
  13192. }
  13193. return new Uint8Array([
  13194. (h0 >> 24) & 0xFF, (h0 >> 16) & 0xFF, (h0 >> 8) & 0xFF, (h0) & 0xFF,
  13195. (h1 >> 24) & 0xFF, (h1 >> 16) & 0xFF, (h1 >> 8) & 0xFF, (h1) & 0xFF,
  13196. (h2 >> 24) & 0xFF, (h2 >> 16) & 0xFF, (h2 >> 8) & 0xFF, (h2) & 0xFF,
  13197. (h3 >> 24) & 0xFF, (h3 >> 16) & 0xFF, (h3 >> 8) & 0xFF, (h3) & 0xFF,
  13198. (h4 >> 24) & 0xFF, (h4 >> 16) & 0xFF, (h4 >> 8) & 0xFF, (h4) & 0xFF,
  13199. (h5 >> 24) & 0xFF, (h5 >> 16) & 0xFF, (h5 >> 8) & 0xFF, (h5) & 0xFF,
  13200. (h6 >> 24) & 0xFF, (h6 >> 16) & 0xFF, (h6 >> 8) & 0xFF, (h6) & 0xFF,
  13201. (h7 >> 24) & 0xFF, (h7 >> 16) & 0xFF, (h7 >> 8) & 0xFF, (h7) & 0xFF
  13202. ]);
  13203. }
  13204. return hash;
  13205. })();
  13206. var calculateSHA512 = (function calculateSHA512Closure() {
  13207. function ch(result, x, y, z, tmp) {
  13208. result.assign(x);
  13209. result.and(y);
  13210. tmp.assign(x);
  13211. tmp.not();
  13212. tmp.and(z);
  13213. result.xor(tmp);
  13214. }
  13215. function maj(result, x, y, z, tmp) {
  13216. result.assign(x);
  13217. result.and(y);
  13218. tmp.assign(x);
  13219. tmp.and(z);
  13220. result.xor(tmp);
  13221. tmp.assign(y);
  13222. tmp.and(z);
  13223. result.xor(tmp);
  13224. }
  13225. function sigma(result, x, tmp) {
  13226. result.assign(x);
  13227. result.rotateRight(28);
  13228. tmp.assign(x);
  13229. tmp.rotateRight(34);
  13230. result.xor(tmp);
  13231. tmp.assign(x);
  13232. tmp.rotateRight(39);
  13233. result.xor(tmp);
  13234. }
  13235. function sigmaPrime(result, x, tmp) {
  13236. result.assign(x);
  13237. result.rotateRight(14);
  13238. tmp.assign(x);
  13239. tmp.rotateRight(18);
  13240. result.xor(tmp);
  13241. tmp.assign(x);
  13242. tmp.rotateRight(41);
  13243. result.xor(tmp);
  13244. }
  13245. function littleSigma(result, x, tmp) {
  13246. result.assign(x);
  13247. result.rotateRight(1);
  13248. tmp.assign(x);
  13249. tmp.rotateRight(8);
  13250. result.xor(tmp);
  13251. tmp.assign(x);
  13252. tmp.shiftRight(7);
  13253. result.xor(tmp);
  13254. }
  13255. function littleSigmaPrime(result, x, tmp) {
  13256. result.assign(x);
  13257. result.rotateRight(19);
  13258. tmp.assign(x);
  13259. tmp.rotateRight(61);
  13260. result.xor(tmp);
  13261. tmp.assign(x);
  13262. tmp.shiftRight(6);
  13263. result.xor(tmp);
  13264. }
  13265. var k = [
  13266. new Word64(0x428a2f98, 0xd728ae22), new Word64(0x71374491, 0x23ef65cd),
  13267. new Word64(0xb5c0fbcf, 0xec4d3b2f), new Word64(0xe9b5dba5, 0x8189dbbc),
  13268. new Word64(0x3956c25b, 0xf348b538), new Word64(0x59f111f1, 0xb605d019),
  13269. new Word64(0x923f82a4, 0xaf194f9b), new Word64(0xab1c5ed5, 0xda6d8118),
  13270. new Word64(0xd807aa98, 0xa3030242), new Word64(0x12835b01, 0x45706fbe),
  13271. new Word64(0x243185be, 0x4ee4b28c), new Word64(0x550c7dc3, 0xd5ffb4e2),
  13272. new Word64(0x72be5d74, 0xf27b896f), new Word64(0x80deb1fe, 0x3b1696b1),
  13273. new Word64(0x9bdc06a7, 0x25c71235), new Word64(0xc19bf174, 0xcf692694),
  13274. new Word64(0xe49b69c1, 0x9ef14ad2), new Word64(0xefbe4786, 0x384f25e3),
  13275. new Word64(0x0fc19dc6, 0x8b8cd5b5), new Word64(0x240ca1cc, 0x77ac9c65),
  13276. new Word64(0x2de92c6f, 0x592b0275), new Word64(0x4a7484aa, 0x6ea6e483),
  13277. new Word64(0x5cb0a9dc, 0xbd41fbd4), new Word64(0x76f988da, 0x831153b5),
  13278. new Word64(0x983e5152, 0xee66dfab), new Word64(0xa831c66d, 0x2db43210),
  13279. new Word64(0xb00327c8, 0x98fb213f), new Word64(0xbf597fc7, 0xbeef0ee4),
  13280. new Word64(0xc6e00bf3, 0x3da88fc2), new Word64(0xd5a79147, 0x930aa725),
  13281. new Word64(0x06ca6351, 0xe003826f), new Word64(0x14292967, 0x0a0e6e70),
  13282. new Word64(0x27b70a85, 0x46d22ffc), new Word64(0x2e1b2138, 0x5c26c926),
  13283. new Word64(0x4d2c6dfc, 0x5ac42aed), new Word64(0x53380d13, 0x9d95b3df),
  13284. new Word64(0x650a7354, 0x8baf63de), new Word64(0x766a0abb, 0x3c77b2a8),
  13285. new Word64(0x81c2c92e, 0x47edaee6), new Word64(0x92722c85, 0x1482353b),
  13286. new Word64(0xa2bfe8a1, 0x4cf10364), new Word64(0xa81a664b, 0xbc423001),
  13287. new Word64(0xc24b8b70, 0xd0f89791), new Word64(0xc76c51a3, 0x0654be30),
  13288. new Word64(0xd192e819, 0xd6ef5218), new Word64(0xd6990624, 0x5565a910),
  13289. new Word64(0xf40e3585, 0x5771202a), new Word64(0x106aa070, 0x32bbd1b8),
  13290. new Word64(0x19a4c116, 0xb8d2d0c8), new Word64(0x1e376c08, 0x5141ab53),
  13291. new Word64(0x2748774c, 0xdf8eeb99), new Word64(0x34b0bcb5, 0xe19b48a8),
  13292. new Word64(0x391c0cb3, 0xc5c95a63), new Word64(0x4ed8aa4a, 0xe3418acb),
  13293. new Word64(0x5b9cca4f, 0x7763e373), new Word64(0x682e6ff3, 0xd6b2b8a3),
  13294. new Word64(0x748f82ee, 0x5defb2fc), new Word64(0x78a5636f, 0x43172f60),
  13295. new Word64(0x84c87814, 0xa1f0ab72), new Word64(0x8cc70208, 0x1a6439ec),
  13296. new Word64(0x90befffa, 0x23631e28), new Word64(0xa4506ceb, 0xde82bde9),
  13297. new Word64(0xbef9a3f7, 0xb2c67915), new Word64(0xc67178f2, 0xe372532b),
  13298. new Word64(0xca273ece, 0xea26619c), new Word64(0xd186b8c7, 0x21c0c207),
  13299. new Word64(0xeada7dd6, 0xcde0eb1e), new Word64(0xf57d4f7f, 0xee6ed178),
  13300. new Word64(0x06f067aa, 0x72176fba), new Word64(0x0a637dc5, 0xa2c898a6),
  13301. new Word64(0x113f9804, 0xbef90dae), new Word64(0x1b710b35, 0x131c471b),
  13302. new Word64(0x28db77f5, 0x23047d84), new Word64(0x32caab7b, 0x40c72493),
  13303. new Word64(0x3c9ebe0a, 0x15c9bebc), new Word64(0x431d67c4, 0x9c100d4c),
  13304. new Word64(0x4cc5d4be, 0xcb3e42b6), new Word64(0x597f299c, 0xfc657e2a),
  13305. new Word64(0x5fcb6fab, 0x3ad6faec), new Word64(0x6c44198c, 0x4a475817)];
  13306. function hash(data, offset, length, mode384) {
  13307. mode384 = !!mode384;
  13308. // initial hash values
  13309. var h0, h1, h2, h3, h4, h5, h6, h7;
  13310. if (!mode384) {
  13311. h0 = new Word64(0x6a09e667, 0xf3bcc908);
  13312. h1 = new Word64(0xbb67ae85, 0x84caa73b);
  13313. h2 = new Word64(0x3c6ef372, 0xfe94f82b);
  13314. h3 = new Word64(0xa54ff53a, 0x5f1d36f1);
  13315. h4 = new Word64(0x510e527f, 0xade682d1);
  13316. h5 = new Word64(0x9b05688c, 0x2b3e6c1f);
  13317. h6 = new Word64(0x1f83d9ab, 0xfb41bd6b);
  13318. h7 = new Word64(0x5be0cd19, 0x137e2179);
  13319. }
  13320. else {
  13321. // SHA384 is exactly the same
  13322. // except with different starting values and a trimmed result
  13323. h0 = new Word64(0xcbbb9d5d, 0xc1059ed8);
  13324. h1 = new Word64(0x629a292a, 0x367cd507);
  13325. h2 = new Word64(0x9159015a, 0x3070dd17);
  13326. h3 = new Word64(0x152fecd8, 0xf70e5939);
  13327. h4 = new Word64(0x67332667, 0xffc00b31);
  13328. h5 = new Word64(0x8eb44a87, 0x68581511);
  13329. h6 = new Word64(0xdb0c2e0d, 0x64f98fa7);
  13330. h7 = new Word64(0x47b5481d, 0xbefa4fa4);
  13331. }
  13332. // pre-processing
  13333. var paddedLength = Math.ceil((length + 17) / 128) * 128;
  13334. var padded = new Uint8Array(paddedLength);
  13335. var i, j, n;
  13336. for (i = 0; i < length; ++i) {
  13337. padded[i] = data[offset++];
  13338. }
  13339. padded[i++] = 0x80;
  13340. n = paddedLength - 16;
  13341. while (i < n) {
  13342. padded[i++] = 0;
  13343. }
  13344. padded[i++] = 0;
  13345. padded[i++] = 0;
  13346. padded[i++] = 0;
  13347. padded[i++] = 0;
  13348. padded[i++] = 0;
  13349. padded[i++] = 0;
  13350. padded[i++] = 0;
  13351. padded[i++] = 0;
  13352. padded[i++] = 0;
  13353. padded[i++] = 0;
  13354. padded[i++] = 0;
  13355. padded[i++] = (length >>> 29) & 0xFF;
  13356. padded[i++] = (length >> 21) & 0xFF;
  13357. padded[i++] = (length >> 13) & 0xFF;
  13358. padded[i++] = (length >> 5) & 0xFF;
  13359. padded[i++] = (length << 3) & 0xFF;
  13360. var w = new Array(80);
  13361. for (i = 0; i < 80; i++) {
  13362. w[i] = new Word64(0, 0);
  13363. }
  13364. var a = new Word64(0, 0), b = new Word64(0, 0), c = new Word64(0, 0);
  13365. var d = new Word64(0, 0), e = new Word64(0, 0), f = new Word64(0, 0);
  13366. var g = new Word64(0, 0), h = new Word64(0, 0);
  13367. var t1 = new Word64(0, 0), t2 = new Word64(0, 0);
  13368. var tmp1 = new Word64(0, 0), tmp2 = new Word64(0, 0), tmp3;
  13369. // for each 1024 bit block
  13370. for (i = 0; i < paddedLength;) {
  13371. for (j = 0; j < 16; ++j) {
  13372. w[j].high = (padded[i] << 24) | (padded[i + 1] << 16) |
  13373. (padded[i + 2] << 8) | (padded[i + 3]);
  13374. w[j].low = (padded[i + 4]) << 24 | (padded[i + 5]) << 16 |
  13375. (padded[i + 6]) << 8 | (padded[i + 7]);
  13376. i += 8;
  13377. }
  13378. for (j = 16; j < 80; ++j) {
  13379. tmp3 = w[j];
  13380. littleSigmaPrime(tmp3, w[j - 2], tmp2);
  13381. tmp3.add(w[j - 7]);
  13382. littleSigma(tmp1, w[j - 15], tmp2);
  13383. tmp3.add(tmp1);
  13384. tmp3.add(w[j - 16]);
  13385. }
  13386. a.assign(h0); b.assign(h1); c.assign(h2); d.assign(h3);
  13387. e.assign(h4); f.assign(h5); g.assign(h6); h.assign(h7);
  13388. for (j = 0; j < 80; ++j) {
  13389. t1.assign(h);
  13390. sigmaPrime(tmp1, e, tmp2);
  13391. t1.add(tmp1);
  13392. ch(tmp1, e, f, g, tmp2);
  13393. t1.add(tmp1);
  13394. t1.add(k[j]);
  13395. t1.add(w[j]);
  13396. sigma(t2, a, tmp2);
  13397. maj(tmp1, a, b, c, tmp2);
  13398. t2.add(tmp1);
  13399. tmp3 = h;
  13400. h = g;
  13401. g = f;
  13402. f = e;
  13403. d.add(t1);
  13404. e = d;
  13405. d = c;
  13406. c = b;
  13407. b = a;
  13408. tmp3.assign(t1);
  13409. tmp3.add(t2);
  13410. a = tmp3;
  13411. }
  13412. h0.add(a);
  13413. h1.add(b);
  13414. h2.add(c);
  13415. h3.add(d);
  13416. h4.add(e);
  13417. h5.add(f);
  13418. h6.add(g);
  13419. h7.add(h);
  13420. }
  13421. var result;
  13422. if (!mode384) {
  13423. result = new Uint8Array(64);
  13424. h0.copyTo(result,0);
  13425. h1.copyTo(result,8);
  13426. h2.copyTo(result,16);
  13427. h3.copyTo(result,24);
  13428. h4.copyTo(result,32);
  13429. h5.copyTo(result,40);
  13430. h6.copyTo(result,48);
  13431. h7.copyTo(result,56);
  13432. }
  13433. else {
  13434. result = new Uint8Array(48);
  13435. h0.copyTo(result,0);
  13436. h1.copyTo(result,8);
  13437. h2.copyTo(result,16);
  13438. h3.copyTo(result,24);
  13439. h4.copyTo(result,32);
  13440. h5.copyTo(result,40);
  13441. }
  13442. return result;
  13443. }
  13444. return hash;
  13445. })();
  13446. var calculateSHA384 = (function calculateSHA384Closure() {
  13447. function hash(data, offset, length) {
  13448. return calculateSHA512(data, offset, length, true);
  13449. }
  13450. return hash;
  13451. })();
  13452. var NullCipher = (function NullCipherClosure() {
  13453. function NullCipher() {
  13454. }
  13455. NullCipher.prototype = {
  13456. decryptBlock: function NullCipher_decryptBlock(data) {
  13457. return data;
  13458. }
  13459. };
  13460. return NullCipher;
  13461. })();
  13462. var AES128Cipher = (function AES128CipherClosure() {
  13463. var rcon = new Uint8Array([
  13464. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13465. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13466. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13467. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13468. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
  13469. 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,
  13470. 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  13471. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  13472. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10,
  13473. 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e,
  13474. 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  13475. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
  13476. 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
  13477. 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  13478. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  13479. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
  13480. 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb,
  13481. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13482. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13483. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13484. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13485. 0x74, 0xe8, 0xcb, 0x8d]);
  13486. var s = new Uint8Array([
  13487. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
  13488. 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
  13489. 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
  13490. 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  13491. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
  13492. 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
  13493. 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
  13494. 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  13495. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
  13496. 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
  13497. 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  13498. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  13499. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
  13500. 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
  13501. 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
  13502. 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  13503. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
  13504. 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
  13505. 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
  13506. 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  13507. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
  13508. 0xb0, 0x54, 0xbb, 0x16]);
  13509. var inv_s = new Uint8Array([
  13510. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
  13511. 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
  13512. 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
  13513. 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  13514. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
  13515. 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
  13516. 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
  13517. 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  13518. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
  13519. 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
  13520. 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  13521. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  13522. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
  13523. 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
  13524. 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
  13525. 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  13526. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
  13527. 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
  13528. 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
  13529. 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  13530. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
  13531. 0x55, 0x21, 0x0c, 0x7d]);
  13532. var mixCol = new Uint8Array(256);
  13533. for (var i = 0; i < 256; i++) {
  13534. if (i < 128) {
  13535. mixCol[i] = i << 1;
  13536. } else {
  13537. mixCol[i] = (i << 1) ^ 0x1b;
  13538. }
  13539. }
  13540. var mix = new Uint32Array([
  13541. 0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927,
  13542. 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
  13543. 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb,
  13544. 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
  13545. 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf,
  13546. 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
  13547. 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28,
  13548. 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
  13549. 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec,
  13550. 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
  13551. 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd,
  13552. 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
  13553. 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89,
  13554. 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
  13555. 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815,
  13556. 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f,
  13557. 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa,
  13558. 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8,
  13559. 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36,
  13560. 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
  13561. 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742,
  13562. 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
  13563. 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4,
  13564. 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e,
  13565. 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360,
  13566. 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
  13567. 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87,
  13568. 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
  13569. 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3,
  13570. 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
  13571. 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f,
  13572. 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
  13573. 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26,
  13574. 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
  13575. 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba,
  13576. 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
  13577. 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce,
  13578. 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
  13579. 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929,
  13580. 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
  13581. 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed,
  13582. 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
  13583. 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
  13584. function expandKey128(cipherKey) {
  13585. var b = 176, result = new Uint8Array(b);
  13586. result.set(cipherKey);
  13587. for (var j = 16, i = 1; j < b; ++i) {
  13588. // RotWord
  13589. var t1 = result[j - 3], t2 = result[j - 2],
  13590. t3 = result[j - 1], t4 = result[j - 4];
  13591. // SubWord
  13592. t1 = s[t1];
  13593. t2 = s[t2];
  13594. t3 = s[t3];
  13595. t4 = s[t4];
  13596. // Rcon
  13597. t1 = t1 ^ rcon[i];
  13598. for (var n = 0; n < 4; ++n) {
  13599. result[j] = (t1 ^= result[j - 16]);
  13600. j++;
  13601. result[j] = (t2 ^= result[j - 16]);
  13602. j++;
  13603. result[j] = (t3 ^= result[j - 16]);
  13604. j++;
  13605. result[j] = (t4 ^= result[j - 16]);
  13606. j++;
  13607. }
  13608. }
  13609. return result;
  13610. }
  13611. function decrypt128(input, key) {
  13612. var state = new Uint8Array(16);
  13613. state.set(input);
  13614. var i, j, k;
  13615. var t, u, v;
  13616. // AddRoundKey
  13617. for (j = 0, k = 160; j < 16; ++j, ++k) {
  13618. state[j] ^= key[k];
  13619. }
  13620. for (i = 9; i >= 1; --i) {
  13621. // InvShiftRows
  13622. t = state[13];
  13623. state[13] = state[9];
  13624. state[9] = state[5];
  13625. state[5] = state[1];
  13626. state[1] = t;
  13627. t = state[14];
  13628. u = state[10];
  13629. state[14] = state[6];
  13630. state[10] = state[2];
  13631. state[6] = t;
  13632. state[2] = u;
  13633. t = state[15];
  13634. u = state[11];
  13635. v = state[7];
  13636. state[15] = state[3];
  13637. state[11] = t;
  13638. state[7] = u;
  13639. state[3] = v;
  13640. // InvSubBytes
  13641. for (j = 0; j < 16; ++j) {
  13642. state[j] = inv_s[state[j]];
  13643. }
  13644. // AddRoundKey
  13645. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13646. state[j] ^= key[k];
  13647. }
  13648. // InvMixColumns
  13649. for (j = 0; j < 16; j += 4) {
  13650. var s0 = mix[state[j]], s1 = mix[state[j + 1]],
  13651. s2 = mix[state[j + 2]], s3 = mix[state[j + 3]];
  13652. t = (s0 ^ (s1 >>> 8) ^ (s1 << 24) ^ (s2 >>> 16) ^ (s2 << 16) ^
  13653. (s3 >>> 24) ^ (s3 << 8));
  13654. state[j] = (t >>> 24) & 0xFF;
  13655. state[j + 1] = (t >> 16) & 0xFF;
  13656. state[j + 2] = (t >> 8) & 0xFF;
  13657. state[j + 3] = t & 0xFF;
  13658. }
  13659. }
  13660. // InvShiftRows
  13661. t = state[13];
  13662. state[13] = state[9];
  13663. state[9] = state[5];
  13664. state[5] = state[1];
  13665. state[1] = t;
  13666. t = state[14];
  13667. u = state[10];
  13668. state[14] = state[6];
  13669. state[10] = state[2];
  13670. state[6] = t;
  13671. state[2] = u;
  13672. t = state[15];
  13673. u = state[11];
  13674. v = state[7];
  13675. state[15] = state[3];
  13676. state[11] = t;
  13677. state[7] = u;
  13678. state[3] = v;
  13679. for (j = 0; j < 16; ++j) {
  13680. // InvSubBytes
  13681. state[j] = inv_s[state[j]];
  13682. // AddRoundKey
  13683. state[j] ^= key[j];
  13684. }
  13685. return state;
  13686. }
  13687. function encrypt128(input, key) {
  13688. var t, u, v, k;
  13689. var state = new Uint8Array(16);
  13690. state.set(input);
  13691. for (j = 0; j < 16; ++j) {
  13692. // AddRoundKey
  13693. state[j] ^= key[j];
  13694. }
  13695. for (i = 1; i < 10; i++) {
  13696. //SubBytes
  13697. for (j = 0; j < 16; ++j) {
  13698. state[j] = s[state[j]];
  13699. }
  13700. //ShiftRows
  13701. v = state[1];
  13702. state[1] = state[5];
  13703. state[5] = state[9];
  13704. state[9] = state[13];
  13705. state[13] = v;
  13706. v = state[2];
  13707. u = state[6];
  13708. state[2] = state[10];
  13709. state[6] = state[14];
  13710. state[10] = v;
  13711. state[14] = u;
  13712. v = state[3];
  13713. u = state[7];
  13714. t = state[11];
  13715. state[3] = state[15];
  13716. state[7] = v;
  13717. state[11] = u;
  13718. state[15] = t;
  13719. //MixColumns
  13720. for (var j = 0; j < 16; j += 4) {
  13721. var s0 = state[j + 0], s1 = state[j + 1];
  13722. var s2 = state[j + 2], s3 = state[j + 3];
  13723. t = s0 ^ s1 ^ s2 ^ s3;
  13724. state[j + 0] ^= t ^ mixCol[s0 ^ s1];
  13725. state[j + 1] ^= t ^ mixCol[s1 ^ s2];
  13726. state[j + 2] ^= t ^ mixCol[s2 ^ s3];
  13727. state[j + 3] ^= t ^ mixCol[s3 ^ s0];
  13728. }
  13729. //AddRoundKey
  13730. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13731. state[j] ^= key[k];
  13732. }
  13733. }
  13734. //SubBytes
  13735. for (j = 0; j < 16; ++j) {
  13736. state[j] = s[state[j]];
  13737. }
  13738. //ShiftRows
  13739. v = state[1];
  13740. state[1] = state[5];
  13741. state[5] = state[9];
  13742. state[9] = state[13];
  13743. state[13] = v;
  13744. v = state[2];
  13745. u = state[6];
  13746. state[2] = state[10];
  13747. state[6] = state[14];
  13748. state[10] = v;
  13749. state[14] = u;
  13750. v = state[3];
  13751. u = state[7];
  13752. t = state[11];
  13753. state[3] = state[15];
  13754. state[7] = v;
  13755. state[11] = u;
  13756. state[15] = t;
  13757. //AddRoundKey
  13758. for (j = 0, k = 160; j < 16; ++j, ++k) {
  13759. state[j] ^= key[k];
  13760. }
  13761. return state;
  13762. }
  13763. function AES128Cipher(key) {
  13764. this.key = expandKey128(key);
  13765. this.buffer = new Uint8Array(16);
  13766. this.bufferPosition = 0;
  13767. }
  13768. function decryptBlock2(data, finalize) {
  13769. var i, j, ii, sourceLength = data.length,
  13770. buffer = this.buffer, bufferLength = this.bufferPosition,
  13771. result = [], iv = this.iv;
  13772. for (i = 0; i < sourceLength; ++i) {
  13773. buffer[bufferLength] = data[i];
  13774. ++bufferLength;
  13775. if (bufferLength < 16) {
  13776. continue;
  13777. }
  13778. // buffer is full, decrypting
  13779. var plain = decrypt128(buffer, this.key);
  13780. // xor-ing the IV vector to get plain text
  13781. for (j = 0; j < 16; ++j) {
  13782. plain[j] ^= iv[j];
  13783. }
  13784. iv = buffer;
  13785. result.push(plain);
  13786. buffer = new Uint8Array(16);
  13787. bufferLength = 0;
  13788. }
  13789. // saving incomplete buffer
  13790. this.buffer = buffer;
  13791. this.bufferLength = bufferLength;
  13792. this.iv = iv;
  13793. if (result.length === 0) {
  13794. return new Uint8Array([]);
  13795. }
  13796. // combining plain text blocks into one
  13797. var outputLength = 16 * result.length;
  13798. if (finalize) {
  13799. // undo a padding that is described in RFC 2898
  13800. var lastBlock = result[result.length - 1];
  13801. var psLen = lastBlock[15];
  13802. if (psLen <= 16) {
  13803. for (i = 15, ii = 16 - psLen; i >= ii; --i) {
  13804. if (lastBlock[i] !== psLen) {
  13805. // Invalid padding, assume that the block has no padding.
  13806. psLen = 0;
  13807. break;
  13808. }
  13809. }
  13810. outputLength -= psLen;
  13811. result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
  13812. }
  13813. }
  13814. var output = new Uint8Array(outputLength);
  13815. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13816. output.set(result[i], j);
  13817. }
  13818. return output;
  13819. }
  13820. AES128Cipher.prototype = {
  13821. decryptBlock: function AES128Cipher_decryptBlock(data, finalize) {
  13822. var i, sourceLength = data.length;
  13823. var buffer = this.buffer, bufferLength = this.bufferPosition;
  13824. // waiting for IV values -- they are at the start of the stream
  13825. for (i = 0; bufferLength < 16 && i < sourceLength; ++i, ++bufferLength) {
  13826. buffer[bufferLength] = data[i];
  13827. }
  13828. if (bufferLength < 16) {
  13829. // need more data
  13830. this.bufferLength = bufferLength;
  13831. return new Uint8Array([]);
  13832. }
  13833. this.iv = buffer;
  13834. this.buffer = new Uint8Array(16);
  13835. this.bufferLength = 0;
  13836. // starting decryption
  13837. this.decryptBlock = decryptBlock2;
  13838. return this.decryptBlock(data.subarray(16), finalize);
  13839. },
  13840. encrypt: function AES128Cipher_encrypt(data, iv) {
  13841. var i, j, ii, sourceLength = data.length,
  13842. buffer = this.buffer, bufferLength = this.bufferPosition,
  13843. result = [];
  13844. if (!iv) {
  13845. iv = new Uint8Array(16);
  13846. }
  13847. for (i = 0; i < sourceLength; ++i) {
  13848. buffer[bufferLength] = data[i];
  13849. ++bufferLength;
  13850. if (bufferLength < 16) {
  13851. continue;
  13852. }
  13853. for (j = 0; j < 16; ++j) {
  13854. buffer[j] ^= iv[j];
  13855. }
  13856. // buffer is full, encrypting
  13857. var cipher = encrypt128(buffer, this.key);
  13858. iv = cipher;
  13859. result.push(cipher);
  13860. buffer = new Uint8Array(16);
  13861. bufferLength = 0;
  13862. }
  13863. // saving incomplete buffer
  13864. this.buffer = buffer;
  13865. this.bufferLength = bufferLength;
  13866. this.iv = iv;
  13867. if (result.length === 0) {
  13868. return new Uint8Array([]);
  13869. }
  13870. // combining plain text blocks into one
  13871. var outputLength = 16 * result.length;
  13872. var output = new Uint8Array(outputLength);
  13873. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13874. output.set(result[i], j);
  13875. }
  13876. return output;
  13877. }
  13878. };
  13879. return AES128Cipher;
  13880. })();
  13881. var AES256Cipher = (function AES256CipherClosure() {
  13882. var rcon = new Uint8Array([
  13883. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13884. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13885. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13886. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13887. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
  13888. 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,
  13889. 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  13890. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  13891. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10,
  13892. 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e,
  13893. 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  13894. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
  13895. 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
  13896. 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  13897. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  13898. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
  13899. 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb,
  13900. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13901. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13902. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13903. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13904. 0x74, 0xe8, 0xcb, 0x8d]);
  13905. var s = new Uint8Array([
  13906. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
  13907. 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
  13908. 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
  13909. 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  13910. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
  13911. 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
  13912. 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
  13913. 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  13914. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
  13915. 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
  13916. 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  13917. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  13918. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
  13919. 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
  13920. 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
  13921. 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  13922. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
  13923. 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
  13924. 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
  13925. 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  13926. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
  13927. 0xb0, 0x54, 0xbb, 0x16]);
  13928. var inv_s = new Uint8Array([
  13929. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
  13930. 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
  13931. 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
  13932. 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  13933. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
  13934. 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
  13935. 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
  13936. 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  13937. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
  13938. 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
  13939. 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  13940. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  13941. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
  13942. 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
  13943. 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
  13944. 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  13945. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
  13946. 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
  13947. 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
  13948. 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  13949. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
  13950. 0x55, 0x21, 0x0c, 0x7d]);
  13951. var mixCol = new Uint8Array(256);
  13952. for (var i = 0; i < 256; i++) {
  13953. if (i < 128) {
  13954. mixCol[i] = i << 1;
  13955. } else {
  13956. mixCol[i] = (i << 1) ^ 0x1b;
  13957. }
  13958. }
  13959. var mix = new Uint32Array([
  13960. 0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927,
  13961. 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
  13962. 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb,
  13963. 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
  13964. 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf,
  13965. 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
  13966. 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28,
  13967. 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
  13968. 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec,
  13969. 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
  13970. 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd,
  13971. 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
  13972. 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89,
  13973. 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
  13974. 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815,
  13975. 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f,
  13976. 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa,
  13977. 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8,
  13978. 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36,
  13979. 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
  13980. 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742,
  13981. 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
  13982. 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4,
  13983. 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e,
  13984. 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360,
  13985. 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
  13986. 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87,
  13987. 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
  13988. 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3,
  13989. 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
  13990. 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f,
  13991. 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
  13992. 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26,
  13993. 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
  13994. 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba,
  13995. 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
  13996. 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce,
  13997. 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
  13998. 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929,
  13999. 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
  14000. 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed,
  14001. 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
  14002. 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
  14003. function expandKey256(cipherKey) {
  14004. var b = 240, result = new Uint8Array(b);
  14005. var r = 1;
  14006. result.set(cipherKey);
  14007. for (var j = 32, i = 1; j < b; ++i) {
  14008. if (j % 32 === 16) {
  14009. t1 = s[t1];
  14010. t2 = s[t2];
  14011. t3 = s[t3];
  14012. t4 = s[t4];
  14013. } else if (j % 32 === 0) {
  14014. // RotWord
  14015. var t1 = result[j - 3], t2 = result[j - 2],
  14016. t3 = result[j - 1], t4 = result[j - 4];
  14017. // SubWord
  14018. t1 = s[t1];
  14019. t2 = s[t2];
  14020. t3 = s[t3];
  14021. t4 = s[t4];
  14022. // Rcon
  14023. t1 = t1 ^ r;
  14024. if ((r <<= 1) >= 256) {
  14025. r = (r ^ 0x1b) & 0xFF;
  14026. }
  14027. }
  14028. for (var n = 0; n < 4; ++n) {
  14029. result[j] = (t1 ^= result[j - 32]);
  14030. j++;
  14031. result[j] = (t2 ^= result[j - 32]);
  14032. j++;
  14033. result[j] = (t3 ^= result[j - 32]);
  14034. j++;
  14035. result[j] = (t4 ^= result[j - 32]);
  14036. j++;
  14037. }
  14038. }
  14039. return result;
  14040. }
  14041. function decrypt256(input, key) {
  14042. var state = new Uint8Array(16);
  14043. state.set(input);
  14044. var i, j, k;
  14045. var t, u, v;
  14046. // AddRoundKey
  14047. for (j = 0, k = 224; j < 16; ++j, ++k) {
  14048. state[j] ^= key[k];
  14049. }
  14050. for (i = 13; i >= 1; --i) {
  14051. // InvShiftRows
  14052. t = state[13];
  14053. state[13] = state[9];
  14054. state[9] = state[5];
  14055. state[5] = state[1];
  14056. state[1] = t;
  14057. t = state[14];
  14058. u = state[10];
  14059. state[14] = state[6];
  14060. state[10] = state[2];
  14061. state[6] = t;
  14062. state[2] = u;
  14063. t = state[15];
  14064. u = state[11];
  14065. v = state[7];
  14066. state[15] = state[3];
  14067. state[11] = t;
  14068. state[7] = u;
  14069. state[3] = v;
  14070. // InvSubBytes
  14071. for (j = 0; j < 16; ++j) {
  14072. state[j] = inv_s[state[j]];
  14073. }
  14074. // AddRoundKey
  14075. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  14076. state[j] ^= key[k];
  14077. }
  14078. // InvMixColumns
  14079. for (j = 0; j < 16; j += 4) {
  14080. var s0 = mix[state[j]], s1 = mix[state[j + 1]],
  14081. s2 = mix[state[j + 2]], s3 = mix[state[j + 3]];
  14082. t = (s0 ^ (s1 >>> 8) ^ (s1 << 24) ^ (s2 >>> 16) ^ (s2 << 16) ^
  14083. (s3 >>> 24) ^ (s3 << 8));
  14084. state[j] = (t >>> 24) & 0xFF;
  14085. state[j + 1] = (t >> 16) & 0xFF;
  14086. state[j + 2] = (t >> 8) & 0xFF;
  14087. state[j + 3] = t & 0xFF;
  14088. }
  14089. }
  14090. // InvShiftRows
  14091. t = state[13];
  14092. state[13] = state[9];
  14093. state[9] = state[5];
  14094. state[5] = state[1];
  14095. state[1] = t;
  14096. t = state[14];
  14097. u = state[10];
  14098. state[14] = state[6];
  14099. state[10] = state[2];
  14100. state[6] = t;
  14101. state[2] = u;
  14102. t = state[15];
  14103. u = state[11];
  14104. v = state[7];
  14105. state[15] = state[3];
  14106. state[11] = t;
  14107. state[7] = u;
  14108. state[3] = v;
  14109. for (j = 0; j < 16; ++j) {
  14110. // InvSubBytes
  14111. state[j] = inv_s[state[j]];
  14112. // AddRoundKey
  14113. state[j] ^= key[j];
  14114. }
  14115. return state;
  14116. }
  14117. function encrypt256(input, key) {
  14118. var t, u, v, k;
  14119. var state = new Uint8Array(16);
  14120. state.set(input);
  14121. for (j = 0; j < 16; ++j) {
  14122. // AddRoundKey
  14123. state[j] ^= key[j];
  14124. }
  14125. for (i = 1; i < 14; i++) {
  14126. //SubBytes
  14127. for (j = 0; j < 16; ++j) {
  14128. state[j] = s[state[j]];
  14129. }
  14130. //ShiftRows
  14131. v = state[1];
  14132. state[1] = state[5];
  14133. state[5] = state[9];
  14134. state[9] = state[13];
  14135. state[13] = v;
  14136. v = state[2];
  14137. u = state[6];
  14138. state[2] = state[10];
  14139. state[6] = state[14];
  14140. state[10] = v;
  14141. state[14] = u;
  14142. v = state[3];
  14143. u = state[7];
  14144. t = state[11];
  14145. state[3] = state[15];
  14146. state[7] = v;
  14147. state[11] = u;
  14148. state[15] = t;
  14149. //MixColumns
  14150. for (var j = 0; j < 16; j += 4) {
  14151. var s0 = state[j + 0], s1 = state[j + 1];
  14152. var s2 = state[j + 2], s3 = state[j + 3];
  14153. t = s0 ^ s1 ^ s2 ^ s3;
  14154. state[j + 0] ^= t ^ mixCol[s0 ^ s1];
  14155. state[j + 1] ^= t ^ mixCol[s1 ^ s2];
  14156. state[j + 2] ^= t ^ mixCol[s2 ^ s3];
  14157. state[j + 3] ^= t ^ mixCol[s3 ^ s0];
  14158. }
  14159. //AddRoundKey
  14160. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  14161. state[j] ^= key[k];
  14162. }
  14163. }
  14164. //SubBytes
  14165. for (j = 0; j < 16; ++j) {
  14166. state[j] = s[state[j]];
  14167. }
  14168. //ShiftRows
  14169. v = state[1];
  14170. state[1] = state[5];
  14171. state[5] = state[9];
  14172. state[9] = state[13];
  14173. state[13] = v;
  14174. v = state[2];
  14175. u = state[6];
  14176. state[2] = state[10];
  14177. state[6] = state[14];
  14178. state[10] = v;
  14179. state[14] = u;
  14180. v = state[3];
  14181. u = state[7];
  14182. t = state[11];
  14183. state[3] = state[15];
  14184. state[7] = v;
  14185. state[11] = u;
  14186. state[15] = t;
  14187. //AddRoundKey
  14188. for (j = 0, k = 224; j < 16; ++j, ++k) {
  14189. state[j] ^= key[k];
  14190. }
  14191. return state;
  14192. }
  14193. function AES256Cipher(key) {
  14194. this.key = expandKey256(key);
  14195. this.buffer = new Uint8Array(16);
  14196. this.bufferPosition = 0;
  14197. }
  14198. function decryptBlock2(data, finalize) {
  14199. var i, j, ii, sourceLength = data.length,
  14200. buffer = this.buffer, bufferLength = this.bufferPosition,
  14201. result = [], iv = this.iv;
  14202. for (i = 0; i < sourceLength; ++i) {
  14203. buffer[bufferLength] = data[i];
  14204. ++bufferLength;
  14205. if (bufferLength < 16) {
  14206. continue;
  14207. }
  14208. // buffer is full, decrypting
  14209. var plain = decrypt256(buffer, this.key);
  14210. // xor-ing the IV vector to get plain text
  14211. for (j = 0; j < 16; ++j) {
  14212. plain[j] ^= iv[j];
  14213. }
  14214. iv = buffer;
  14215. result.push(plain);
  14216. buffer = new Uint8Array(16);
  14217. bufferLength = 0;
  14218. }
  14219. // saving incomplete buffer
  14220. this.buffer = buffer;
  14221. this.bufferLength = bufferLength;
  14222. this.iv = iv;
  14223. if (result.length === 0) {
  14224. return new Uint8Array([]);
  14225. }
  14226. // combining plain text blocks into one
  14227. var outputLength = 16 * result.length;
  14228. if (finalize) {
  14229. // undo a padding that is described in RFC 2898
  14230. var lastBlock = result[result.length - 1];
  14231. var psLen = lastBlock[15];
  14232. if (psLen <= 16) {
  14233. for (i = 15, ii = 16 - psLen; i >= ii; --i) {
  14234. if (lastBlock[i] !== psLen) {
  14235. // Invalid padding, assume that the block has no padding.
  14236. psLen = 0;
  14237. break;
  14238. }
  14239. }
  14240. outputLength -= psLen;
  14241. result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
  14242. }
  14243. }
  14244. var output = new Uint8Array(outputLength);
  14245. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  14246. output.set(result[i], j);
  14247. }
  14248. return output;
  14249. }
  14250. AES256Cipher.prototype = {
  14251. decryptBlock: function AES256Cipher_decryptBlock(data, finalize, iv) {
  14252. var i, sourceLength = data.length;
  14253. var buffer = this.buffer, bufferLength = this.bufferPosition;
  14254. // if not supplied an IV wait for IV values
  14255. // they are at the start of the stream
  14256. if (iv) {
  14257. this.iv = iv;
  14258. } else {
  14259. for (i = 0; bufferLength < 16 &&
  14260. i < sourceLength; ++i, ++bufferLength) {
  14261. buffer[bufferLength] = data[i];
  14262. }
  14263. if (bufferLength < 16) {
  14264. //need more data
  14265. this.bufferLength = bufferLength;
  14266. return new Uint8Array([]);
  14267. }
  14268. this.iv = buffer;
  14269. data = data.subarray(16);
  14270. }
  14271. this.buffer = new Uint8Array(16);
  14272. this.bufferLength = 0;
  14273. // starting decryption
  14274. this.decryptBlock = decryptBlock2;
  14275. return this.decryptBlock(data, finalize);
  14276. },
  14277. encrypt: function AES256Cipher_encrypt(data, iv) {
  14278. var i, j, ii, sourceLength = data.length,
  14279. buffer = this.buffer, bufferLength = this.bufferPosition,
  14280. result = [];
  14281. if (!iv) {
  14282. iv = new Uint8Array(16);
  14283. }
  14284. for (i = 0; i < sourceLength; ++i) {
  14285. buffer[bufferLength] = data[i];
  14286. ++bufferLength;
  14287. if (bufferLength < 16) {
  14288. continue;
  14289. }
  14290. for (j = 0; j < 16; ++j) {
  14291. buffer[j] ^= iv[j];
  14292. }
  14293. // buffer is full, encrypting
  14294. var cipher = encrypt256(buffer, this.key);
  14295. this.iv = cipher;
  14296. result.push(cipher);
  14297. buffer = new Uint8Array(16);
  14298. bufferLength = 0;
  14299. }
  14300. // saving incomplete buffer
  14301. this.buffer = buffer;
  14302. this.bufferLength = bufferLength;
  14303. this.iv = iv;
  14304. if (result.length === 0) {
  14305. return new Uint8Array([]);
  14306. }
  14307. // combining plain text blocks into one
  14308. var outputLength = 16 * result.length;
  14309. var output = new Uint8Array(outputLength);
  14310. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  14311. output.set(result[i], j);
  14312. }
  14313. return output;
  14314. }
  14315. };
  14316. return AES256Cipher;
  14317. })();
  14318. var PDF17 = (function PDF17Closure() {
  14319. function compareByteArrays(array1, array2) {
  14320. if (array1.length !== array2.length) {
  14321. return false;
  14322. }
  14323. for (var i = 0; i < array1.length; i++) {
  14324. if (array1[i] !== array2[i]) {
  14325. return false;
  14326. }
  14327. }
  14328. return true;
  14329. }
  14330. function PDF17() {
  14331. }
  14332. PDF17.prototype = {
  14333. checkOwnerPassword: function PDF17_checkOwnerPassword(password,
  14334. ownerValidationSalt,
  14335. userBytes,
  14336. ownerPassword) {
  14337. var hashData = new Uint8Array(password.length + 56);
  14338. hashData.set(password, 0);
  14339. hashData.set(ownerValidationSalt, password.length);
  14340. hashData.set(userBytes, password.length + ownerValidationSalt.length);
  14341. var result = calculateSHA256(hashData, 0, hashData.length);
  14342. return compareByteArrays(result, ownerPassword);
  14343. },
  14344. checkUserPassword: function PDF17_checkUserPassword(password,
  14345. userValidationSalt,
  14346. userPassword) {
  14347. var hashData = new Uint8Array(password.length + 8);
  14348. hashData.set(password, 0);
  14349. hashData.set(userValidationSalt, password.length);
  14350. var result = calculateSHA256(hashData, 0, hashData.length);
  14351. return compareByteArrays(result, userPassword);
  14352. },
  14353. getOwnerKey: function PDF17_getOwnerKey(password, ownerKeySalt, userBytes,
  14354. ownerEncryption) {
  14355. var hashData = new Uint8Array(password.length + 56);
  14356. hashData.set(password, 0);
  14357. hashData.set(ownerKeySalt, password.length);
  14358. hashData.set(userBytes, password.length + ownerKeySalt.length);
  14359. var key = calculateSHA256(hashData, 0, hashData.length);
  14360. var cipher = new AES256Cipher(key);
  14361. return cipher.decryptBlock(ownerEncryption,
  14362. false,
  14363. new Uint8Array(16));
  14364. },
  14365. getUserKey: function PDF17_getUserKey(password, userKeySalt,
  14366. userEncryption) {
  14367. var hashData = new Uint8Array(password.length + 8);
  14368. hashData.set(password, 0);
  14369. hashData.set(userKeySalt, password.length);
  14370. //key is the decryption key for the UE string
  14371. var key = calculateSHA256(hashData, 0, hashData.length);
  14372. var cipher = new AES256Cipher(key);
  14373. return cipher.decryptBlock(userEncryption,
  14374. false,
  14375. new Uint8Array(16));
  14376. }
  14377. };
  14378. return PDF17;
  14379. })();
  14380. var PDF20 = (function PDF20Closure() {
  14381. function concatArrays(array1, array2) {
  14382. var t = new Uint8Array(array1.length + array2.length);
  14383. t.set(array1, 0);
  14384. t.set(array2, array1.length);
  14385. return t;
  14386. }
  14387. function calculatePDF20Hash(password, input, userBytes) {
  14388. //This refers to Algorithm 2.B as defined in ISO 32000-2
  14389. var k = calculateSHA256(input, 0, input.length).subarray(0, 32);
  14390. var e = [0];
  14391. var i = 0;
  14392. while (i < 64 || e[e.length - 1] > i - 32) {
  14393. var arrayLength = password.length + k.length + userBytes.length;
  14394. var k1 = new Uint8Array(arrayLength * 64);
  14395. var array = concatArrays(password, k);
  14396. array = concatArrays(array, userBytes);
  14397. for (var j = 0, pos = 0; j < 64; j++, pos += arrayLength) {
  14398. k1.set(array, pos);
  14399. }
  14400. //AES128 CBC NO PADDING with
  14401. //first 16 bytes of k as the key and the second 16 as the iv.
  14402. var cipher = new AES128Cipher(k.subarray(0, 16));
  14403. e = cipher.encrypt(k1, k.subarray(16, 32));
  14404. //Now we have to take the first 16 bytes of an unsigned
  14405. //big endian integer... and compute the remainder
  14406. //modulo 3.... That is a fairly large number and
  14407. //JavaScript isn't going to handle that well...
  14408. //So we're using a trick that allows us to perform
  14409. //modulo math byte by byte
  14410. var remainder = 0;
  14411. for (var z = 0; z < 16; z++) {
  14412. remainder *= (256 % 3);
  14413. remainder %= 3;
  14414. remainder += ((e[z] >>> 0) % 3);
  14415. remainder %= 3;
  14416. }
  14417. if (remainder === 0) {
  14418. k = calculateSHA256(e, 0, e.length);
  14419. }
  14420. else if (remainder === 1) {
  14421. k = calculateSHA384(e, 0, e.length);
  14422. }
  14423. else if (remainder === 2) {
  14424. k = calculateSHA512(e, 0, e.length);
  14425. }
  14426. i++;
  14427. }
  14428. return k.subarray(0, 32);
  14429. }
  14430. function PDF20() {
  14431. }
  14432. function compareByteArrays(array1, array2) {
  14433. if (array1.length !== array2.length) {
  14434. return false;
  14435. }
  14436. for (var i = 0; i < array1.length; i++) {
  14437. if (array1[i] !== array2[i]) {
  14438. return false;
  14439. }
  14440. }
  14441. return true;
  14442. }
  14443. PDF20.prototype = {
  14444. hash: function PDF20_hash(password, concatBytes, userBytes) {
  14445. return calculatePDF20Hash(password, concatBytes, userBytes);
  14446. },
  14447. checkOwnerPassword: function PDF20_checkOwnerPassword(password,
  14448. ownerValidationSalt,
  14449. userBytes,
  14450. ownerPassword) {
  14451. var hashData = new Uint8Array(password.length + 56);
  14452. hashData.set(password, 0);
  14453. hashData.set(ownerValidationSalt, password.length);
  14454. hashData.set(userBytes, password.length + ownerValidationSalt.length);
  14455. var result = calculatePDF20Hash(password, hashData, userBytes);
  14456. return compareByteArrays(result, ownerPassword);
  14457. },
  14458. checkUserPassword: function PDF20_checkUserPassword(password,
  14459. userValidationSalt,
  14460. userPassword) {
  14461. var hashData = new Uint8Array(password.length + 8);
  14462. hashData.set(password, 0);
  14463. hashData.set(userValidationSalt, password.length);
  14464. var result = calculatePDF20Hash(password, hashData, []);
  14465. return compareByteArrays(result, userPassword);
  14466. },
  14467. getOwnerKey: function PDF20_getOwnerKey(password, ownerKeySalt, userBytes,
  14468. ownerEncryption) {
  14469. var hashData = new Uint8Array(password.length + 56);
  14470. hashData.set(password, 0);
  14471. hashData.set(ownerKeySalt, password.length);
  14472. hashData.set(userBytes, password.length + ownerKeySalt.length);
  14473. var key = calculatePDF20Hash(password, hashData, userBytes);
  14474. var cipher = new AES256Cipher(key);
  14475. return cipher.decryptBlock(ownerEncryption,
  14476. false,
  14477. new Uint8Array(16));
  14478. },
  14479. getUserKey: function PDF20_getUserKey(password, userKeySalt,
  14480. userEncryption) {
  14481. var hashData = new Uint8Array(password.length + 8);
  14482. hashData.set(password, 0);
  14483. hashData.set(userKeySalt, password.length);
  14484. //key is the decryption key for the UE string
  14485. var key = calculatePDF20Hash(password, hashData, []);
  14486. var cipher = new AES256Cipher(key);
  14487. return cipher.decryptBlock(userEncryption,
  14488. false,
  14489. new Uint8Array(16));
  14490. }
  14491. };
  14492. return PDF20;
  14493. })();
  14494. var CipherTransform = (function CipherTransformClosure() {
  14495. function CipherTransform(stringCipherConstructor, streamCipherConstructor) {
  14496. this.stringCipherConstructor = stringCipherConstructor;
  14497. this.streamCipherConstructor = streamCipherConstructor;
  14498. }
  14499. CipherTransform.prototype = {
  14500. createStream: function CipherTransform_createStream(stream, length) {
  14501. var cipher = new this.streamCipherConstructor();
  14502. return new DecryptStream(stream, length,
  14503. function cipherTransformDecryptStream(data, finalize) {
  14504. return cipher.decryptBlock(data, finalize);
  14505. }
  14506. );
  14507. },
  14508. decryptString: function CipherTransform_decryptString(s) {
  14509. var cipher = new this.stringCipherConstructor();
  14510. var data = stringToBytes(s);
  14511. data = cipher.decryptBlock(data, true);
  14512. return bytesToString(data);
  14513. }
  14514. };
  14515. return CipherTransform;
  14516. })();
  14517. var CipherTransformFactory = (function CipherTransformFactoryClosure() {
  14518. var defaultPasswordBytes = new Uint8Array([
  14519. 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41,
  14520. 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
  14521. 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80,
  14522. 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A]);
  14523. function createEncryptionKey20(revision, password, ownerPassword,
  14524. ownerValidationSalt, ownerKeySalt, uBytes,
  14525. userPassword, userValidationSalt, userKeySalt,
  14526. ownerEncryption, userEncryption, perms) {
  14527. if (password) {
  14528. var passwordLength = Math.min(127, password.length);
  14529. password = password.subarray(0, passwordLength);
  14530. } else {
  14531. password = [];
  14532. }
  14533. var pdfAlgorithm;
  14534. if (revision === 6) {
  14535. pdfAlgorithm = new PDF20();
  14536. } else {
  14537. pdfAlgorithm = new PDF17();
  14538. }
  14539. if (pdfAlgorithm) {
  14540. if (pdfAlgorithm.checkUserPassword(password, userValidationSalt,
  14541. userPassword)) {
  14542. return pdfAlgorithm.getUserKey(password, userKeySalt, userEncryption);
  14543. } else if (password.length && pdfAlgorithm.checkOwnerPassword(password,
  14544. ownerValidationSalt,
  14545. uBytes,
  14546. ownerPassword)) {
  14547. return pdfAlgorithm.getOwnerKey(password, ownerKeySalt, uBytes,
  14548. ownerEncryption);
  14549. }
  14550. }
  14551. return null;
  14552. }
  14553. function prepareKeyData(fileId, password, ownerPassword, userPassword,
  14554. flags, revision, keyLength, encryptMetadata) {
  14555. var hashDataSize = 40 + ownerPassword.length + fileId.length;
  14556. var hashData = new Uint8Array(hashDataSize), i = 0, j, n;
  14557. if (password) {
  14558. n = Math.min(32, password.length);
  14559. for (; i < n; ++i) {
  14560. hashData[i] = password[i];
  14561. }
  14562. }
  14563. j = 0;
  14564. while (i < 32) {
  14565. hashData[i++] = defaultPasswordBytes[j++];
  14566. }
  14567. // as now the padded password in the hashData[0..i]
  14568. for (j = 0, n = ownerPassword.length; j < n; ++j) {
  14569. hashData[i++] = ownerPassword[j];
  14570. }
  14571. hashData[i++] = flags & 0xFF;
  14572. hashData[i++] = (flags >> 8) & 0xFF;
  14573. hashData[i++] = (flags >> 16) & 0xFF;
  14574. hashData[i++] = (flags >>> 24) & 0xFF;
  14575. for (j = 0, n = fileId.length; j < n; ++j) {
  14576. hashData[i++] = fileId[j];
  14577. }
  14578. if (revision >= 4 && !encryptMetadata) {
  14579. hashData[i++] = 0xFF;
  14580. hashData[i++] = 0xFF;
  14581. hashData[i++] = 0xFF;
  14582. hashData[i++] = 0xFF;
  14583. }
  14584. var hash = calculateMD5(hashData, 0, i);
  14585. var keyLengthInBytes = keyLength >> 3;
  14586. if (revision >= 3) {
  14587. for (j = 0; j < 50; ++j) {
  14588. hash = calculateMD5(hash, 0, keyLengthInBytes);
  14589. }
  14590. }
  14591. var encryptionKey = hash.subarray(0, keyLengthInBytes);
  14592. var cipher, checkData;
  14593. if (revision >= 3) {
  14594. for (i = 0; i < 32; ++i) {
  14595. hashData[i] = defaultPasswordBytes[i];
  14596. }
  14597. for (j = 0, n = fileId.length; j < n; ++j) {
  14598. hashData[i++] = fileId[j];
  14599. }
  14600. cipher = new ARCFourCipher(encryptionKey);
  14601. checkData = cipher.encryptBlock(calculateMD5(hashData, 0, i));
  14602. n = encryptionKey.length;
  14603. var derivedKey = new Uint8Array(n), k;
  14604. for (j = 1; j <= 19; ++j) {
  14605. for (k = 0; k < n; ++k) {
  14606. derivedKey[k] = encryptionKey[k] ^ j;
  14607. }
  14608. cipher = new ARCFourCipher(derivedKey);
  14609. checkData = cipher.encryptBlock(checkData);
  14610. }
  14611. for (j = 0, n = checkData.length; j < n; ++j) {
  14612. if (userPassword[j] !== checkData[j]) {
  14613. return null;
  14614. }
  14615. }
  14616. } else {
  14617. cipher = new ARCFourCipher(encryptionKey);
  14618. checkData = cipher.encryptBlock(defaultPasswordBytes);
  14619. for (j = 0, n = checkData.length; j < n; ++j) {
  14620. if (userPassword[j] !== checkData[j]) {
  14621. return null;
  14622. }
  14623. }
  14624. }
  14625. return encryptionKey;
  14626. }
  14627. function decodeUserPassword(password, ownerPassword, revision, keyLength) {
  14628. var hashData = new Uint8Array(32), i = 0, j, n;
  14629. n = Math.min(32, password.length);
  14630. for (; i < n; ++i) {
  14631. hashData[i] = password[i];
  14632. }
  14633. j = 0;
  14634. while (i < 32) {
  14635. hashData[i++] = defaultPasswordBytes[j++];
  14636. }
  14637. var hash = calculateMD5(hashData, 0, i);
  14638. var keyLengthInBytes = keyLength >> 3;
  14639. if (revision >= 3) {
  14640. for (j = 0; j < 50; ++j) {
  14641. hash = calculateMD5(hash, 0, hash.length);
  14642. }
  14643. }
  14644. var cipher, userPassword;
  14645. if (revision >= 3) {
  14646. userPassword = ownerPassword;
  14647. var derivedKey = new Uint8Array(keyLengthInBytes), k;
  14648. for (j = 19; j >= 0; j--) {
  14649. for (k = 0; k < keyLengthInBytes; ++k) {
  14650. derivedKey[k] = hash[k] ^ j;
  14651. }
  14652. cipher = new ARCFourCipher(derivedKey);
  14653. userPassword = cipher.encryptBlock(userPassword);
  14654. }
  14655. } else {
  14656. cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
  14657. userPassword = cipher.encryptBlock(ownerPassword);
  14658. }
  14659. return userPassword;
  14660. }
  14661. var identityName = Name.get('Identity');
  14662. function CipherTransformFactory(dict, fileId, password) {
  14663. var filter = dict.get('Filter');
  14664. if (!isName(filter) || filter.name !== 'Standard') {
  14665. error('unknown encryption method');
  14666. }
  14667. this.dict = dict;
  14668. var algorithm = dict.get('V');
  14669. if (!isInt(algorithm) ||
  14670. (algorithm !== 1 && algorithm !== 2 && algorithm !== 4 &&
  14671. algorithm !== 5)) {
  14672. error('unsupported encryption algorithm');
  14673. }
  14674. this.algorithm = algorithm;
  14675. var keyLength = dict.get('Length') || 40;
  14676. if (!isInt(keyLength) ||
  14677. keyLength < 40 || (keyLength % 8) !== 0) {
  14678. error('invalid key length');
  14679. }
  14680. // prepare keys
  14681. var ownerPassword = stringToBytes(dict.get('O')).subarray(0, 32);
  14682. var userPassword = stringToBytes(dict.get('U')).subarray(0, 32);
  14683. var flags = dict.get('P');
  14684. var revision = dict.get('R');
  14685. // meaningful when V is 4 or 5
  14686. var encryptMetadata = ((algorithm === 4 || algorithm === 5) &&
  14687. dict.get('EncryptMetadata') !== false);
  14688. this.encryptMetadata = encryptMetadata;
  14689. var fileIdBytes = stringToBytes(fileId);
  14690. var passwordBytes;
  14691. if (password) {
  14692. if (revision === 6) {
  14693. try {
  14694. password = utf8StringToString(password);
  14695. } catch (ex) {
  14696. warn('CipherTransformFactory: ' +
  14697. 'Unable to convert UTF8 encoded password.');
  14698. }
  14699. }
  14700. passwordBytes = stringToBytes(password);
  14701. }
  14702. var encryptionKey;
  14703. if (algorithm !== 5) {
  14704. encryptionKey = prepareKeyData(fileIdBytes, passwordBytes,
  14705. ownerPassword, userPassword, flags,
  14706. revision, keyLength, encryptMetadata);
  14707. }
  14708. else {
  14709. var ownerValidationSalt = stringToBytes(dict.get('O')).subarray(32, 40);
  14710. var ownerKeySalt = stringToBytes(dict.get('O')).subarray(40, 48);
  14711. var uBytes = stringToBytes(dict.get('U')).subarray(0, 48);
  14712. var userValidationSalt = stringToBytes(dict.get('U')).subarray(32, 40);
  14713. var userKeySalt = stringToBytes(dict.get('U')).subarray(40, 48);
  14714. var ownerEncryption = stringToBytes(dict.get('OE'));
  14715. var userEncryption = stringToBytes(dict.get('UE'));
  14716. var perms = stringToBytes(dict.get('Perms'));
  14717. encryptionKey =
  14718. createEncryptionKey20(revision, passwordBytes,
  14719. ownerPassword, ownerValidationSalt,
  14720. ownerKeySalt, uBytes,
  14721. userPassword, userValidationSalt,
  14722. userKeySalt, ownerEncryption,
  14723. userEncryption, perms);
  14724. }
  14725. if (!encryptionKey && !password) {
  14726. throw new PasswordException('No password given',
  14727. PasswordResponses.NEED_PASSWORD);
  14728. } else if (!encryptionKey && password) {
  14729. // Attempting use the password as an owner password
  14730. var decodedPassword = decodeUserPassword(passwordBytes, ownerPassword,
  14731. revision, keyLength);
  14732. encryptionKey = prepareKeyData(fileIdBytes, decodedPassword,
  14733. ownerPassword, userPassword, flags,
  14734. revision, keyLength, encryptMetadata);
  14735. }
  14736. if (!encryptionKey) {
  14737. throw new PasswordException('Incorrect Password',
  14738. PasswordResponses.INCORRECT_PASSWORD);
  14739. }
  14740. this.encryptionKey = encryptionKey;
  14741. if (algorithm >= 4) {
  14742. this.cf = dict.get('CF');
  14743. this.stmf = dict.get('StmF') || identityName;
  14744. this.strf = dict.get('StrF') || identityName;
  14745. this.eff = dict.get('EFF') || this.stmf;
  14746. }
  14747. }
  14748. function buildObjectKey(num, gen, encryptionKey, isAes) {
  14749. var key = new Uint8Array(encryptionKey.length + 9), i, n;
  14750. for (i = 0, n = encryptionKey.length; i < n; ++i) {
  14751. key[i] = encryptionKey[i];
  14752. }
  14753. key[i++] = num & 0xFF;
  14754. key[i++] = (num >> 8) & 0xFF;
  14755. key[i++] = (num >> 16) & 0xFF;
  14756. key[i++] = gen & 0xFF;
  14757. key[i++] = (gen >> 8) & 0xFF;
  14758. if (isAes) {
  14759. key[i++] = 0x73;
  14760. key[i++] = 0x41;
  14761. key[i++] = 0x6C;
  14762. key[i++] = 0x54;
  14763. }
  14764. var hash = calculateMD5(key, 0, i);
  14765. return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
  14766. }
  14767. function buildCipherConstructor(cf, name, num, gen, key) {
  14768. var cryptFilter = cf.get(name.name);
  14769. var cfm;
  14770. if (cryptFilter !== null && cryptFilter !== undefined) {
  14771. cfm = cryptFilter.get('CFM');
  14772. }
  14773. if (!cfm || cfm.name === 'None') {
  14774. return function cipherTransformFactoryBuildCipherConstructorNone() {
  14775. return new NullCipher();
  14776. };
  14777. }
  14778. if ('V2' === cfm.name) {
  14779. return function cipherTransformFactoryBuildCipherConstructorV2() {
  14780. return new ARCFourCipher(buildObjectKey(num, gen, key, false));
  14781. };
  14782. }
  14783. if ('AESV2' === cfm.name) {
  14784. return function cipherTransformFactoryBuildCipherConstructorAESV2() {
  14785. return new AES128Cipher(buildObjectKey(num, gen, key, true));
  14786. };
  14787. }
  14788. if ('AESV3' === cfm.name) {
  14789. return function cipherTransformFactoryBuildCipherConstructorAESV3() {
  14790. return new AES256Cipher(key);
  14791. };
  14792. }
  14793. error('Unknown crypto method');
  14794. }
  14795. CipherTransformFactory.prototype = {
  14796. createCipherTransform:
  14797. function CipherTransformFactory_createCipherTransform(num, gen) {
  14798. if (this.algorithm === 4 || this.algorithm === 5) {
  14799. return new CipherTransform(
  14800. buildCipherConstructor(this.cf, this.stmf,
  14801. num, gen, this.encryptionKey),
  14802. buildCipherConstructor(this.cf, this.strf,
  14803. num, gen, this.encryptionKey));
  14804. }
  14805. // algorithms 1 and 2
  14806. var key = buildObjectKey(num, gen, this.encryptionKey, false);
  14807. var cipherConstructor = function buildCipherCipherConstructor() {
  14808. return new ARCFourCipher(key);
  14809. };
  14810. return new CipherTransform(cipherConstructor, cipherConstructor);
  14811. }
  14812. };
  14813. return CipherTransformFactory;
  14814. })();
  14815. var ShadingType = {
  14816. FUNCTION_BASED: 1,
  14817. AXIAL: 2,
  14818. RADIAL: 3,
  14819. FREE_FORM_MESH: 4,
  14820. LATTICE_FORM_MESH: 5,
  14821. COONS_PATCH_MESH: 6,
  14822. TENSOR_PATCH_MESH: 7
  14823. };
  14824. var Pattern = (function PatternClosure() {
  14825. // Constructor should define this.getPattern
  14826. function Pattern() {
  14827. error('should not call Pattern constructor');
  14828. }
  14829. Pattern.prototype = {
  14830. // Input: current Canvas context
  14831. // Output: the appropriate fillStyle or strokeStyle
  14832. getPattern: function Pattern_getPattern(ctx) {
  14833. error('Should not call Pattern.getStyle: ' + ctx);
  14834. }
  14835. };
  14836. Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref,
  14837. res) {
  14838. var dict = isStream(shading) ? shading.dict : shading;
  14839. var type = dict.get('ShadingType');
  14840. try {
  14841. switch (type) {
  14842. case ShadingType.AXIAL:
  14843. case ShadingType.RADIAL:
  14844. // Both radial and axial shadings are handled by RadialAxial shading.
  14845. return new Shadings.RadialAxial(dict, matrix, xref, res);
  14846. case ShadingType.FREE_FORM_MESH:
  14847. case ShadingType.LATTICE_FORM_MESH:
  14848. case ShadingType.COONS_PATCH_MESH:
  14849. case ShadingType.TENSOR_PATCH_MESH:
  14850. return new Shadings.Mesh(shading, matrix, xref, res);
  14851. default:
  14852. throw new Error('Unsupported ShadingType: ' + type);
  14853. }
  14854. } catch (ex) {
  14855. if (ex instanceof MissingDataException) {
  14856. throw ex;
  14857. }
  14858. UnsupportedManager.notify(UNSUPPORTED_FEATURES.shadingPattern);
  14859. warn(ex);
  14860. return new Shadings.Dummy();
  14861. }
  14862. };
  14863. return Pattern;
  14864. })();
  14865. var Shadings = {};
  14866. // A small number to offset the first/last color stops so we can insert ones to
  14867. // support extend. Number.MIN_VALUE appears to be too small and breaks the
  14868. // extend. 1e-7 works in FF but chrome seems to use an even smaller sized number
  14869. // internally so we have to go bigger.
  14870. Shadings.SMALL_NUMBER = 1e-2;
  14871. // Radial and axial shading have very similar implementations
  14872. // If needed, the implementations can be broken into two classes
  14873. Shadings.RadialAxial = (function RadialAxialClosure() {
  14874. function RadialAxial(dict, matrix, xref, res) {
  14875. this.matrix = matrix;
  14876. this.coordsArr = dict.get('Coords');
  14877. this.shadingType = dict.get('ShadingType');
  14878. this.type = 'Pattern';
  14879. var cs = dict.get('ColorSpace', 'CS');
  14880. cs = ColorSpace.parse(cs, xref, res);
  14881. this.cs = cs;
  14882. var t0 = 0.0, t1 = 1.0;
  14883. if (dict.has('Domain')) {
  14884. var domainArr = dict.get('Domain');
  14885. t0 = domainArr[0];
  14886. t1 = domainArr[1];
  14887. }
  14888. var extendStart = false, extendEnd = false;
  14889. if (dict.has('Extend')) {
  14890. var extendArr = dict.get('Extend');
  14891. extendStart = extendArr[0];
  14892. extendEnd = extendArr[1];
  14893. }
  14894. if (this.shadingType === ShadingType.RADIAL &&
  14895. (!extendStart || !extendEnd)) {
  14896. // Radial gradient only currently works if either circle is fully within
  14897. // the other circle.
  14898. var x1 = this.coordsArr[0];
  14899. var y1 = this.coordsArr[1];
  14900. var r1 = this.coordsArr[2];
  14901. var x2 = this.coordsArr[3];
  14902. var y2 = this.coordsArr[4];
  14903. var r2 = this.coordsArr[5];
  14904. var distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  14905. if (r1 <= r2 + distance &&
  14906. r2 <= r1 + distance) {
  14907. warn('Unsupported radial gradient.');
  14908. }
  14909. }
  14910. this.extendStart = extendStart;
  14911. this.extendEnd = extendEnd;
  14912. var fnObj = dict.get('Function');
  14913. var fn = PDFFunction.parseArray(xref, fnObj);
  14914. // 10 samples seems good enough for now, but probably won't work
  14915. // if there are sharp color changes. Ideally, we would implement
  14916. // the spec faithfully and add lossless optimizations.
  14917. var diff = t1 - t0;
  14918. var step = diff / 10;
  14919. var colorStops = this.colorStops = [];
  14920. // Protect against bad domains so we don't end up in an infinte loop below.
  14921. if (t0 >= t1 || step <= 0) {
  14922. // Acrobat doesn't seem to handle these cases so we'll ignore for
  14923. // now.
  14924. info('Bad shading domain.');
  14925. return;
  14926. }
  14927. var color = new Float32Array(cs.numComps), ratio = new Float32Array(1);
  14928. var rgbColor;
  14929. for (var i = t0; i <= t1; i += step) {
  14930. ratio[0] = i;
  14931. fn(ratio, 0, color, 0);
  14932. rgbColor = cs.getRgb(color, 0);
  14933. var cssColor = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
  14934. colorStops.push([(i - t0) / diff, cssColor]);
  14935. }
  14936. var background = 'transparent';
  14937. if (dict.has('Background')) {
  14938. rgbColor = cs.getRgb(dict.get('Background'), 0);
  14939. background = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
  14940. }
  14941. if (!extendStart) {
  14942. // Insert a color stop at the front and offset the first real color stop
  14943. // so it doesn't conflict with the one we insert.
  14944. colorStops.unshift([0, background]);
  14945. colorStops[1][0] += Shadings.SMALL_NUMBER;
  14946. }
  14947. if (!extendEnd) {
  14948. // Same idea as above in extendStart but for the end.
  14949. colorStops[colorStops.length - 1][0] -= Shadings.SMALL_NUMBER;
  14950. colorStops.push([1, background]);
  14951. }
  14952. this.colorStops = colorStops;
  14953. }
  14954. RadialAxial.prototype = {
  14955. getIR: function RadialAxial_getIR() {
  14956. var coordsArr = this.coordsArr;
  14957. var shadingType = this.shadingType;
  14958. var type, p0, p1, r0, r1;
  14959. if (shadingType === ShadingType.AXIAL) {
  14960. p0 = [coordsArr[0], coordsArr[1]];
  14961. p1 = [coordsArr[2], coordsArr[3]];
  14962. r0 = null;
  14963. r1 = null;
  14964. type = 'axial';
  14965. } else if (shadingType === ShadingType.RADIAL) {
  14966. p0 = [coordsArr[0], coordsArr[1]];
  14967. p1 = [coordsArr[3], coordsArr[4]];
  14968. r0 = coordsArr[2];
  14969. r1 = coordsArr[5];
  14970. type = 'radial';
  14971. } else {
  14972. error('getPattern type unknown: ' + shadingType);
  14973. }
  14974. var matrix = this.matrix;
  14975. if (matrix) {
  14976. p0 = Util.applyTransform(p0, matrix);
  14977. p1 = Util.applyTransform(p1, matrix);
  14978. }
  14979. return ['RadialAxial', type, this.colorStops, p0, p1, r0, r1];
  14980. }
  14981. };
  14982. return RadialAxial;
  14983. })();
  14984. // All mesh shading. For now, they will be presented as set of the triangles
  14985. // to be drawn on the canvas and rgb color for each vertex.
  14986. Shadings.Mesh = (function MeshClosure() {
  14987. function MeshStreamReader(stream, context) {
  14988. this.stream = stream;
  14989. this.context = context;
  14990. this.buffer = 0;
  14991. this.bufferLength = 0;
  14992. var numComps = context.numComps;
  14993. this.tmpCompsBuf = new Float32Array(numComps);
  14994. var csNumComps = context.colorSpace.numComps;
  14995. this.tmpCsCompsBuf = context.colorFn ? new Float32Array(csNumComps) :
  14996. this.tmpCompsBuf;
  14997. }
  14998. MeshStreamReader.prototype = {
  14999. get hasData() {
  15000. if (this.stream.end) {
  15001. return this.stream.pos < this.stream.end;
  15002. }
  15003. if (this.bufferLength > 0) {
  15004. return true;
  15005. }
  15006. var nextByte = this.stream.getByte();
  15007. if (nextByte < 0) {
  15008. return false;
  15009. }
  15010. this.buffer = nextByte;
  15011. this.bufferLength = 8;
  15012. return true;
  15013. },
  15014. readBits: function MeshStreamReader_readBits(n) {
  15015. var buffer = this.buffer;
  15016. var bufferLength = this.bufferLength;
  15017. if (n === 32) {
  15018. if (bufferLength === 0) {
  15019. return ((this.stream.getByte() << 24) |
  15020. (this.stream.getByte() << 16) | (this.stream.getByte() << 8) |
  15021. this.stream.getByte()) >>> 0;
  15022. }
  15023. buffer = (buffer << 24) | (this.stream.getByte() << 16) |
  15024. (this.stream.getByte() << 8) | this.stream.getByte();
  15025. var nextByte = this.stream.getByte();
  15026. this.buffer = nextByte & ((1 << bufferLength) - 1);
  15027. return ((buffer << (8 - bufferLength)) |
  15028. ((nextByte & 0xFF) >> bufferLength)) >>> 0;
  15029. }
  15030. if (n === 8 && bufferLength === 0) {
  15031. return this.stream.getByte();
  15032. }
  15033. while (bufferLength < n) {
  15034. buffer = (buffer << 8) | this.stream.getByte();
  15035. bufferLength += 8;
  15036. }
  15037. bufferLength -= n;
  15038. this.bufferLength = bufferLength;
  15039. this.buffer = buffer & ((1 << bufferLength) - 1);
  15040. return buffer >> bufferLength;
  15041. },
  15042. align: function MeshStreamReader_align() {
  15043. this.buffer = 0;
  15044. this.bufferLength = 0;
  15045. },
  15046. readFlag: function MeshStreamReader_readFlag() {
  15047. return this.readBits(this.context.bitsPerFlag);
  15048. },
  15049. readCoordinate: function MeshStreamReader_readCoordinate() {
  15050. var bitsPerCoordinate = this.context.bitsPerCoordinate;
  15051. var xi = this.readBits(bitsPerCoordinate);
  15052. var yi = this.readBits(bitsPerCoordinate);
  15053. var decode = this.context.decode;
  15054. var scale = bitsPerCoordinate < 32 ? 1 / ((1 << bitsPerCoordinate) - 1) :
  15055. 2.3283064365386963e-10; // 2 ^ -32
  15056. return [
  15057. xi * scale * (decode[1] - decode[0]) + decode[0],
  15058. yi * scale * (decode[3] - decode[2]) + decode[2]
  15059. ];
  15060. },
  15061. readComponents: function MeshStreamReader_readComponents() {
  15062. var numComps = this.context.numComps;
  15063. var bitsPerComponent = this.context.bitsPerComponent;
  15064. var scale = bitsPerComponent < 32 ? 1 / ((1 << bitsPerComponent) - 1) :
  15065. 2.3283064365386963e-10; // 2 ^ -32
  15066. var decode = this.context.decode;
  15067. var components = this.tmpCompsBuf;
  15068. for (var i = 0, j = 4; i < numComps; i++, j += 2) {
  15069. var ci = this.readBits(bitsPerComponent);
  15070. components[i] = ci * scale * (decode[j + 1] - decode[j]) + decode[j];
  15071. }
  15072. var color = this.tmpCsCompsBuf;
  15073. if (this.context.colorFn) {
  15074. this.context.colorFn(components, 0, color, 0);
  15075. }
  15076. return this.context.colorSpace.getRgb(color, 0);
  15077. }
  15078. };
  15079. function decodeType4Shading(mesh, reader) {
  15080. var coords = mesh.coords;
  15081. var colors = mesh.colors;
  15082. var operators = [];
  15083. var ps = []; // not maintaining cs since that will match ps
  15084. var verticesLeft = 0; // assuming we have all data to start a new triangle
  15085. while (reader.hasData) {
  15086. var f = reader.readFlag();
  15087. var coord = reader.readCoordinate();
  15088. var color = reader.readComponents();
  15089. if (verticesLeft === 0) { // ignoring flags if we started a triangle
  15090. assert(0 <= f && f <= 2, 'Unknown type4 flag');
  15091. switch (f) {
  15092. case 0:
  15093. verticesLeft = 3;
  15094. break;
  15095. case 1:
  15096. ps.push(ps[ps.length - 2], ps[ps.length - 1]);
  15097. verticesLeft = 1;
  15098. break;
  15099. case 2:
  15100. ps.push(ps[ps.length - 3], ps[ps.length - 1]);
  15101. verticesLeft = 1;
  15102. break;
  15103. }
  15104. operators.push(f);
  15105. }
  15106. ps.push(coords.length);
  15107. coords.push(coord);
  15108. colors.push(color);
  15109. verticesLeft--;
  15110. reader.align();
  15111. }
  15112. mesh.figures.push({
  15113. type: 'triangles',
  15114. coords: new Int32Array(ps),
  15115. colors: new Int32Array(ps),
  15116. });
  15117. }
  15118. function decodeType5Shading(mesh, reader, verticesPerRow) {
  15119. var coords = mesh.coords;
  15120. var colors = mesh.colors;
  15121. var ps = []; // not maintaining cs since that will match ps
  15122. while (reader.hasData) {
  15123. var coord = reader.readCoordinate();
  15124. var color = reader.readComponents();
  15125. ps.push(coords.length);
  15126. coords.push(coord);
  15127. colors.push(color);
  15128. }
  15129. mesh.figures.push({
  15130. type: 'lattice',
  15131. coords: new Int32Array(ps),
  15132. colors: new Int32Array(ps),
  15133. verticesPerRow: verticesPerRow
  15134. });
  15135. }
  15136. var MIN_SPLIT_PATCH_CHUNKS_AMOUNT = 3;
  15137. var MAX_SPLIT_PATCH_CHUNKS_AMOUNT = 20;
  15138. var TRIANGLE_DENSITY = 20; // count of triangles per entire mesh bounds
  15139. var getB = (function getBClosure() {
  15140. function buildB(count) {
  15141. var lut = [];
  15142. for (var i = 0; i <= count; i++) {
  15143. var t = i / count, t_ = 1 - t;
  15144. lut.push(new Float32Array([t_ * t_ * t_, 3 * t * t_ * t_,
  15145. 3 * t * t * t_, t * t * t]));
  15146. }
  15147. return lut;
  15148. }
  15149. var cache = [];
  15150. return function getB(count) {
  15151. if (!cache[count]) {
  15152. cache[count] = buildB(count);
  15153. }
  15154. return cache[count];
  15155. };
  15156. })();
  15157. function buildFigureFromPatch(mesh, index) {
  15158. var figure = mesh.figures[index];
  15159. assert(figure.type === 'patch', 'Unexpected patch mesh figure');
  15160. var coords = mesh.coords, colors = mesh.colors;
  15161. var pi = figure.coords;
  15162. var ci = figure.colors;
  15163. var figureMinX = Math.min(coords[pi[0]][0], coords[pi[3]][0],
  15164. coords[pi[12]][0], coords[pi[15]][0]);
  15165. var figureMinY = Math.min(coords[pi[0]][1], coords[pi[3]][1],
  15166. coords[pi[12]][1], coords[pi[15]][1]);
  15167. var figureMaxX = Math.max(coords[pi[0]][0], coords[pi[3]][0],
  15168. coords[pi[12]][0], coords[pi[15]][0]);
  15169. var figureMaxY = Math.max(coords[pi[0]][1], coords[pi[3]][1],
  15170. coords[pi[12]][1], coords[pi[15]][1]);
  15171. var splitXBy = Math.ceil((figureMaxX - figureMinX) * TRIANGLE_DENSITY /
  15172. (mesh.bounds[2] - mesh.bounds[0]));
  15173. splitXBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
  15174. Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitXBy));
  15175. var splitYBy = Math.ceil((figureMaxY - figureMinY) * TRIANGLE_DENSITY /
  15176. (mesh.bounds[3] - mesh.bounds[1]));
  15177. splitYBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
  15178. Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitYBy));
  15179. var verticesPerRow = splitXBy + 1;
  15180. var figureCoords = new Int32Array((splitYBy + 1) * verticesPerRow);
  15181. var figureColors = new Int32Array((splitYBy + 1) * verticesPerRow);
  15182. var k = 0;
  15183. var cl = new Uint8Array(3), cr = new Uint8Array(3);
  15184. var c0 = colors[ci[0]], c1 = colors[ci[1]],
  15185. c2 = colors[ci[2]], c3 = colors[ci[3]];
  15186. var bRow = getB(splitYBy), bCol = getB(splitXBy);
  15187. for (var row = 0; row <= splitYBy; row++) {
  15188. cl[0] = ((c0[0] * (splitYBy - row) + c2[0] * row) / splitYBy) | 0;
  15189. cl[1] = ((c0[1] * (splitYBy - row) + c2[1] * row) / splitYBy) | 0;
  15190. cl[2] = ((c0[2] * (splitYBy - row) + c2[2] * row) / splitYBy) | 0;
  15191. cr[0] = ((c1[0] * (splitYBy - row) + c3[0] * row) / splitYBy) | 0;
  15192. cr[1] = ((c1[1] * (splitYBy - row) + c3[1] * row) / splitYBy) | 0;
  15193. cr[2] = ((c1[2] * (splitYBy - row) + c3[2] * row) / splitYBy) | 0;
  15194. for (var col = 0; col <= splitXBy; col++, k++) {
  15195. if ((row === 0 || row === splitYBy) &&
  15196. (col === 0 || col === splitXBy)) {
  15197. continue;
  15198. }
  15199. var x = 0, y = 0;
  15200. var q = 0;
  15201. for (var i = 0; i <= 3; i++) {
  15202. for (var j = 0; j <= 3; j++, q++) {
  15203. var m = bRow[row][i] * bCol[col][j];
  15204. x += coords[pi[q]][0] * m;
  15205. y += coords[pi[q]][1] * m;
  15206. }
  15207. }
  15208. figureCoords[k] = coords.length;
  15209. coords.push([x, y]);
  15210. figureColors[k] = colors.length;
  15211. var newColor = new Uint8Array(3);
  15212. newColor[0] = ((cl[0] * (splitXBy - col) + cr[0] * col) / splitXBy) | 0;
  15213. newColor[1] = ((cl[1] * (splitXBy - col) + cr[1] * col) / splitXBy) | 0;
  15214. newColor[2] = ((cl[2] * (splitXBy - col) + cr[2] * col) / splitXBy) | 0;
  15215. colors.push(newColor);
  15216. }
  15217. }
  15218. figureCoords[0] = pi[0];
  15219. figureColors[0] = ci[0];
  15220. figureCoords[splitXBy] = pi[3];
  15221. figureColors[splitXBy] = ci[1];
  15222. figureCoords[verticesPerRow * splitYBy] = pi[12];
  15223. figureColors[verticesPerRow * splitYBy] = ci[2];
  15224. figureCoords[verticesPerRow * splitYBy + splitXBy] = pi[15];
  15225. figureColors[verticesPerRow * splitYBy + splitXBy] = ci[3];
  15226. mesh.figures[index] = {
  15227. type: 'lattice',
  15228. coords: figureCoords,
  15229. colors: figureColors,
  15230. verticesPerRow: verticesPerRow
  15231. };
  15232. }
  15233. function decodeType6Shading(mesh, reader) {
  15234. // A special case of Type 7. The p11, p12, p21, p22 automatically filled
  15235. var coords = mesh.coords;
  15236. var colors = mesh.colors;
  15237. var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33
  15238. var cs = new Int32Array(4); // c00, c30, c03, c33
  15239. while (reader.hasData) {
  15240. var f = reader.readFlag();
  15241. assert(0 <= f && f <= 3, 'Unknown type6 flag');
  15242. var i, ii;
  15243. var pi = coords.length;
  15244. for (i = 0, ii = (f !== 0 ? 8 : 12); i < ii; i++) {
  15245. coords.push(reader.readCoordinate());
  15246. }
  15247. var ci = colors.length;
  15248. for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {
  15249. colors.push(reader.readComponents());
  15250. }
  15251. var tmp1, tmp2, tmp3, tmp4;
  15252. switch (f) {
  15253. case 0:
  15254. ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;
  15255. ps[ 8] = pi + 2; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;
  15256. ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 8;
  15257. ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;
  15258. cs[2] = ci + 1; cs[3] = ci + 2;
  15259. cs[0] = ci; cs[1] = ci + 3;
  15260. break;
  15261. case 1:
  15262. tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];
  15263. ps[12] = tmp4; ps[13] = pi + 0; ps[14] = pi + 1; ps[15] = pi + 2;
  15264. ps[ 8] = tmp3; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 3;
  15265. ps[ 4] = tmp2; /* calculated below */ ps[ 7] = pi + 4;
  15266. ps[ 0] = tmp1; ps[ 1] = pi + 7; ps[ 2] = pi + 6; ps[ 3] = pi + 5;
  15267. tmp1 = cs[2]; tmp2 = cs[3];
  15268. cs[2] = tmp2; cs[3] = ci;
  15269. cs[0] = tmp1; cs[1] = ci + 1;
  15270. break;
  15271. case 2:
  15272. tmp1 = ps[15];
  15273. tmp2 = ps[11];
  15274. ps[12] = ps[3]; ps[13] = pi + 0; ps[14] = pi + 1; ps[15] = pi + 2;
  15275. ps[ 8] = ps[7]; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 3;
  15276. ps[ 4] = tmp2; /* calculated below */ ps[ 7] = pi + 4;
  15277. ps[ 0] = tmp1; ps[ 1] = pi + 7; ps[ 2] = pi + 6; ps[ 3] = pi + 5;
  15278. tmp1 = cs[3];
  15279. cs[2] = cs[1]; cs[3] = ci;
  15280. cs[0] = tmp1; cs[1] = ci + 1;
  15281. break;
  15282. case 3:
  15283. ps[12] = ps[0]; ps[13] = pi + 0; ps[14] = pi + 1; ps[15] = pi + 2;
  15284. ps[ 8] = ps[1]; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 3;
  15285. ps[ 4] = ps[2]; /* calculated below */ ps[ 7] = pi + 4;
  15286. ps[ 0] = ps[3]; ps[ 1] = pi + 7; ps[ 2] = pi + 6; ps[ 3] = pi + 5;
  15287. cs[2] = cs[0]; cs[3] = ci;
  15288. cs[0] = cs[1]; cs[1] = ci + 1;
  15289. break;
  15290. }
  15291. // set p11, p12, p21, p22
  15292. ps[5] = coords.length;
  15293. coords.push([
  15294. (-4 * coords[ps[0]][0] - coords[ps[15]][0] +
  15295. 6 * (coords[ps[4]][0] + coords[ps[1]][0]) -
  15296. 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +
  15297. 3 * (coords[ps[13]][0] + coords[ps[7]][0])) / 9,
  15298. (-4 * coords[ps[0]][1] - coords[ps[15]][1] +
  15299. 6 * (coords[ps[4]][1] + coords[ps[1]][1]) -
  15300. 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +
  15301. 3 * (coords[ps[13]][1] + coords[ps[7]][1])) / 9
  15302. ]);
  15303. ps[6] = coords.length;
  15304. coords.push([
  15305. (-4 * coords[ps[3]][0] - coords[ps[12]][0] +
  15306. 6 * (coords[ps[2]][0] + coords[ps[7]][0]) -
  15307. 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +
  15308. 3 * (coords[ps[4]][0] + coords[ps[14]][0])) / 9,
  15309. (-4 * coords[ps[3]][1] - coords[ps[12]][1] +
  15310. 6 * (coords[ps[2]][1] + coords[ps[7]][1]) -
  15311. 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +
  15312. 3 * (coords[ps[4]][1] + coords[ps[14]][1])) / 9
  15313. ]);
  15314. ps[9] = coords.length;
  15315. coords.push([
  15316. (-4 * coords[ps[12]][0] - coords[ps[3]][0] +
  15317. 6 * (coords[ps[8]][0] + coords[ps[13]][0]) -
  15318. 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +
  15319. 3 * (coords[ps[11]][0] + coords[ps[1]][0])) / 9,
  15320. (-4 * coords[ps[12]][1] - coords[ps[3]][1] +
  15321. 6 * (coords[ps[8]][1] + coords[ps[13]][1]) -
  15322. 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +
  15323. 3 * (coords[ps[11]][1] + coords[ps[1]][1])) / 9
  15324. ]);
  15325. ps[10] = coords.length;
  15326. coords.push([
  15327. (-4 * coords[ps[15]][0] - coords[ps[0]][0] +
  15328. 6 * (coords[ps[11]][0] + coords[ps[14]][0]) -
  15329. 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +
  15330. 3 * (coords[ps[2]][0] + coords[ps[8]][0])) / 9,
  15331. (-4 * coords[ps[15]][1] - coords[ps[0]][1] +
  15332. 6 * (coords[ps[11]][1] + coords[ps[14]][1]) -
  15333. 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +
  15334. 3 * (coords[ps[2]][1] + coords[ps[8]][1])) / 9
  15335. ]);
  15336. mesh.figures.push({
  15337. type: 'patch',
  15338. coords: new Int32Array(ps), // making copies of ps and cs
  15339. colors: new Int32Array(cs)
  15340. });
  15341. }
  15342. }
  15343. function decodeType7Shading(mesh, reader) {
  15344. var coords = mesh.coords;
  15345. var colors = mesh.colors;
  15346. var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33
  15347. var cs = new Int32Array(4); // c00, c30, c03, c33
  15348. while (reader.hasData) {
  15349. var f = reader.readFlag();
  15350. assert(0 <= f && f <= 3, 'Unknown type7 flag');
  15351. var i, ii;
  15352. var pi = coords.length;
  15353. for (i = 0, ii = (f !== 0 ? 12 : 16); i < ii; i++) {
  15354. coords.push(reader.readCoordinate());
  15355. }
  15356. var ci = colors.length;
  15357. for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {
  15358. colors.push(reader.readComponents());
  15359. }
  15360. var tmp1, tmp2, tmp3, tmp4;
  15361. switch (f) {
  15362. case 0:
  15363. ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;
  15364. ps[ 8] = pi + 2; ps[ 9] = pi + 13; ps[10] = pi + 14; ps[11] = pi + 7;
  15365. ps[ 4] = pi + 1; ps[ 5] = pi + 12; ps[ 6] = pi + 15; ps[ 7] = pi + 8;
  15366. ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;
  15367. cs[2] = ci + 1; cs[3] = ci + 2;
  15368. cs[0] = ci; cs[1] = ci + 3;
  15369. break;
  15370. case 1:
  15371. tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];
  15372. ps[12] = tmp4; ps[13] = pi + 0; ps[14] = pi + 1; ps[15] = pi + 2;
  15373. ps[ 8] = tmp3; ps[ 9] = pi + 9; ps[10] = pi + 10; ps[11] = pi + 3;
  15374. ps[ 4] = tmp2; ps[ 5] = pi + 8; ps[ 6] = pi + 11; ps[ 7] = pi + 4;
  15375. ps[ 0] = tmp1; ps[ 1] = pi + 7; ps[ 2] = pi + 6; ps[ 3] = pi + 5;
  15376. tmp1 = cs[2]; tmp2 = cs[3];
  15377. cs[2] = tmp2; cs[3] = ci;
  15378. cs[0] = tmp1; cs[1] = ci + 1;
  15379. break;
  15380. case 2:
  15381. tmp1 = ps[15];
  15382. tmp2 = ps[11];
  15383. ps[12] = ps[3]; ps[13] = pi + 0; ps[14] = pi + 1; ps[15] = pi + 2;
  15384. ps[ 8] = ps[7]; ps[ 9] = pi + 9; ps[10] = pi + 10; ps[11] = pi + 3;
  15385. ps[ 4] = tmp2; ps[ 5] = pi + 8; ps[ 6] = pi + 11; ps[ 7] = pi + 4;
  15386. ps[ 0] = tmp1; ps[ 1] = pi + 7; ps[ 2] = pi + 6; ps[ 3] = pi + 5;
  15387. tmp1 = cs[3];
  15388. cs[2] = cs[1]; cs[3] = ci;
  15389. cs[0] = tmp1; cs[1] = ci + 1;
  15390. break;
  15391. case 3:
  15392. ps[12] = ps[0]; ps[13] = pi + 0; ps[14] = pi + 1; ps[15] = pi + 2;
  15393. ps[ 8] = ps[1]; ps[ 9] = pi + 9; ps[10] = pi + 10; ps[11] = pi + 3;
  15394. ps[ 4] = ps[2]; ps[ 5] = pi + 8; ps[ 6] = pi + 11; ps[ 7] = pi + 4;
  15395. ps[ 0] = ps[3]; ps[ 1] = pi + 7; ps[ 2] = pi + 6; ps[ 3] = pi + 5;
  15396. cs[2] = cs[0]; cs[3] = ci;
  15397. cs[0] = cs[1]; cs[1] = ci + 1;
  15398. break;
  15399. }
  15400. mesh.figures.push({
  15401. type: 'patch',
  15402. coords: new Int32Array(ps), // making copies of ps and cs
  15403. colors: new Int32Array(cs)
  15404. });
  15405. }
  15406. }
  15407. function updateBounds(mesh) {
  15408. var minX = mesh.coords[0][0], minY = mesh.coords[0][1],
  15409. maxX = minX, maxY = minY;
  15410. for (var i = 1, ii = mesh.coords.length; i < ii; i++) {
  15411. var x = mesh.coords[i][0], y = mesh.coords[i][1];
  15412. minX = minX > x ? x : minX;
  15413. minY = minY > y ? y : minY;
  15414. maxX = maxX < x ? x : maxX;
  15415. maxY = maxY < y ? y : maxY;
  15416. }
  15417. mesh.bounds = [minX, minY, maxX, maxY];
  15418. }
  15419. function packData(mesh) {
  15420. var i, ii, j, jj;
  15421. var coords = mesh.coords;
  15422. var coordsPacked = new Float32Array(coords.length * 2);
  15423. for (i = 0, j = 0, ii = coords.length; i < ii; i++) {
  15424. var xy = coords[i];
  15425. coordsPacked[j++] = xy[0];
  15426. coordsPacked[j++] = xy[1];
  15427. }
  15428. mesh.coords = coordsPacked;
  15429. var colors = mesh.colors;
  15430. var colorsPacked = new Uint8Array(colors.length * 3);
  15431. for (i = 0, j = 0, ii = colors.length; i < ii; i++) {
  15432. var c = colors[i];
  15433. colorsPacked[j++] = c[0];
  15434. colorsPacked[j++] = c[1];
  15435. colorsPacked[j++] = c[2];
  15436. }
  15437. mesh.colors = colorsPacked;
  15438. var figures = mesh.figures;
  15439. for (i = 0, ii = figures.length; i < ii; i++) {
  15440. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  15441. for (j = 0, jj = ps.length; j < jj; j++) {
  15442. ps[j] *= 2;
  15443. cs[j] *= 3;
  15444. }
  15445. }
  15446. }
  15447. function Mesh(stream, matrix, xref, res) {
  15448. assert(isStream(stream), 'Mesh data is not a stream');
  15449. var dict = stream.dict;
  15450. this.matrix = matrix;
  15451. this.shadingType = dict.get('ShadingType');
  15452. this.type = 'Pattern';
  15453. this.bbox = dict.get('BBox');
  15454. var cs = dict.get('ColorSpace', 'CS');
  15455. cs = ColorSpace.parse(cs, xref, res);
  15456. this.cs = cs;
  15457. this.background = dict.has('Background') ?
  15458. cs.getRgb(dict.get('Background'), 0) : null;
  15459. var fnObj = dict.get('Function');
  15460. var fn = fnObj ? PDFFunction.parseArray(xref, fnObj) : null;
  15461. this.coords = [];
  15462. this.colors = [];
  15463. this.figures = [];
  15464. var decodeContext = {
  15465. bitsPerCoordinate: dict.get('BitsPerCoordinate'),
  15466. bitsPerComponent: dict.get('BitsPerComponent'),
  15467. bitsPerFlag: dict.get('BitsPerFlag'),
  15468. decode: dict.get('Decode'),
  15469. colorFn: fn,
  15470. colorSpace: cs,
  15471. numComps: fn ? 1 : cs.numComps
  15472. };
  15473. var reader = new MeshStreamReader(stream, decodeContext);
  15474. var patchMesh = false;
  15475. switch (this.shadingType) {
  15476. case ShadingType.FREE_FORM_MESH:
  15477. decodeType4Shading(this, reader);
  15478. break;
  15479. case ShadingType.LATTICE_FORM_MESH:
  15480. var verticesPerRow = dict.get('VerticesPerRow') | 0;
  15481. assert(verticesPerRow >= 2, 'Invalid VerticesPerRow');
  15482. decodeType5Shading(this, reader, verticesPerRow);
  15483. break;
  15484. case ShadingType.COONS_PATCH_MESH:
  15485. decodeType6Shading(this, reader);
  15486. patchMesh = true;
  15487. break;
  15488. case ShadingType.TENSOR_PATCH_MESH:
  15489. decodeType7Shading(this, reader);
  15490. patchMesh = true;
  15491. break;
  15492. default:
  15493. error('Unsupported mesh type.');
  15494. break;
  15495. }
  15496. if (patchMesh) {
  15497. // dirty bounds calculation for determining, how dense shall be triangles
  15498. updateBounds(this);
  15499. for (var i = 0, ii = this.figures.length; i < ii; i++) {
  15500. buildFigureFromPatch(this, i);
  15501. }
  15502. }
  15503. // calculate bounds
  15504. updateBounds(this);
  15505. packData(this);
  15506. }
  15507. Mesh.prototype = {
  15508. getIR: function Mesh_getIR() {
  15509. return ['Mesh', this.shadingType, this.coords, this.colors, this.figures,
  15510. this.bounds, this.matrix, this.bbox, this.background];
  15511. }
  15512. };
  15513. return Mesh;
  15514. })();
  15515. Shadings.Dummy = (function DummyClosure() {
  15516. function Dummy() {
  15517. this.type = 'Pattern';
  15518. }
  15519. Dummy.prototype = {
  15520. getIR: function Dummy_getIR() {
  15521. return ['Dummy'];
  15522. }
  15523. };
  15524. return Dummy;
  15525. })();
  15526. function getTilingPatternIR(operatorList, dict, args) {
  15527. var matrix = dict.get('Matrix');
  15528. var bbox = dict.get('BBox');
  15529. var xstep = dict.get('XStep');
  15530. var ystep = dict.get('YStep');
  15531. var paintType = dict.get('PaintType');
  15532. var tilingType = dict.get('TilingType');
  15533. return [
  15534. 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep,
  15535. paintType, tilingType
  15536. ];
  15537. }
  15538. var PartialEvaluator = (function PartialEvaluatorClosure() {
  15539. function PartialEvaluator(pdfManager, xref, handler, pageIndex,
  15540. uniquePrefix, idCounters, fontCache) {
  15541. this.pdfManager = pdfManager;
  15542. this.xref = xref;
  15543. this.handler = handler;
  15544. this.pageIndex = pageIndex;
  15545. this.uniquePrefix = uniquePrefix;
  15546. this.idCounters = idCounters;
  15547. this.fontCache = fontCache;
  15548. }
  15549. // Trying to minimize Date.now() usage and check every 100 time
  15550. var TIME_SLOT_DURATION_MS = 20;
  15551. var CHECK_TIME_EVERY = 100;
  15552. function TimeSlotManager() {
  15553. this.reset();
  15554. }
  15555. TimeSlotManager.prototype = {
  15556. check: function TimeSlotManager_check() {
  15557. if (++this.checked < CHECK_TIME_EVERY) {
  15558. return false;
  15559. }
  15560. this.checked = 0;
  15561. return this.endTime <= Date.now();
  15562. },
  15563. reset: function TimeSlotManager_reset() {
  15564. this.endTime = Date.now() + TIME_SLOT_DURATION_MS;
  15565. this.checked = 0;
  15566. }
  15567. };
  15568. var deferred = Promise.resolve();
  15569. var TILING_PATTERN = 1, SHADING_PATTERN = 2;
  15570. PartialEvaluator.prototype = {
  15571. hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {
  15572. if (!isDict(resources)) {
  15573. return false;
  15574. }
  15575. var processed = Object.create(null);
  15576. if (resources.objId) {
  15577. processed[resources.objId] = true;
  15578. }
  15579. var nodes = [resources];
  15580. while (nodes.length) {
  15581. var key;
  15582. var node = nodes.shift();
  15583. // First check the current resources for blend modes.
  15584. var graphicStates = node.get('ExtGState');
  15585. if (isDict(graphicStates)) {
  15586. graphicStates = graphicStates.getAll();
  15587. for (key in graphicStates) {
  15588. var graphicState = graphicStates[key];
  15589. var bm = graphicState['BM'];
  15590. if (isName(bm) && bm.name !== 'Normal') {
  15591. return true;
  15592. }
  15593. }
  15594. }
  15595. // Descend into the XObjects to look for more resources and blend modes.
  15596. var xObjects = node.get('XObject');
  15597. if (!isDict(xObjects)) {
  15598. continue;
  15599. }
  15600. xObjects = xObjects.getAll();
  15601. for (key in xObjects) {
  15602. var xObject = xObjects[key];
  15603. if (!isStream(xObject)) {
  15604. continue;
  15605. }
  15606. if (xObject.dict.objId) {
  15607. if (processed[xObject.dict.objId]) {
  15608. // stream has objId and is processed already
  15609. continue;
  15610. }
  15611. processed[xObject.dict.objId] = true;
  15612. }
  15613. var xResources = xObject.dict.get('Resources');
  15614. // Checking objId to detect an infinite loop.
  15615. if (isDict(xResources) &&
  15616. (!xResources.objId || !processed[xResources.objId])) {
  15617. nodes.push(xResources);
  15618. if (xResources.objId) {
  15619. processed[xResources.objId] = true;
  15620. }
  15621. }
  15622. }
  15623. }
  15624. return false;
  15625. },
  15626. buildFormXObject: function PartialEvaluator_buildFormXObject(resources,
  15627. xobj, smask,
  15628. operatorList,
  15629. initialState) {
  15630. var matrix = xobj.dict.getArray('Matrix');
  15631. var bbox = xobj.dict.getArray('BBox');
  15632. var group = xobj.dict.get('Group');
  15633. if (group) {
  15634. var groupOptions = {
  15635. matrix: matrix,
  15636. bbox: bbox,
  15637. smask: smask,
  15638. isolated: false,
  15639. knockout: false
  15640. };
  15641. var groupSubtype = group.get('S');
  15642. var colorSpace;
  15643. if (isName(groupSubtype) && groupSubtype.name === 'Transparency') {
  15644. groupOptions.isolated = (group.get('I') || false);
  15645. groupOptions.knockout = (group.get('K') || false);
  15646. colorSpace = (group.has('CS') ?
  15647. ColorSpace.parse(group.get('CS'), this.xref, resources) : null);
  15648. }
  15649. if (smask && smask.backdrop) {
  15650. colorSpace = colorSpace || ColorSpace.singletons.rgb;
  15651. smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
  15652. }
  15653. operatorList.addOp(OPS.beginGroup, [groupOptions]);
  15654. }
  15655. operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]);
  15656. return this.getOperatorList(xobj,
  15657. (xobj.dict.get('Resources') || resources), operatorList, initialState).
  15658. then(function () {
  15659. operatorList.addOp(OPS.paintFormXObjectEnd, []);
  15660. if (group) {
  15661. operatorList.addOp(OPS.endGroup, [groupOptions]);
  15662. }
  15663. });
  15664. },
  15665. buildPaintImageXObject:
  15666. function PartialEvaluator_buildPaintImageXObject(resources, image,
  15667. inline, operatorList,
  15668. cacheKey, imageCache) {
  15669. var self = this;
  15670. var dict = image.dict;
  15671. var w = dict.get('Width', 'W');
  15672. var h = dict.get('Height', 'H');
  15673. if (!(w && isNum(w)) || !(h && isNum(h))) {
  15674. warn('Image dimensions are missing, or not numbers.');
  15675. return;
  15676. }
  15677. if (PDFJS.maxImageSize !== -1 && w * h > PDFJS.maxImageSize) {
  15678. warn('Image exceeded maximum allowed size and was removed.');
  15679. return;
  15680. }
  15681. var imageMask = (dict.get('ImageMask', 'IM') || false);
  15682. var imgData, args;
  15683. if (imageMask) {
  15684. // This depends on a tmpCanvas being filled with the
  15685. // current fillStyle, such that processing the pixel
  15686. // data can't be done here. Instead of creating a
  15687. // complete PDFImage, only read the information needed
  15688. // for later.
  15689. var width = dict.get('Width', 'W');
  15690. var height = dict.get('Height', 'H');
  15691. var bitStrideLength = (width + 7) >> 3;
  15692. var imgArray = image.getBytes(bitStrideLength * height);
  15693. var decode = dict.get('Decode', 'D');
  15694. var inverseDecode = (!!decode && decode[0] > 0);
  15695. imgData = PDFImage.createMask(imgArray, width, height,
  15696. image instanceof DecodeStream,
  15697. inverseDecode);
  15698. imgData.cached = true;
  15699. args = [imgData];
  15700. operatorList.addOp(OPS.paintImageMaskXObject, args);
  15701. if (cacheKey) {
  15702. imageCache[cacheKey] = {
  15703. fn: OPS.paintImageMaskXObject,
  15704. args: args
  15705. };
  15706. }
  15707. return;
  15708. }
  15709. var softMask = (dict.get('SMask', 'SM') || false);
  15710. var mask = (dict.get('Mask') || false);
  15711. var SMALL_IMAGE_DIMENSIONS = 200;
  15712. // Inlining small images into the queue as RGB data
  15713. if (inline && !softMask && !mask && !(image instanceof JpegStream) &&
  15714. (w + h) < SMALL_IMAGE_DIMENSIONS) {
  15715. var imageObj = new PDFImage(this.xref, resources, image,
  15716. inline, null, null);
  15717. // We force the use of RGBA_32BPP images here, because we can't handle
  15718. // any other kind.
  15719. imgData = imageObj.createImageData(/* forceRGBA = */ true);
  15720. operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);
  15721. return;
  15722. }
  15723. // If there is no imageMask, create the PDFImage and a lot
  15724. // of image processing can be done here.
  15725. var uniquePrefix = (this.uniquePrefix || '');
  15726. var objId = 'img_' + uniquePrefix + (++this.idCounters.obj);
  15727. operatorList.addDependency(objId);
  15728. args = [objId, w, h];
  15729. if (!softMask && !mask && image instanceof JpegStream &&
  15730. image.isNativelySupported(this.xref, resources)) {
  15731. // These JPEGs don't need any more processing so we can just send it.
  15732. operatorList.addOp(OPS.paintJpegXObject, args);
  15733. this.handler.send('obj',
  15734. [objId, this.pageIndex, 'JpegStream', image.getIR()]);
  15735. return;
  15736. }
  15737. PDFImage.buildImage(self.handler, self.xref, resources, image, inline).
  15738. then(function(imageObj) {
  15739. var imgData = imageObj.createImageData(/* forceRGBA = */ false);
  15740. self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData],
  15741. [imgData.data.buffer]);
  15742. }).then(undefined, function (reason) {
  15743. warn('Unable to decode image: ' + reason);
  15744. self.handler.send('obj', [objId, self.pageIndex, 'Image', null]);
  15745. });
  15746. operatorList.addOp(OPS.paintImageXObject, args);
  15747. if (cacheKey) {
  15748. imageCache[cacheKey] = {
  15749. fn: OPS.paintImageXObject,
  15750. args: args
  15751. };
  15752. }
  15753. },
  15754. handleSMask: function PartialEvaluator_handleSmask(smask, resources,
  15755. operatorList,
  15756. stateManager) {
  15757. var smaskContent = smask.get('G');
  15758. var smaskOptions = {
  15759. subtype: smask.get('S').name,
  15760. backdrop: smask.get('BC')
  15761. };
  15762. return this.buildFormXObject(resources, smaskContent, smaskOptions,
  15763. operatorList, stateManager.state.clone());
  15764. },
  15765. handleTilingType:
  15766. function PartialEvaluator_handleTilingType(fn, args, resources,
  15767. pattern, patternDict,
  15768. operatorList) {
  15769. // Create an IR of the pattern code.
  15770. var tilingOpList = new OperatorList();
  15771. // Merge the available resources, to prevent issues when the patternDict
  15772. // is missing some /Resources entries (fixes issue6541.pdf).
  15773. var resourcesArray = [patternDict.get('Resources'), resources];
  15774. var patternResources = Dict.merge(this.xref, resourcesArray);
  15775. return this.getOperatorList(pattern, patternResources, tilingOpList).then(
  15776. function () {
  15777. // Add the dependencies to the parent operator list so they are
  15778. // resolved before sub operator list is executed synchronously.
  15779. operatorList.addDependencies(tilingOpList.dependencies);
  15780. operatorList.addOp(fn, getTilingPatternIR({
  15781. fnArray: tilingOpList.fnArray,
  15782. argsArray: tilingOpList.argsArray
  15783. }, patternDict, args));
  15784. });
  15785. },
  15786. handleSetFont:
  15787. function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef,
  15788. operatorList, state) {
  15789. // TODO(mack): Not needed?
  15790. var fontName;
  15791. if (fontArgs) {
  15792. fontArgs = fontArgs.slice();
  15793. fontName = fontArgs[0].name;
  15794. }
  15795. var self = this;
  15796. return this.loadFont(fontName, fontRef, this.xref, resources).then(
  15797. function (translated) {
  15798. if (!translated.font.isType3Font) {
  15799. return translated;
  15800. }
  15801. return translated.loadType3Data(self, resources, operatorList).then(
  15802. function () {
  15803. return translated;
  15804. });
  15805. }).then(function (translated) {
  15806. state.font = translated.font;
  15807. translated.send(self.handler);
  15808. return translated.loadedName;
  15809. });
  15810. },
  15811. handleText: function PartialEvaluator_handleText(chars, state) {
  15812. var font = state.font;
  15813. var glyphs = font.charsToGlyphs(chars);
  15814. var isAddToPathSet = !!(state.textRenderingMode &
  15815. TextRenderingMode.ADD_TO_PATH_FLAG);
  15816. if (font.data && (isAddToPathSet || PDFJS.disableFontFace)) {
  15817. var buildPath = function (fontChar) {
  15818. if (!font.renderer.hasBuiltPath(fontChar)) {
  15819. var path = font.renderer.getPathJs(fontChar);
  15820. this.handler.send('commonobj', [
  15821. font.loadedName + '_path_' + fontChar,
  15822. 'FontPath',
  15823. path
  15824. ]);
  15825. }
  15826. }.bind(this);
  15827. for (var i = 0, ii = glyphs.length; i < ii; i++) {
  15828. var glyph = glyphs[i];
  15829. if (glyph === null) {
  15830. continue;
  15831. }
  15832. buildPath(glyph.fontChar);
  15833. // If the glyph has an accent we need to build a path for its
  15834. // fontChar too, otherwise CanvasGraphics_paintChar will fail.
  15835. var accent = glyph.accent;
  15836. if (accent && accent.fontChar) {
  15837. buildPath(accent.fontChar);
  15838. }
  15839. }
  15840. }
  15841. return glyphs;
  15842. },
  15843. setGState: function PartialEvaluator_setGState(resources, gState,
  15844. operatorList, xref,
  15845. stateManager) {
  15846. // This array holds the converted/processed state data.
  15847. var gStateObj = [];
  15848. var gStateMap = gState.map;
  15849. var self = this;
  15850. var promise = Promise.resolve();
  15851. for (var key in gStateMap) {
  15852. var value = gStateMap[key];
  15853. switch (key) {
  15854. case 'Type':
  15855. break;
  15856. case 'LW':
  15857. case 'LC':
  15858. case 'LJ':
  15859. case 'ML':
  15860. case 'D':
  15861. case 'RI':
  15862. case 'FL':
  15863. case 'CA':
  15864. case 'ca':
  15865. gStateObj.push([key, value]);
  15866. break;
  15867. case 'Font':
  15868. promise = promise.then(function () {
  15869. return self.handleSetFont(resources, null, value[0],
  15870. operatorList, stateManager.state).
  15871. then(function (loadedName) {
  15872. operatorList.addDependency(loadedName);
  15873. gStateObj.push([key, [loadedName, value[1]]]);
  15874. });
  15875. });
  15876. break;
  15877. case 'BM':
  15878. gStateObj.push([key, value]);
  15879. break;
  15880. case 'SMask':
  15881. if (isName(value) && value.name === 'None') {
  15882. gStateObj.push([key, false]);
  15883. break;
  15884. }
  15885. var dict = xref.fetchIfRef(value);
  15886. if (isDict(dict)) {
  15887. promise = promise.then(function () {
  15888. return self.handleSMask(dict, resources, operatorList,
  15889. stateManager);
  15890. });
  15891. gStateObj.push([key, true]);
  15892. } else {
  15893. warn('Unsupported SMask type');
  15894. }
  15895. break;
  15896. // Only generate info log messages for the following since
  15897. // they are unlikely to have a big impact on the rendering.
  15898. case 'OP':
  15899. case 'op':
  15900. case 'OPM':
  15901. case 'BG':
  15902. case 'BG2':
  15903. case 'UCR':
  15904. case 'UCR2':
  15905. case 'TR':
  15906. case 'TR2':
  15907. case 'HT':
  15908. case 'SM':
  15909. case 'SA':
  15910. case 'AIS':
  15911. case 'TK':
  15912. // TODO implement these operators.
  15913. info('graphic state operator ' + key);
  15914. break;
  15915. default:
  15916. info('Unknown graphic state operator ' + key);
  15917. break;
  15918. }
  15919. }
  15920. return promise.then(function () {
  15921. if (gStateObj.length >= 0) {
  15922. operatorList.addOp(OPS.setGState, [gStateObj]);
  15923. }
  15924. });
  15925. },
  15926. loadFont: function PartialEvaluator_loadFont(fontName, font, xref,
  15927. resources) {
  15928. function errorFont() {
  15929. return Promise.resolve(new TranslatedFont('g_font_error',
  15930. new ErrorFont('Font ' + fontName + ' is not available'), font));
  15931. }
  15932. var fontRef;
  15933. if (font) { // Loading by ref.
  15934. assert(isRef(font));
  15935. fontRef = font;
  15936. } else { // Loading by name.
  15937. var fontRes = resources.get('Font');
  15938. if (fontRes) {
  15939. fontRef = fontRes.getRaw(fontName);
  15940. } else {
  15941. warn('fontRes not available');
  15942. return errorFont();
  15943. }
  15944. }
  15945. if (!fontRef) {
  15946. warn('fontRef not available');
  15947. return errorFont();
  15948. }
  15949. if (this.fontCache.has(fontRef)) {
  15950. return this.fontCache.get(fontRef);
  15951. }
  15952. font = xref.fetchIfRef(fontRef);
  15953. if (!isDict(font)) {
  15954. return errorFont();
  15955. }
  15956. // We are holding font.translated references just for fontRef that are not
  15957. // dictionaries (Dict). See explanation below.
  15958. if (font.translated) {
  15959. return font.translated;
  15960. }
  15961. var fontCapability = createPromiseCapability();
  15962. var preEvaluatedFont = this.preEvaluateFont(font, xref);
  15963. var descriptor = preEvaluatedFont.descriptor;
  15964. var fontID = fontRef.num + '_' + fontRef.gen;
  15965. if (isDict(descriptor)) {
  15966. if (!descriptor.fontAliases) {
  15967. descriptor.fontAliases = Object.create(null);
  15968. }
  15969. var fontAliases = descriptor.fontAliases;
  15970. var hash = preEvaluatedFont.hash;
  15971. if (fontAliases[hash]) {
  15972. var aliasFontRef = fontAliases[hash].aliasRef;
  15973. if (aliasFontRef && this.fontCache.has(aliasFontRef)) {
  15974. this.fontCache.putAlias(fontRef, aliasFontRef);
  15975. return this.fontCache.get(fontRef);
  15976. }
  15977. }
  15978. if (!fontAliases[hash]) {
  15979. fontAliases[hash] = {
  15980. fontID: Font.getFontID()
  15981. };
  15982. }
  15983. fontAliases[hash].aliasRef = fontRef;
  15984. fontID = fontAliases[hash].fontID;
  15985. }
  15986. // Workaround for bad PDF generators that don't reference fonts
  15987. // properly, i.e. by not using an object identifier.
  15988. // Check if the fontRef is a Dict (as opposed to a standard object),
  15989. // in which case we don't cache the font and instead reference it by
  15990. // fontName in font.loadedName below.
  15991. var fontRefIsDict = isDict(fontRef);
  15992. if (!fontRefIsDict) {
  15993. this.fontCache.put(fontRef, fontCapability.promise);
  15994. }
  15995. // Keep track of each font we translated so the caller can
  15996. // load them asynchronously before calling display on a page.
  15997. font.loadedName = 'g_font_' + (fontRefIsDict ?
  15998. fontName.replace(/\W/g, '') : fontID);
  15999. font.translated = fontCapability.promise;
  16000. // TODO move promises into translate font
  16001. var translatedPromise;
  16002. try {
  16003. translatedPromise = Promise.resolve(
  16004. this.translateFont(preEvaluatedFont, xref));
  16005. } catch (e) {
  16006. translatedPromise = Promise.reject(e);
  16007. }
  16008. translatedPromise.then(function (translatedFont) {
  16009. if (translatedFont.fontType !== undefined) {
  16010. var xrefFontStats = xref.stats.fontTypes;
  16011. xrefFontStats[translatedFont.fontType] = true;
  16012. }
  16013. fontCapability.resolve(new TranslatedFont(font.loadedName,
  16014. translatedFont, font));
  16015. }, function (reason) {
  16016. // TODO fontCapability.reject?
  16017. UnsupportedManager.notify(UNSUPPORTED_FEATURES.font);
  16018. try {
  16019. // error, but it's still nice to have font type reported
  16020. var descriptor = preEvaluatedFont.descriptor;
  16021. var fontFile3 = descriptor && descriptor.get('FontFile3');
  16022. var subtype = fontFile3 && fontFile3.get('Subtype');
  16023. var fontType = getFontType(preEvaluatedFont.type,
  16024. subtype && subtype.name);
  16025. var xrefFontStats = xref.stats.fontTypes;
  16026. xrefFontStats[fontType] = true;
  16027. } catch (ex) { }
  16028. fontCapability.resolve(new TranslatedFont(font.loadedName,
  16029. new ErrorFont(reason instanceof Error ? reason.message : reason),
  16030. font));
  16031. });
  16032. return fontCapability.promise;
  16033. },
  16034. buildPath: function PartialEvaluator_buildPath(operatorList, fn, args) {
  16035. var lastIndex = operatorList.length - 1;
  16036. if (!args) {
  16037. args = [];
  16038. }
  16039. if (lastIndex < 0 ||
  16040. operatorList.fnArray[lastIndex] !== OPS.constructPath) {
  16041. operatorList.addOp(OPS.constructPath, [[fn], args]);
  16042. } else {
  16043. var opArgs = operatorList.argsArray[lastIndex];
  16044. opArgs[0].push(fn);
  16045. Array.prototype.push.apply(opArgs[1], args);
  16046. }
  16047. },
  16048. handleColorN: function PartialEvaluator_handleColorN(operatorList, fn, args,
  16049. cs, patterns, resources, xref) {
  16050. // compile tiling patterns
  16051. var patternName = args[args.length - 1];
  16052. // SCN/scn applies patterns along with normal colors
  16053. var pattern;
  16054. if (isName(patternName) &&
  16055. (pattern = patterns.get(patternName.name))) {
  16056. var dict = (isStream(pattern) ? pattern.dict : pattern);
  16057. var typeNum = dict.get('PatternType');
  16058. if (typeNum === TILING_PATTERN) {
  16059. var color = cs.base ? cs.base.getRgb(args, 0) : null;
  16060. return this.handleTilingType(fn, color, resources, pattern,
  16061. dict, operatorList);
  16062. } else if (typeNum === SHADING_PATTERN) {
  16063. var shading = dict.get('Shading');
  16064. var matrix = dict.get('Matrix');
  16065. pattern = Pattern.parseShading(shading, matrix, xref, resources);
  16066. operatorList.addOp(fn, pattern.getIR());
  16067. return Promise.resolve();
  16068. } else {
  16069. return Promise.reject('Unknown PatternType: ' + typeNum);
  16070. }
  16071. }
  16072. // TODO shall we fail here?
  16073. operatorList.addOp(fn, args);
  16074. return Promise.resolve();
  16075. },
  16076. getOperatorList: function PartialEvaluator_getOperatorList(stream,
  16077. resources,
  16078. operatorList,
  16079. initialState) {
  16080. var self = this;
  16081. var xref = this.xref;
  16082. var imageCache = {};
  16083. assert(operatorList);
  16084. resources = (resources || Dict.empty);
  16085. var xobjs = (resources.get('XObject') || Dict.empty);
  16086. var patterns = (resources.get('Pattern') || Dict.empty);
  16087. var stateManager = new StateManager(initialState || new EvalState());
  16088. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  16089. var timeSlotManager = new TimeSlotManager();
  16090. return new Promise(function next(resolve, reject) {
  16091. timeSlotManager.reset();
  16092. var stop, operation = {}, i, ii, cs;
  16093. while (!(stop = timeSlotManager.check())) {
  16094. // The arguments parsed by read() are used beyond this loop, so we
  16095. // cannot reuse the same array on each iteration. Therefore we pass
  16096. // in |null| as the initial value (see the comment on
  16097. // EvaluatorPreprocessor_read() for why).
  16098. operation.args = null;
  16099. if (!(preprocessor.read(operation))) {
  16100. break;
  16101. }
  16102. var args = operation.args;
  16103. var fn = operation.fn;
  16104. switch (fn | 0) {
  16105. case OPS.paintXObject:
  16106. if (args[0].code) {
  16107. break;
  16108. }
  16109. // eagerly compile XForm objects
  16110. var name = args[0].name;
  16111. if (!name) {
  16112. warn('XObject must be referred to by name.');
  16113. continue;
  16114. }
  16115. if (imageCache[name] !== undefined) {
  16116. operatorList.addOp(imageCache[name].fn, imageCache[name].args);
  16117. args = null;
  16118. continue;
  16119. }
  16120. var xobj = xobjs.get(name);
  16121. if (xobj) {
  16122. assert(isStream(xobj), 'XObject should be a stream');
  16123. var type = xobj.dict.get('Subtype');
  16124. assert(isName(type),
  16125. 'XObject should have a Name subtype');
  16126. if (type.name === 'Form') {
  16127. stateManager.save();
  16128. return self.buildFormXObject(resources, xobj, null,
  16129. operatorList,
  16130. stateManager.state.clone()).
  16131. then(function () {
  16132. stateManager.restore();
  16133. next(resolve, reject);
  16134. }, reject);
  16135. } else if (type.name === 'Image') {
  16136. self.buildPaintImageXObject(resources, xobj, false,
  16137. operatorList, name, imageCache);
  16138. args = null;
  16139. continue;
  16140. } else if (type.name === 'PS') {
  16141. // PostScript XObjects are unused when viewing documents.
  16142. // See section 4.7.1 of Adobe's PDF reference.
  16143. info('Ignored XObject subtype PS');
  16144. continue;
  16145. } else {
  16146. error('Unhandled XObject subtype ' + type.name);
  16147. }
  16148. }
  16149. break;
  16150. case OPS.setFont:
  16151. var fontSize = args[1];
  16152. // eagerly collect all fonts
  16153. return self.handleSetFont(resources, args, null,
  16154. operatorList, stateManager.state).
  16155. then(function (loadedName) {
  16156. operatorList.addDependency(loadedName);
  16157. operatorList.addOp(OPS.setFont, [loadedName, fontSize]);
  16158. next(resolve, reject);
  16159. }, reject);
  16160. case OPS.endInlineImage:
  16161. var cacheKey = args[0].cacheKey;
  16162. if (cacheKey) {
  16163. var cacheEntry = imageCache[cacheKey];
  16164. if (cacheEntry !== undefined) {
  16165. operatorList.addOp(cacheEntry.fn, cacheEntry.args);
  16166. args = null;
  16167. continue;
  16168. }
  16169. }
  16170. self.buildPaintImageXObject(resources, args[0], true,
  16171. operatorList, cacheKey, imageCache);
  16172. args = null;
  16173. continue;
  16174. case OPS.showText:
  16175. args[0] = self.handleText(args[0], stateManager.state);
  16176. break;
  16177. case OPS.showSpacedText:
  16178. var arr = args[0];
  16179. var combinedGlyphs = [];
  16180. var arrLength = arr.length;
  16181. var state = stateManager.state;
  16182. for (i = 0; i < arrLength; ++i) {
  16183. var arrItem = arr[i];
  16184. if (isString(arrItem)) {
  16185. Array.prototype.push.apply(combinedGlyphs,
  16186. self.handleText(arrItem, state));
  16187. } else if (isNum(arrItem)) {
  16188. combinedGlyphs.push(arrItem);
  16189. }
  16190. }
  16191. args[0] = combinedGlyphs;
  16192. fn = OPS.showText;
  16193. break;
  16194. case OPS.nextLineShowText:
  16195. operatorList.addOp(OPS.nextLine);
  16196. args[0] = self.handleText(args[0], stateManager.state);
  16197. fn = OPS.showText;
  16198. break;
  16199. case OPS.nextLineSetSpacingShowText:
  16200. operatorList.addOp(OPS.nextLine);
  16201. operatorList.addOp(OPS.setWordSpacing, [args.shift()]);
  16202. operatorList.addOp(OPS.setCharSpacing, [args.shift()]);
  16203. args[0] = self.handleText(args[0], stateManager.state);
  16204. fn = OPS.showText;
  16205. break;
  16206. case OPS.setTextRenderingMode:
  16207. stateManager.state.textRenderingMode = args[0];
  16208. break;
  16209. case OPS.setFillColorSpace:
  16210. stateManager.state.fillColorSpace =
  16211. ColorSpace.parse(args[0], xref, resources);
  16212. continue;
  16213. case OPS.setStrokeColorSpace:
  16214. stateManager.state.strokeColorSpace =
  16215. ColorSpace.parse(args[0], xref, resources);
  16216. continue;
  16217. case OPS.setFillColor:
  16218. cs = stateManager.state.fillColorSpace;
  16219. args = cs.getRgb(args, 0);
  16220. fn = OPS.setFillRGBColor;
  16221. break;
  16222. case OPS.setStrokeColor:
  16223. cs = stateManager.state.strokeColorSpace;
  16224. args = cs.getRgb(args, 0);
  16225. fn = OPS.setStrokeRGBColor;
  16226. break;
  16227. case OPS.setFillGray:
  16228. stateManager.state.fillColorSpace = ColorSpace.singletons.gray;
  16229. args = ColorSpace.singletons.gray.getRgb(args, 0);
  16230. fn = OPS.setFillRGBColor;
  16231. break;
  16232. case OPS.setStrokeGray:
  16233. stateManager.state.strokeColorSpace = ColorSpace.singletons.gray;
  16234. args = ColorSpace.singletons.gray.getRgb(args, 0);
  16235. fn = OPS.setStrokeRGBColor;
  16236. break;
  16237. case OPS.setFillCMYKColor:
  16238. stateManager.state.fillColorSpace = ColorSpace.singletons.cmyk;
  16239. args = ColorSpace.singletons.cmyk.getRgb(args, 0);
  16240. fn = OPS.setFillRGBColor;
  16241. break;
  16242. case OPS.setStrokeCMYKColor:
  16243. stateManager.state.strokeColorSpace = ColorSpace.singletons.cmyk;
  16244. args = ColorSpace.singletons.cmyk.getRgb(args, 0);
  16245. fn = OPS.setStrokeRGBColor;
  16246. break;
  16247. case OPS.setFillRGBColor:
  16248. stateManager.state.fillColorSpace = ColorSpace.singletons.rgb;
  16249. args = ColorSpace.singletons.rgb.getRgb(args, 0);
  16250. break;
  16251. case OPS.setStrokeRGBColor:
  16252. stateManager.state.strokeColorSpace = ColorSpace.singletons.rgb;
  16253. args = ColorSpace.singletons.rgb.getRgb(args, 0);
  16254. break;
  16255. case OPS.setFillColorN:
  16256. cs = stateManager.state.fillColorSpace;
  16257. if (cs.name === 'Pattern') {
  16258. return self.handleColorN(operatorList, OPS.setFillColorN,
  16259. args, cs, patterns, resources, xref).then(function() {
  16260. next(resolve, reject);
  16261. }, reject);
  16262. }
  16263. args = cs.getRgb(args, 0);
  16264. fn = OPS.setFillRGBColor;
  16265. break;
  16266. case OPS.setStrokeColorN:
  16267. cs = stateManager.state.strokeColorSpace;
  16268. if (cs.name === 'Pattern') {
  16269. return self.handleColorN(operatorList, OPS.setStrokeColorN,
  16270. args, cs, patterns, resources, xref).then(function() {
  16271. next(resolve, reject);
  16272. }, reject);
  16273. }
  16274. args = cs.getRgb(args, 0);
  16275. fn = OPS.setStrokeRGBColor;
  16276. break;
  16277. case OPS.shadingFill:
  16278. var shadingRes = resources.get('Shading');
  16279. if (!shadingRes) {
  16280. error('No shading resource found');
  16281. }
  16282. var shading = shadingRes.get(args[0].name);
  16283. if (!shading) {
  16284. error('No shading object found');
  16285. }
  16286. var shadingFill = Pattern.parseShading(shading, null, xref,
  16287. resources);
  16288. var patternIR = shadingFill.getIR();
  16289. args = [patternIR];
  16290. fn = OPS.shadingFill;
  16291. break;
  16292. case OPS.setGState:
  16293. var dictName = args[0];
  16294. var extGState = resources.get('ExtGState');
  16295. if (!isDict(extGState) || !extGState.has(dictName.name)) {
  16296. break;
  16297. }
  16298. var gState = extGState.get(dictName.name);
  16299. return self.setGState(resources, gState, operatorList, xref,
  16300. stateManager).then(function() {
  16301. next(resolve, reject);
  16302. }, reject);
  16303. case OPS.moveTo:
  16304. case OPS.lineTo:
  16305. case OPS.curveTo:
  16306. case OPS.curveTo2:
  16307. case OPS.curveTo3:
  16308. case OPS.closePath:
  16309. self.buildPath(operatorList, fn, args);
  16310. continue;
  16311. case OPS.rectangle:
  16312. self.buildPath(operatorList, fn, args);
  16313. continue;
  16314. case OPS.markPoint:
  16315. case OPS.markPointProps:
  16316. case OPS.beginMarkedContent:
  16317. case OPS.beginMarkedContentProps:
  16318. case OPS.endMarkedContent:
  16319. case OPS.beginCompat:
  16320. case OPS.endCompat:
  16321. // Ignore operators where the corresponding handlers are known to
  16322. // be no-op in CanvasGraphics (display/canvas.js). This prevents
  16323. // serialization errors and is also a bit more efficient.
  16324. // We could also try to serialize all objects in a general way,
  16325. // e.g. as done in https://github.com/mozilla/pdf.js/pull/6266,
  16326. // but doing so is meaningless without knowing the semantics.
  16327. continue;
  16328. default:
  16329. // Note: Let's hope that the ignored operator does not have any
  16330. // non-serializable arguments, otherwise postMessage will throw
  16331. // "An object could not be cloned.".
  16332. }
  16333. operatorList.addOp(fn, args);
  16334. }
  16335. if (stop) {
  16336. deferred.then(function () {
  16337. next(resolve, reject);
  16338. });
  16339. return;
  16340. }
  16341. // Some PDFs don't close all restores inside object/form.
  16342. // Closing those for them.
  16343. for (i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
  16344. operatorList.addOp(OPS.restore, []);
  16345. }
  16346. resolve();
  16347. });
  16348. },
  16349. getTextContent: function PartialEvaluator_getTextContent(stream, resources,
  16350. stateManager) {
  16351. stateManager = (stateManager || new StateManager(new TextState()));
  16352. var textContent = {
  16353. items: [],
  16354. styles: Object.create(null)
  16355. };
  16356. var bidiTexts = textContent.items;
  16357. var SPACE_FACTOR = 0.3;
  16358. var MULTI_SPACE_FACTOR = 1.5;
  16359. var self = this;
  16360. var xref = this.xref;
  16361. resources = (xref.fetchIfRef(resources) || Dict.empty);
  16362. // The xobj is parsed iff it's needed, e.g. if there is a `DO` cmd.
  16363. var xobjs = null;
  16364. var xobjsCache = {};
  16365. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  16366. var textState;
  16367. function newTextChunk() {
  16368. var font = textState.font;
  16369. if (!(font.loadedName in textContent.styles)) {
  16370. textContent.styles[font.loadedName] = {
  16371. fontFamily: font.fallbackName,
  16372. ascent: font.ascent,
  16373. descent: font.descent,
  16374. vertical: font.vertical
  16375. };
  16376. }
  16377. return {
  16378. // |str| is initially an array which we push individual chars to, and
  16379. // then runBidi() overwrites it with the final string.
  16380. str: [],
  16381. dir: null,
  16382. width: 0,
  16383. height: 0,
  16384. transform: null,
  16385. fontName: font.loadedName
  16386. };
  16387. }
  16388. function runBidi(textChunk) {
  16389. var str = textChunk.str.join('');
  16390. var bidiResult = PDFJS.bidi(str, -1, textState.font.vertical);
  16391. textChunk.str = bidiResult.str;
  16392. textChunk.dir = bidiResult.dir;
  16393. return textChunk;
  16394. }
  16395. function handleSetFont(fontName, fontRef) {
  16396. return self.loadFont(fontName, fontRef, xref, resources).
  16397. then(function (translated) {
  16398. textState.font = translated.font;
  16399. textState.fontMatrix = translated.font.fontMatrix ||
  16400. FONT_IDENTITY_MATRIX;
  16401. });
  16402. }
  16403. function buildTextGeometry(chars, textChunk) {
  16404. var font = textState.font;
  16405. textChunk = textChunk || newTextChunk();
  16406. if (!textChunk.transform) {
  16407. // 9.4.4 Text Space Details
  16408. var tsm = [textState.fontSize * textState.textHScale, 0,
  16409. 0, textState.fontSize,
  16410. 0, textState.textRise];
  16411. if (font.isType3Font &&
  16412. textState.fontMatrix !== FONT_IDENTITY_MATRIX &&
  16413. textState.fontSize === 1) {
  16414. var glyphHeight = font.bbox[3] - font.bbox[1];
  16415. if (glyphHeight > 0) {
  16416. glyphHeight = glyphHeight * textState.fontMatrix[3];
  16417. tsm[3] *= glyphHeight;
  16418. }
  16419. }
  16420. var trm = textChunk.transform = Util.transform(textState.ctm,
  16421. Util.transform(textState.textMatrix, tsm));
  16422. if (!font.vertical) {
  16423. textChunk.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]);
  16424. } else {
  16425. textChunk.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]);
  16426. }
  16427. }
  16428. var width = 0;
  16429. var height = 0;
  16430. var glyphs = font.charsToGlyphs(chars);
  16431. var defaultVMetrics = font.defaultVMetrics;
  16432. for (var i = 0; i < glyphs.length; i++) {
  16433. var glyph = glyphs[i];
  16434. if (!glyph) { // Previous glyph was a space.
  16435. width += textState.wordSpacing * textState.textHScale;
  16436. continue;
  16437. }
  16438. var vMetricX = null;
  16439. var vMetricY = null;
  16440. var glyphWidth = null;
  16441. if (font.vertical) {
  16442. if (glyph.vmetric) {
  16443. glyphWidth = glyph.vmetric[0];
  16444. vMetricX = glyph.vmetric[1];
  16445. vMetricY = glyph.vmetric[2];
  16446. } else {
  16447. glyphWidth = glyph.width;
  16448. vMetricX = glyph.width * 0.5;
  16449. vMetricY = defaultVMetrics[2];
  16450. }
  16451. } else {
  16452. glyphWidth = glyph.width;
  16453. }
  16454. var glyphUnicode = glyph.unicode;
  16455. if (NormalizedUnicodes[glyphUnicode] !== undefined) {
  16456. glyphUnicode = NormalizedUnicodes[glyphUnicode];
  16457. }
  16458. glyphUnicode = reverseIfRtl(glyphUnicode);
  16459. // The following will calculate the x and y of the individual glyphs.
  16460. // if (font.vertical) {
  16461. // tsm[4] -= vMetricX * Math.abs(textState.fontSize) *
  16462. // textState.fontMatrix[0];
  16463. // tsm[5] -= vMetricY * textState.fontSize *
  16464. // textState.fontMatrix[0];
  16465. // }
  16466. // var trm = Util.transform(textState.textMatrix, tsm);
  16467. // var pt = Util.applyTransform([trm[4], trm[5]], textState.ctm);
  16468. // var x = pt[0];
  16469. // var y = pt[1];
  16470. var charSpacing = 0;
  16471. if (textChunk.str.length > 0) {
  16472. // Apply char spacing only when there are chars.
  16473. // As a result there is only spacing between glyphs.
  16474. charSpacing = textState.charSpacing;
  16475. }
  16476. var tx = 0;
  16477. var ty = 0;
  16478. if (!font.vertical) {
  16479. var w0 = glyphWidth * textState.fontMatrix[0];
  16480. tx = (w0 * textState.fontSize + charSpacing) *
  16481. textState.textHScale;
  16482. width += tx;
  16483. } else {
  16484. var w1 = glyphWidth * textState.fontMatrix[0];
  16485. ty = w1 * textState.fontSize + charSpacing;
  16486. height += ty;
  16487. }
  16488. textState.translateTextMatrix(tx, ty);
  16489. textChunk.str.push(glyphUnicode);
  16490. }
  16491. var a = textState.textLineMatrix[0];
  16492. var b = textState.textLineMatrix[1];
  16493. var scaleLineX = Math.sqrt(a * a + b * b);
  16494. a = textState.ctm[0];
  16495. b = textState.ctm[1];
  16496. var scaleCtmX = Math.sqrt(a * a + b * b);
  16497. if (!font.vertical) {
  16498. textChunk.width += width * scaleCtmX * scaleLineX;
  16499. } else {
  16500. textChunk.height += Math.abs(height * scaleCtmX * scaleLineX);
  16501. }
  16502. return textChunk;
  16503. }
  16504. var timeSlotManager = new TimeSlotManager();
  16505. return new Promise(function next(resolve, reject) {
  16506. timeSlotManager.reset();
  16507. var stop, operation = {}, args = [];
  16508. while (!(stop = timeSlotManager.check())) {
  16509. // The arguments parsed by read() are not used beyond this loop, so
  16510. // we can reuse the same array on every iteration, thus avoiding
  16511. // unnecessary allocations.
  16512. args.length = 0;
  16513. operation.args = args;
  16514. if (!(preprocessor.read(operation))) {
  16515. break;
  16516. }
  16517. textState = stateManager.state;
  16518. var fn = operation.fn;
  16519. args = operation.args;
  16520. switch (fn | 0) {
  16521. case OPS.setFont:
  16522. textState.fontSize = args[1];
  16523. return handleSetFont(args[0].name).then(function() {
  16524. next(resolve, reject);
  16525. }, reject);
  16526. case OPS.setTextRise:
  16527. textState.textRise = args[0];
  16528. break;
  16529. case OPS.setHScale:
  16530. textState.textHScale = args[0] / 100;
  16531. break;
  16532. case OPS.setLeading:
  16533. textState.leading = args[0];
  16534. break;
  16535. case OPS.moveText:
  16536. textState.translateTextLineMatrix(args[0], args[1]);
  16537. textState.textMatrix = textState.textLineMatrix.slice();
  16538. break;
  16539. case OPS.setLeadingMoveText:
  16540. textState.leading = -args[1];
  16541. textState.translateTextLineMatrix(args[0], args[1]);
  16542. textState.textMatrix = textState.textLineMatrix.slice();
  16543. break;
  16544. case OPS.nextLine:
  16545. textState.carriageReturn();
  16546. break;
  16547. case OPS.setTextMatrix:
  16548. textState.setTextMatrix(args[0], args[1], args[2], args[3],
  16549. args[4], args[5]);
  16550. textState.setTextLineMatrix(args[0], args[1], args[2], args[3],
  16551. args[4], args[5]);
  16552. break;
  16553. case OPS.setCharSpacing:
  16554. textState.charSpacing = args[0];
  16555. break;
  16556. case OPS.setWordSpacing:
  16557. textState.wordSpacing = args[0];
  16558. break;
  16559. case OPS.beginText:
  16560. textState.textMatrix = IDENTITY_MATRIX.slice();
  16561. textState.textLineMatrix = IDENTITY_MATRIX.slice();
  16562. break;
  16563. case OPS.showSpacedText:
  16564. var items = args[0];
  16565. var textChunk = newTextChunk();
  16566. var offset;
  16567. for (var j = 0, jj = items.length; j < jj; j++) {
  16568. if (typeof items[j] === 'string') {
  16569. buildTextGeometry(items[j], textChunk);
  16570. } else {
  16571. // PDF Specification 5.3.2 states:
  16572. // The number is expressed in thousandths of a unit of text
  16573. // space.
  16574. // This amount is subtracted from the current horizontal or
  16575. // vertical coordinate, depending on the writing mode.
  16576. // In the default coordinate system, a positive adjustment
  16577. // has the effect of moving the next glyph painted either to
  16578. // the left or down by the given amount.
  16579. var val = items[j] * textState.fontSize / 1000;
  16580. if (textState.font.vertical) {
  16581. offset = val * textState.textMatrix[3];
  16582. textState.translateTextMatrix(0, offset);
  16583. // Value needs to be added to height to paint down.
  16584. textChunk.height += offset;
  16585. } else {
  16586. offset = val * textState.textHScale *
  16587. textState.textMatrix[0];
  16588. textState.translateTextMatrix(offset, 0);
  16589. // Value needs to be subtracted from width to paint left.
  16590. textChunk.width -= offset;
  16591. }
  16592. if (items[j] < 0 && textState.font.spaceWidth > 0) {
  16593. var fakeSpaces = -items[j] / textState.font.spaceWidth;
  16594. if (fakeSpaces > MULTI_SPACE_FACTOR) {
  16595. fakeSpaces = Math.round(fakeSpaces);
  16596. while (fakeSpaces--) {
  16597. textChunk.str.push(' ');
  16598. }
  16599. } else if (fakeSpaces > SPACE_FACTOR) {
  16600. textChunk.str.push(' ');
  16601. }
  16602. }
  16603. }
  16604. }
  16605. bidiTexts.push(runBidi(textChunk));
  16606. break;
  16607. case OPS.showText:
  16608. bidiTexts.push(runBidi(buildTextGeometry(args[0])));
  16609. break;
  16610. case OPS.nextLineShowText:
  16611. textState.carriageReturn();
  16612. bidiTexts.push(runBidi(buildTextGeometry(args[0])));
  16613. break;
  16614. case OPS.nextLineSetSpacingShowText:
  16615. textState.wordSpacing = args[0];
  16616. textState.charSpacing = args[1];
  16617. textState.carriageReturn();
  16618. bidiTexts.push(runBidi(buildTextGeometry(args[2])));
  16619. break;
  16620. case OPS.paintXObject:
  16621. if (args[0].code) {
  16622. break;
  16623. }
  16624. if (!xobjs) {
  16625. xobjs = (resources.get('XObject') || Dict.empty);
  16626. }
  16627. var name = args[0].name;
  16628. if (xobjsCache.key === name) {
  16629. if (xobjsCache.texts) {
  16630. Util.appendToArray(bidiTexts, xobjsCache.texts.items);
  16631. Util.extendObj(textContent.styles, xobjsCache.texts.styles);
  16632. }
  16633. break;
  16634. }
  16635. var xobj = xobjs.get(name);
  16636. if (!xobj) {
  16637. break;
  16638. }
  16639. assert(isStream(xobj), 'XObject should be a stream');
  16640. var type = xobj.dict.get('Subtype');
  16641. assert(isName(type),
  16642. 'XObject should have a Name subtype');
  16643. if ('Form' !== type.name) {
  16644. xobjsCache.key = name;
  16645. xobjsCache.texts = null;
  16646. break;
  16647. }
  16648. stateManager.save();
  16649. var matrix = xobj.dict.get('Matrix');
  16650. if (isArray(matrix) && matrix.length === 6) {
  16651. stateManager.transform(matrix);
  16652. }
  16653. return self.getTextContent(xobj,
  16654. xobj.dict.get('Resources') || resources, stateManager).
  16655. then(function (formTextContent) {
  16656. Util.appendToArray(bidiTexts, formTextContent.items);
  16657. Util.extendObj(textContent.styles, formTextContent.styles);
  16658. stateManager.restore();
  16659. xobjsCache.key = name;
  16660. xobjsCache.texts = formTextContent;
  16661. next(resolve, reject);
  16662. }, reject);
  16663. case OPS.setGState:
  16664. var dictName = args[0];
  16665. var extGState = resources.get('ExtGState');
  16666. if (!isDict(extGState) || !extGState.has(dictName.name)) {
  16667. break;
  16668. }
  16669. var gsStateMap = extGState.get(dictName.name);
  16670. var gsStateFont = null;
  16671. for (var key in gsStateMap) {
  16672. if (key === 'Font') {
  16673. assert(!gsStateFont);
  16674. gsStateFont = gsStateMap[key];
  16675. }
  16676. }
  16677. if (gsStateFont) {
  16678. textState.fontSize = gsStateFont[1];
  16679. return handleSetFont(gsStateFont[0]).then(function() {
  16680. next(resolve, reject);
  16681. }, reject);
  16682. }
  16683. break;
  16684. } // switch
  16685. } // while
  16686. if (stop) {
  16687. deferred.then(function () {
  16688. next(resolve, reject);
  16689. });
  16690. return;
  16691. }
  16692. resolve(textContent);
  16693. });
  16694. },
  16695. extractDataStructures: function
  16696. partialEvaluatorExtractDataStructures(dict, baseDict,
  16697. xref, properties) {
  16698. // 9.10.2
  16699. var toUnicode = (dict.get('ToUnicode') || baseDict.get('ToUnicode'));
  16700. if (toUnicode) {
  16701. properties.toUnicode = this.readToUnicode(toUnicode);
  16702. }
  16703. if (properties.composite) {
  16704. // CIDSystemInfo helps to match CID to glyphs
  16705. var cidSystemInfo = dict.get('CIDSystemInfo');
  16706. if (isDict(cidSystemInfo)) {
  16707. properties.cidSystemInfo = {
  16708. registry: cidSystemInfo.get('Registry'),
  16709. ordering: cidSystemInfo.get('Ordering'),
  16710. supplement: cidSystemInfo.get('Supplement')
  16711. };
  16712. }
  16713. var cidToGidMap = dict.get('CIDToGIDMap');
  16714. if (isStream(cidToGidMap)) {
  16715. properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
  16716. }
  16717. }
  16718. // Based on 9.6.6 of the spec the encoding can come from multiple places
  16719. // and depends on the font type. The base encoding and differences are
  16720. // read here, but the encoding that is actually used is chosen during
  16721. // glyph mapping in the font.
  16722. // TODO: Loading the built in encoding in the font would allow the
  16723. // differences to be merged in here not require us to hold on to it.
  16724. var differences = [];
  16725. var baseEncodingName = null;
  16726. var encoding;
  16727. if (dict.has('Encoding')) {
  16728. encoding = dict.get('Encoding');
  16729. if (isDict(encoding)) {
  16730. baseEncodingName = encoding.get('BaseEncoding');
  16731. baseEncodingName = (isName(baseEncodingName) ?
  16732. baseEncodingName.name : null);
  16733. // Load the differences between the base and original
  16734. if (encoding.has('Differences')) {
  16735. var diffEncoding = encoding.get('Differences');
  16736. var index = 0;
  16737. for (var j = 0, jj = diffEncoding.length; j < jj; j++) {
  16738. var data = diffEncoding[j];
  16739. if (isNum(data)) {
  16740. index = data;
  16741. } else if (isName(data)) {
  16742. differences[index++] = data.name;
  16743. } else if (isRef(data)) {
  16744. diffEncoding[j--] = xref.fetch(data);
  16745. continue;
  16746. } else {
  16747. error('Invalid entry in \'Differences\' array: ' + data);
  16748. }
  16749. }
  16750. }
  16751. } else if (isName(encoding)) {
  16752. baseEncodingName = encoding.name;
  16753. } else {
  16754. error('Encoding is not a Name nor a Dict');
  16755. }
  16756. // According to table 114 if the encoding is a named encoding it must be
  16757. // one of these predefined encodings.
  16758. if ((baseEncodingName !== 'MacRomanEncoding' &&
  16759. baseEncodingName !== 'MacExpertEncoding' &&
  16760. baseEncodingName !== 'WinAnsiEncoding')) {
  16761. baseEncodingName = null;
  16762. }
  16763. }
  16764. if (baseEncodingName) {
  16765. properties.defaultEncoding = Encodings[baseEncodingName].slice();
  16766. } else {
  16767. encoding = (properties.type === 'TrueType' ?
  16768. Encodings.WinAnsiEncoding : Encodings.StandardEncoding);
  16769. // The Symbolic attribute can be misused for regular fonts
  16770. // Heuristic: we have to check if the font is a standard one also
  16771. if (!!(properties.flags & FontFlags.Symbolic)) {
  16772. encoding = Encodings.MacRomanEncoding;
  16773. if (!properties.file) {
  16774. if (/Symbol/i.test(properties.name)) {
  16775. encoding = Encodings.SymbolSetEncoding;
  16776. } else if (/Dingbats/i.test(properties.name)) {
  16777. encoding = Encodings.ZapfDingbatsEncoding;
  16778. }
  16779. }
  16780. }
  16781. properties.defaultEncoding = encoding;
  16782. }
  16783. properties.differences = differences;
  16784. properties.baseEncodingName = baseEncodingName;
  16785. properties.dict = dict;
  16786. },
  16787. readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
  16788. var cmap, cmapObj = toUnicode;
  16789. if (isName(cmapObj)) {
  16790. cmap = CMapFactory.create(cmapObj,
  16791. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  16792. if (cmap instanceof IdentityCMap) {
  16793. return new IdentityToUnicodeMap(0, 0xFFFF);
  16794. }
  16795. return new ToUnicodeMap(cmap.getMap());
  16796. } else if (isStream(cmapObj)) {
  16797. cmap = CMapFactory.create(cmapObj,
  16798. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  16799. if (cmap instanceof IdentityCMap) {
  16800. return new IdentityToUnicodeMap(0, 0xFFFF);
  16801. }
  16802. var map = new Array(cmap.length);
  16803. // Convert UTF-16BE
  16804. // NOTE: cmap can be a sparse array, so use forEach instead of for(;;)
  16805. // to iterate over all keys.
  16806. cmap.forEach(function(charCode, token) {
  16807. var str = [];
  16808. for (var k = 0; k < token.length; k += 2) {
  16809. var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
  16810. if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF
  16811. str.push(w1);
  16812. continue;
  16813. }
  16814. k += 2;
  16815. var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
  16816. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  16817. }
  16818. map[charCode] = String.fromCharCode.apply(String, str);
  16819. });
  16820. return new ToUnicodeMap(map);
  16821. }
  16822. return null;
  16823. },
  16824. readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
  16825. // Extract the encoding from the CIDToGIDMap
  16826. var glyphsData = cidToGidStream.getBytes();
  16827. // Set encoding 0 to later verify the font has an encoding
  16828. var result = [];
  16829. for (var j = 0, jj = glyphsData.length; j < jj; j++) {
  16830. var glyphID = (glyphsData[j++] << 8) | glyphsData[j];
  16831. if (glyphID === 0) {
  16832. continue;
  16833. }
  16834. var code = j >> 1;
  16835. result[code] = glyphID;
  16836. }
  16837. return result;
  16838. },
  16839. extractWidths: function PartialEvaluator_extractWidths(dict, xref,
  16840. descriptor,
  16841. properties) {
  16842. var glyphsWidths = [];
  16843. var defaultWidth = 0;
  16844. var glyphsVMetrics = [];
  16845. var defaultVMetrics;
  16846. var i, ii, j, jj, start, code, widths;
  16847. if (properties.composite) {
  16848. defaultWidth = dict.get('DW') || 1000;
  16849. widths = dict.get('W');
  16850. if (widths) {
  16851. for (i = 0, ii = widths.length; i < ii; i++) {
  16852. start = widths[i++];
  16853. code = xref.fetchIfRef(widths[i]);
  16854. if (isArray(code)) {
  16855. for (j = 0, jj = code.length; j < jj; j++) {
  16856. glyphsWidths[start++] = code[j];
  16857. }
  16858. } else {
  16859. var width = widths[++i];
  16860. for (j = start; j <= code; j++) {
  16861. glyphsWidths[j] = width;
  16862. }
  16863. }
  16864. }
  16865. }
  16866. if (properties.vertical) {
  16867. var vmetrics = (dict.get('DW2') || [880, -1000]);
  16868. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  16869. vmetrics = dict.get('W2');
  16870. if (vmetrics) {
  16871. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  16872. start = vmetrics[i++];
  16873. code = xref.fetchIfRef(vmetrics[i]);
  16874. if (isArray(code)) {
  16875. for (j = 0, jj = code.length; j < jj; j++) {
  16876. glyphsVMetrics[start++] = [code[j++], code[j++], code[j]];
  16877. }
  16878. } else {
  16879. var vmetric = [vmetrics[++i], vmetrics[++i], vmetrics[++i]];
  16880. for (j = start; j <= code; j++) {
  16881. glyphsVMetrics[j] = vmetric;
  16882. }
  16883. }
  16884. }
  16885. }
  16886. }
  16887. } else {
  16888. var firstChar = properties.firstChar;
  16889. widths = dict.get('Widths');
  16890. if (widths) {
  16891. j = firstChar;
  16892. for (i = 0, ii = widths.length; i < ii; i++) {
  16893. glyphsWidths[j++] = widths[i];
  16894. }
  16895. defaultWidth = (parseFloat(descriptor.get('MissingWidth')) || 0);
  16896. } else {
  16897. // Trying get the BaseFont metrics (see comment above).
  16898. var baseFontName = dict.get('BaseFont');
  16899. if (isName(baseFontName)) {
  16900. var metrics = this.getBaseFontMetrics(baseFontName.name);
  16901. glyphsWidths = this.buildCharCodeToWidth(metrics.widths,
  16902. properties);
  16903. defaultWidth = metrics.defaultWidth;
  16904. }
  16905. }
  16906. }
  16907. // Heuristic: detection of monospace font by checking all non-zero widths
  16908. var isMonospace = true;
  16909. var firstWidth = defaultWidth;
  16910. for (var glyph in glyphsWidths) {
  16911. var glyphWidth = glyphsWidths[glyph];
  16912. if (!glyphWidth) {
  16913. continue;
  16914. }
  16915. if (!firstWidth) {
  16916. firstWidth = glyphWidth;
  16917. continue;
  16918. }
  16919. if (firstWidth !== glyphWidth) {
  16920. isMonospace = false;
  16921. break;
  16922. }
  16923. }
  16924. if (isMonospace) {
  16925. properties.flags |= FontFlags.FixedPitch;
  16926. }
  16927. properties.defaultWidth = defaultWidth;
  16928. properties.widths = glyphsWidths;
  16929. properties.defaultVMetrics = defaultVMetrics;
  16930. properties.vmetrics = glyphsVMetrics;
  16931. },
  16932. isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
  16933. // Simulating descriptor flags attribute
  16934. var fontNameWoStyle = baseFontName.split('-')[0];
  16935. return (fontNameWoStyle in serifFonts) ||
  16936. (fontNameWoStyle.search(/serif/gi) !== -1);
  16937. },
  16938. getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
  16939. var defaultWidth = 0;
  16940. var widths = [];
  16941. var monospace = false;
  16942. var lookupName = (stdFontMap[name] || name);
  16943. if (!(lookupName in Metrics)) {
  16944. // Use default fonts for looking up font metrics if the passed
  16945. // font is not a base font
  16946. if (this.isSerifFont(name)) {
  16947. lookupName = 'Times-Roman';
  16948. } else {
  16949. lookupName = 'Helvetica';
  16950. }
  16951. }
  16952. var glyphWidths = Metrics[lookupName];
  16953. if (isNum(glyphWidths)) {
  16954. defaultWidth = glyphWidths;
  16955. monospace = true;
  16956. } else {
  16957. widths = glyphWidths;
  16958. }
  16959. return {
  16960. defaultWidth: defaultWidth,
  16961. monospace: monospace,
  16962. widths: widths
  16963. };
  16964. },
  16965. buildCharCodeToWidth:
  16966. function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName,
  16967. properties) {
  16968. var widths = Object.create(null);
  16969. var differences = properties.differences;
  16970. var encoding = properties.defaultEncoding;
  16971. for (var charCode = 0; charCode < 256; charCode++) {
  16972. if (charCode in differences &&
  16973. widthsByGlyphName[differences[charCode]]) {
  16974. widths[charCode] = widthsByGlyphName[differences[charCode]];
  16975. continue;
  16976. }
  16977. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  16978. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  16979. continue;
  16980. }
  16981. }
  16982. return widths;
  16983. },
  16984. preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict, xref) {
  16985. var baseDict = dict;
  16986. var type = dict.get('Subtype');
  16987. assert(isName(type), 'invalid font Subtype');
  16988. var composite = false;
  16989. var uint8array;
  16990. if (type.name === 'Type0') {
  16991. // If font is a composite
  16992. // - get the descendant font
  16993. // - set the type according to the descendant font
  16994. // - get the FontDescriptor from the descendant font
  16995. var df = dict.get('DescendantFonts');
  16996. if (!df) {
  16997. error('Descendant fonts are not specified');
  16998. }
  16999. dict = (isArray(df) ? xref.fetchIfRef(df[0]) : df);
  17000. type = dict.get('Subtype');
  17001. assert(isName(type), 'invalid font Subtype');
  17002. composite = true;
  17003. }
  17004. var descriptor = dict.get('FontDescriptor');
  17005. if (descriptor) {
  17006. var hash = new MurmurHash3_64();
  17007. var encoding = baseDict.getRaw('Encoding');
  17008. if (isName(encoding)) {
  17009. hash.update(encoding.name);
  17010. } else if (isRef(encoding)) {
  17011. hash.update(encoding.num + '_' + encoding.gen);
  17012. } else if (isDict(encoding)) {
  17013. var keys = encoding.getKeys();
  17014. for (var i = 0, ii = keys.length; i < ii; i++) {
  17015. var entry = encoding.getRaw(keys[i]);
  17016. if (isName(entry)) {
  17017. hash.update(entry.name);
  17018. } else if (isRef(entry)) {
  17019. hash.update(entry.num + '_' + entry.gen);
  17020. } else if (isArray(entry)) { // 'Differences' entry.
  17021. // Ideally we should check the contents of the array, but to avoid
  17022. // parsing it here and then again in |extractDataStructures|,
  17023. // we only use the array length for now (fixes bug1157493.pdf).
  17024. hash.update(entry.length.toString());
  17025. }
  17026. }
  17027. }
  17028. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  17029. if (isStream(toUnicode)) {
  17030. var stream = toUnicode.str || toUnicode;
  17031. uint8array = stream.buffer ?
  17032. new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) :
  17033. new Uint8Array(stream.bytes.buffer,
  17034. stream.start, stream.end - stream.start);
  17035. hash.update(uint8array);
  17036. } else if (isName(toUnicode)) {
  17037. hash.update(toUnicode.name);
  17038. }
  17039. var widths = dict.get('Widths') || baseDict.get('Widths');
  17040. if (widths) {
  17041. uint8array = new Uint8Array(new Uint32Array(widths).buffer);
  17042. hash.update(uint8array);
  17043. }
  17044. }
  17045. return {
  17046. descriptor: descriptor,
  17047. dict: dict,
  17048. baseDict: baseDict,
  17049. composite: composite,
  17050. type: type.name,
  17051. hash: hash ? hash.hexdigest() : ''
  17052. };
  17053. },
  17054. translateFont: function PartialEvaluator_translateFont(preEvaluatedFont,
  17055. xref) {
  17056. var baseDict = preEvaluatedFont.baseDict;
  17057. var dict = preEvaluatedFont.dict;
  17058. var composite = preEvaluatedFont.composite;
  17059. var descriptor = preEvaluatedFont.descriptor;
  17060. var type = preEvaluatedFont.type;
  17061. var maxCharIndex = (composite ? 0xFFFF : 0xFF);
  17062. var properties;
  17063. if (!descriptor) {
  17064. if (type === 'Type3') {
  17065. // FontDescriptor is only required for Type3 fonts when the document
  17066. // is a tagged pdf. Create a barbebones one to get by.
  17067. descriptor = new Dict(null);
  17068. descriptor.set('FontName', Name.get(type));
  17069. descriptor.set('FontBBox', dict.get('FontBBox'));
  17070. } else {
  17071. // Before PDF 1.5 if the font was one of the base 14 fonts, having a
  17072. // FontDescriptor was not required.
  17073. // This case is here for compatibility.
  17074. var baseFontName = dict.get('BaseFont');
  17075. if (!isName(baseFontName)) {
  17076. error('Base font is not specified');
  17077. }
  17078. // Using base font name as a font name.
  17079. baseFontName = baseFontName.name.replace(/[,_]/g, '-');
  17080. var metrics = this.getBaseFontMetrics(baseFontName);
  17081. // Simulating descriptor flags attribute
  17082. var fontNameWoStyle = baseFontName.split('-')[0];
  17083. var flags =
  17084. (this.isSerifFont(fontNameWoStyle) ? FontFlags.Serif : 0) |
  17085. (metrics.monospace ? FontFlags.FixedPitch : 0) |
  17086. (symbolsFonts[fontNameWoStyle] ? FontFlags.Symbolic :
  17087. FontFlags.Nonsymbolic);
  17088. properties = {
  17089. type: type,
  17090. name: baseFontName,
  17091. widths: metrics.widths,
  17092. defaultWidth: metrics.defaultWidth,
  17093. flags: flags,
  17094. firstChar: 0,
  17095. lastChar: maxCharIndex
  17096. };
  17097. this.extractDataStructures(dict, dict, xref, properties);
  17098. properties.widths = this.buildCharCodeToWidth(metrics.widths,
  17099. properties);
  17100. return new Font(baseFontName, null, properties);
  17101. }
  17102. }
  17103. // According to the spec if 'FontDescriptor' is declared, 'FirstChar',
  17104. // 'LastChar' and 'Widths' should exist too, but some PDF encoders seem
  17105. // to ignore this rule when a variant of a standart font is used.
  17106. // TODO Fill the width array depending on which of the base font this is
  17107. // a variant.
  17108. var firstChar = (dict.get('FirstChar') || 0);
  17109. var lastChar = (dict.get('LastChar') || maxCharIndex);
  17110. var fontName = descriptor.get('FontName');
  17111. var baseFont = dict.get('BaseFont');
  17112. // Some bad PDFs have a string as the font name.
  17113. if (isString(fontName)) {
  17114. fontName = Name.get(fontName);
  17115. }
  17116. if (isString(baseFont)) {
  17117. baseFont = Name.get(baseFont);
  17118. }
  17119. if (type !== 'Type3') {
  17120. var fontNameStr = fontName && fontName.name;
  17121. var baseFontStr = baseFont && baseFont.name;
  17122. if (fontNameStr !== baseFontStr) {
  17123. info('The FontDescriptor\'s FontName is "' + fontNameStr +
  17124. '" but should be the same as the Font\'s BaseFont "' +
  17125. baseFontStr + '"');
  17126. // Workaround for cases where e.g. fontNameStr = 'Arial' and
  17127. // baseFontStr = 'Arial,Bold' (needed when no font file is embedded).
  17128. if (fontNameStr && baseFontStr &&
  17129. baseFontStr.indexOf(fontNameStr) === 0) {
  17130. fontName = baseFont;
  17131. }
  17132. }
  17133. }
  17134. fontName = (fontName || baseFont);
  17135. assert(isName(fontName), 'invalid font name');
  17136. var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
  17137. if (fontFile) {
  17138. if (fontFile.dict) {
  17139. var subtype = fontFile.dict.get('Subtype');
  17140. if (subtype) {
  17141. subtype = subtype.name;
  17142. }
  17143. var length1 = fontFile.dict.get('Length1');
  17144. var length2 = fontFile.dict.get('Length2');
  17145. }
  17146. }
  17147. properties = {
  17148. type: type,
  17149. name: fontName.name,
  17150. subtype: subtype,
  17151. file: fontFile,
  17152. length1: length1,
  17153. length2: length2,
  17154. loadedName: baseDict.loadedName,
  17155. composite: composite,
  17156. wideChars: composite,
  17157. fixedPitch: false,
  17158. fontMatrix: (dict.get('FontMatrix') || FONT_IDENTITY_MATRIX),
  17159. firstChar: firstChar || 0,
  17160. lastChar: (lastChar || maxCharIndex),
  17161. bbox: descriptor.get('FontBBox'),
  17162. ascent: descriptor.get('Ascent'),
  17163. descent: descriptor.get('Descent'),
  17164. xHeight: descriptor.get('XHeight'),
  17165. capHeight: descriptor.get('CapHeight'),
  17166. flags: descriptor.get('Flags'),
  17167. italicAngle: descriptor.get('ItalicAngle'),
  17168. coded: false
  17169. };
  17170. if (composite) {
  17171. var cidEncoding = baseDict.get('Encoding');
  17172. if (isName(cidEncoding)) {
  17173. properties.cidEncoding = cidEncoding.name;
  17174. }
  17175. properties.cMap = CMapFactory.create(cidEncoding,
  17176. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  17177. properties.vertical = properties.cMap.vertical;
  17178. }
  17179. this.extractDataStructures(dict, baseDict, xref, properties);
  17180. this.extractWidths(dict, xref, descriptor, properties);
  17181. if (type === 'Type3') {
  17182. properties.isType3Font = true;
  17183. }
  17184. return new Font(fontName.name, fontFile, properties);
  17185. }
  17186. };
  17187. return PartialEvaluator;
  17188. })();
  17189. var TranslatedFont = (function TranslatedFontClosure() {
  17190. function TranslatedFont(loadedName, font, dict) {
  17191. this.loadedName = loadedName;
  17192. this.font = font;
  17193. this.dict = dict;
  17194. this.type3Loaded = null;
  17195. this.sent = false;
  17196. }
  17197. TranslatedFont.prototype = {
  17198. send: function (handler) {
  17199. if (this.sent) {
  17200. return;
  17201. }
  17202. var fontData = this.font.exportData();
  17203. handler.send('commonobj', [
  17204. this.loadedName,
  17205. 'Font',
  17206. fontData
  17207. ]);
  17208. this.sent = true;
  17209. },
  17210. loadType3Data: function (evaluator, resources, parentOperatorList) {
  17211. assert(this.font.isType3Font);
  17212. if (this.type3Loaded) {
  17213. return this.type3Loaded;
  17214. }
  17215. var translatedFont = this.font;
  17216. var loadCharProcsPromise = Promise.resolve();
  17217. var charProcs = this.dict.get('CharProcs').getAll();
  17218. var fontResources = this.dict.get('Resources') || resources;
  17219. var charProcKeys = Object.keys(charProcs);
  17220. var charProcOperatorList = {};
  17221. for (var i = 0, n = charProcKeys.length; i < n; ++i) {
  17222. loadCharProcsPromise = loadCharProcsPromise.then(function (key) {
  17223. var glyphStream = charProcs[key];
  17224. var operatorList = new OperatorList();
  17225. return evaluator.getOperatorList(glyphStream, fontResources,
  17226. operatorList).then(function () {
  17227. charProcOperatorList[key] = operatorList.getIR();
  17228. // Add the dependencies to the parent operator list so they are
  17229. // resolved before sub operator list is executed synchronously.
  17230. parentOperatorList.addDependencies(operatorList.dependencies);
  17231. }, function (reason) {
  17232. warn('Type3 font resource \"' + key + '\" is not available');
  17233. var operatorList = new OperatorList();
  17234. charProcOperatorList[key] = operatorList.getIR();
  17235. });
  17236. }.bind(this, charProcKeys[i]));
  17237. }
  17238. this.type3Loaded = loadCharProcsPromise.then(function () {
  17239. translatedFont.charProcOperatorList = charProcOperatorList;
  17240. });
  17241. return this.type3Loaded;
  17242. }
  17243. };
  17244. return TranslatedFont;
  17245. })();
  17246. var OperatorList = (function OperatorListClosure() {
  17247. var CHUNK_SIZE = 1000;
  17248. var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5; // close to chunk size
  17249. function getTransfers(queue) {
  17250. var transfers = [];
  17251. var fnArray = queue.fnArray, argsArray = queue.argsArray;
  17252. for (var i = 0, ii = queue.length; i < ii; i++) {
  17253. switch (fnArray[i]) {
  17254. case OPS.paintInlineImageXObject:
  17255. case OPS.paintInlineImageXObjectGroup:
  17256. case OPS.paintImageMaskXObject:
  17257. var arg = argsArray[i][0]; // first param in imgData
  17258. if (!arg.cached) {
  17259. transfers.push(arg.data.buffer);
  17260. }
  17261. break;
  17262. }
  17263. }
  17264. return transfers;
  17265. }
  17266. function OperatorList(intent, messageHandler, pageIndex) {
  17267. this.messageHandler = messageHandler;
  17268. this.fnArray = [];
  17269. this.argsArray = [];
  17270. this.dependencies = {};
  17271. this.pageIndex = pageIndex;
  17272. this.intent = intent;
  17273. }
  17274. OperatorList.prototype = {
  17275. get length() {
  17276. return this.argsArray.length;
  17277. },
  17278. addOp: function(fn, args) {
  17279. this.fnArray.push(fn);
  17280. this.argsArray.push(args);
  17281. if (this.messageHandler) {
  17282. if (this.fnArray.length >= CHUNK_SIZE) {
  17283. this.flush();
  17284. } else if (this.fnArray.length >= CHUNK_SIZE_ABOUT &&
  17285. (fn === OPS.restore || fn === OPS.endText)) {
  17286. // heuristic to flush on boundary of restore or endText
  17287. this.flush();
  17288. }
  17289. }
  17290. },
  17291. addDependency: function(dependency) {
  17292. if (dependency in this.dependencies) {
  17293. return;
  17294. }
  17295. this.dependencies[dependency] = true;
  17296. this.addOp(OPS.dependency, [dependency]);
  17297. },
  17298. addDependencies: function(dependencies) {
  17299. for (var key in dependencies) {
  17300. this.addDependency(key);
  17301. }
  17302. },
  17303. addOpList: function(opList) {
  17304. Util.extendObj(this.dependencies, opList.dependencies);
  17305. for (var i = 0, ii = opList.length; i < ii; i++) {
  17306. this.addOp(opList.fnArray[i], opList.argsArray[i]);
  17307. }
  17308. },
  17309. getIR: function() {
  17310. return {
  17311. fnArray: this.fnArray,
  17312. argsArray: this.argsArray,
  17313. length: this.length
  17314. };
  17315. },
  17316. flush: function(lastChunk) {
  17317. if (this.intent !== 'oplist') {
  17318. new QueueOptimizer().optimize(this);
  17319. }
  17320. var transfers = getTransfers(this);
  17321. this.messageHandler.send('RenderPageChunk', {
  17322. operatorList: {
  17323. fnArray: this.fnArray,
  17324. argsArray: this.argsArray,
  17325. lastChunk: lastChunk,
  17326. length: this.length
  17327. },
  17328. pageIndex: this.pageIndex,
  17329. intent: this.intent
  17330. }, transfers);
  17331. this.dependencies = {};
  17332. this.fnArray.length = 0;
  17333. this.argsArray.length = 0;
  17334. }
  17335. };
  17336. return OperatorList;
  17337. })();
  17338. var StateManager = (function StateManagerClosure() {
  17339. function StateManager(initialState) {
  17340. this.state = initialState;
  17341. this.stateStack = [];
  17342. }
  17343. StateManager.prototype = {
  17344. save: function () {
  17345. var old = this.state;
  17346. this.stateStack.push(this.state);
  17347. this.state = old.clone();
  17348. },
  17349. restore: function () {
  17350. var prev = this.stateStack.pop();
  17351. if (prev) {
  17352. this.state = prev;
  17353. }
  17354. },
  17355. transform: function (args) {
  17356. this.state.ctm = Util.transform(this.state.ctm, args);
  17357. }
  17358. };
  17359. return StateManager;
  17360. })();
  17361. var TextState = (function TextStateClosure() {
  17362. function TextState() {
  17363. this.ctm = new Float32Array(IDENTITY_MATRIX);
  17364. this.fontSize = 0;
  17365. this.font = null;
  17366. this.fontMatrix = FONT_IDENTITY_MATRIX;
  17367. this.textMatrix = IDENTITY_MATRIX.slice();
  17368. this.textLineMatrix = IDENTITY_MATRIX.slice();
  17369. this.charSpacing = 0;
  17370. this.wordSpacing = 0;
  17371. this.leading = 0;
  17372. this.textHScale = 1;
  17373. this.textRise = 0;
  17374. }
  17375. TextState.prototype = {
  17376. setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  17377. var m = this.textMatrix;
  17378. m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
  17379. },
  17380. setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  17381. var m = this.textLineMatrix;
  17382. m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
  17383. },
  17384. translateTextMatrix: function TextState_translateTextMatrix(x, y) {
  17385. var m = this.textMatrix;
  17386. m[4] = m[0] * x + m[2] * y + m[4];
  17387. m[5] = m[1] * x + m[3] * y + m[5];
  17388. },
  17389. translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
  17390. var m = this.textLineMatrix;
  17391. m[4] = m[0] * x + m[2] * y + m[4];
  17392. m[5] = m[1] * x + m[3] * y + m[5];
  17393. },
  17394. calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
  17395. // 9.4.4 Text Space Details
  17396. var tsm = [this.fontSize * this.textHScale, 0,
  17397. 0, this.fontSize,
  17398. 0, this.textRise];
  17399. return Util.transform(ctm, Util.transform(this.textMatrix, tsm));
  17400. },
  17401. carriageReturn: function TextState_carriageReturn() {
  17402. this.translateTextLineMatrix(0, -this.leading);
  17403. this.textMatrix = this.textLineMatrix.slice();
  17404. },
  17405. clone: function TextState_clone() {
  17406. var clone = Object.create(this);
  17407. clone.textMatrix = this.textMatrix.slice();
  17408. clone.textLineMatrix = this.textLineMatrix.slice();
  17409. clone.fontMatrix = this.fontMatrix.slice();
  17410. return clone;
  17411. }
  17412. };
  17413. return TextState;
  17414. })();
  17415. var EvalState = (function EvalStateClosure() {
  17416. function EvalState() {
  17417. this.ctm = new Float32Array(IDENTITY_MATRIX);
  17418. this.font = null;
  17419. this.textRenderingMode = TextRenderingMode.FILL;
  17420. this.fillColorSpace = ColorSpace.singletons.gray;
  17421. this.strokeColorSpace = ColorSpace.singletons.gray;
  17422. }
  17423. EvalState.prototype = {
  17424. clone: function CanvasExtraState_clone() {
  17425. return Object.create(this);
  17426. },
  17427. };
  17428. return EvalState;
  17429. })();
  17430. var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
  17431. // Specifies properties for each command
  17432. //
  17433. // If variableArgs === true: [0, `numArgs`] expected
  17434. // If variableArgs === false: exactly `numArgs` expected
  17435. var OP_MAP = {
  17436. // Graphic state
  17437. w: { id: OPS.setLineWidth, numArgs: 1, variableArgs: false },
  17438. J: { id: OPS.setLineCap, numArgs: 1, variableArgs: false },
  17439. j: { id: OPS.setLineJoin, numArgs: 1, variableArgs: false },
  17440. M: { id: OPS.setMiterLimit, numArgs: 1, variableArgs: false },
  17441. d: { id: OPS.setDash, numArgs: 2, variableArgs: false },
  17442. ri: { id: OPS.setRenderingIntent, numArgs: 1, variableArgs: false },
  17443. i: { id: OPS.setFlatness, numArgs: 1, variableArgs: false },
  17444. gs: { id: OPS.setGState, numArgs: 1, variableArgs: false },
  17445. q: { id: OPS.save, numArgs: 0, variableArgs: false },
  17446. Q: { id: OPS.restore, numArgs: 0, variableArgs: false },
  17447. cm: { id: OPS.transform, numArgs: 6, variableArgs: false },
  17448. // Path
  17449. m: { id: OPS.moveTo, numArgs: 2, variableArgs: false },
  17450. l: { id: OPS.lineTo, numArgs: 2, variableArgs: false },
  17451. c: { id: OPS.curveTo, numArgs: 6, variableArgs: false },
  17452. v: { id: OPS.curveTo2, numArgs: 4, variableArgs: false },
  17453. y: { id: OPS.curveTo3, numArgs: 4, variableArgs: false },
  17454. h: { id: OPS.closePath, numArgs: 0, variableArgs: false },
  17455. re: { id: OPS.rectangle, numArgs: 4, variableArgs: false },
  17456. S: { id: OPS.stroke, numArgs: 0, variableArgs: false },
  17457. s: { id: OPS.closeStroke, numArgs: 0, variableArgs: false },
  17458. f: { id: OPS.fill, numArgs: 0, variableArgs: false },
  17459. F: { id: OPS.fill, numArgs: 0, variableArgs: false },
  17460. 'f*': { id: OPS.eoFill, numArgs: 0, variableArgs: false },
  17461. B: { id: OPS.fillStroke, numArgs: 0, variableArgs: false },
  17462. 'B*': { id: OPS.eoFillStroke, numArgs: 0, variableArgs: false },
  17463. b: { id: OPS.closeFillStroke, numArgs: 0, variableArgs: false },
  17464. 'b*': { id: OPS.closeEOFillStroke, numArgs: 0, variableArgs: false },
  17465. n: { id: OPS.endPath, numArgs: 0, variableArgs: false },
  17466. // Clipping
  17467. W: { id: OPS.clip, numArgs: 0, variableArgs: false },
  17468. 'W*': { id: OPS.eoClip, numArgs: 0, variableArgs: false },
  17469. // Text
  17470. BT: { id: OPS.beginText, numArgs: 0, variableArgs: false },
  17471. ET: { id: OPS.endText, numArgs: 0, variableArgs: false },
  17472. Tc: { id: OPS.setCharSpacing, numArgs: 1, variableArgs: false },
  17473. Tw: { id: OPS.setWordSpacing, numArgs: 1, variableArgs: false },
  17474. Tz: { id: OPS.setHScale, numArgs: 1, variableArgs: false },
  17475. TL: { id: OPS.setLeading, numArgs: 1, variableArgs: false },
  17476. Tf: { id: OPS.setFont, numArgs: 2, variableArgs: false },
  17477. Tr: { id: OPS.setTextRenderingMode, numArgs: 1, variableArgs: false },
  17478. Ts: { id: OPS.setTextRise, numArgs: 1, variableArgs: false },
  17479. Td: { id: OPS.moveText, numArgs: 2, variableArgs: false },
  17480. TD: { id: OPS.setLeadingMoveText, numArgs: 2, variableArgs: false },
  17481. Tm: { id: OPS.setTextMatrix, numArgs: 6, variableArgs: false },
  17482. 'T*': { id: OPS.nextLine, numArgs: 0, variableArgs: false },
  17483. Tj: { id: OPS.showText, numArgs: 1, variableArgs: false },
  17484. TJ: { id: OPS.showSpacedText, numArgs: 1, variableArgs: false },
  17485. '\'': { id: OPS.nextLineShowText, numArgs: 1, variableArgs: false },
  17486. '"': { id: OPS.nextLineSetSpacingShowText, numArgs: 3,
  17487. variableArgs: false },
  17488. // Type3 fonts
  17489. d0: { id: OPS.setCharWidth, numArgs: 2, variableArgs: false },
  17490. d1: { id: OPS.setCharWidthAndBounds, numArgs: 6, variableArgs: false },
  17491. // Color
  17492. CS: { id: OPS.setStrokeColorSpace, numArgs: 1, variableArgs: false },
  17493. cs: { id: OPS.setFillColorSpace, numArgs: 1, variableArgs: false },
  17494. SC: { id: OPS.setStrokeColor, numArgs: 4, variableArgs: true },
  17495. SCN: { id: OPS.setStrokeColorN, numArgs: 33, variableArgs: true },
  17496. sc: { id: OPS.setFillColor, numArgs: 4, variableArgs: true },
  17497. scn: { id: OPS.setFillColorN, numArgs: 33, variableArgs: true },
  17498. G: { id: OPS.setStrokeGray, numArgs: 1, variableArgs: false },
  17499. g: { id: OPS.setFillGray, numArgs: 1, variableArgs: false },
  17500. RG: { id: OPS.setStrokeRGBColor, numArgs: 3, variableArgs: false },
  17501. rg: { id: OPS.setFillRGBColor, numArgs: 3, variableArgs: false },
  17502. K: { id: OPS.setStrokeCMYKColor, numArgs: 4, variableArgs: false },
  17503. k: { id: OPS.setFillCMYKColor, numArgs: 4, variableArgs: false },
  17504. // Shading
  17505. sh: { id: OPS.shadingFill, numArgs: 1, variableArgs: false },
  17506. // Images
  17507. BI: { id: OPS.beginInlineImage, numArgs: 0, variableArgs: false },
  17508. ID: { id: OPS.beginImageData, numArgs: 0, variableArgs: false },
  17509. EI: { id: OPS.endInlineImage, numArgs: 1, variableArgs: false },
  17510. // XObjects
  17511. Do: { id: OPS.paintXObject, numArgs: 1, variableArgs: false },
  17512. MP: { id: OPS.markPoint, numArgs: 1, variableArgs: false },
  17513. DP: { id: OPS.markPointProps, numArgs: 2, variableArgs: false },
  17514. BMC: { id: OPS.beginMarkedContent, numArgs: 1, variableArgs: false },
  17515. BDC: { id: OPS.beginMarkedContentProps, numArgs: 2,
  17516. variableArgs: false },
  17517. EMC: { id: OPS.endMarkedContent, numArgs: 0, variableArgs: false },
  17518. // Compatibility
  17519. BX: { id: OPS.beginCompat, numArgs: 0, variableArgs: false },
  17520. EX: { id: OPS.endCompat, numArgs: 0, variableArgs: false },
  17521. // (reserved partial commands for the lexer)
  17522. BM: null,
  17523. BD: null,
  17524. 'true': null,
  17525. fa: null,
  17526. fal: null,
  17527. fals: null,
  17528. 'false': null,
  17529. nu: null,
  17530. nul: null,
  17531. 'null': null
  17532. };
  17533. function EvaluatorPreprocessor(stream, xref, stateManager) {
  17534. // TODO(mduan): pass array of knownCommands rather than OP_MAP
  17535. // dictionary
  17536. this.parser = new Parser(new Lexer(stream, OP_MAP), false, xref);
  17537. this.stateManager = stateManager;
  17538. this.nonProcessedArgs = [];
  17539. }
  17540. EvaluatorPreprocessor.prototype = {
  17541. get savedStatesDepth() {
  17542. return this.stateManager.stateStack.length;
  17543. },
  17544. // |operation| is an object with two fields:
  17545. //
  17546. // - |fn| is an out param.
  17547. //
  17548. // - |args| is an inout param. On entry, it should have one of two values.
  17549. //
  17550. // - An empty array. This indicates that the caller is providing the
  17551. // array in which the args will be stored in. The caller should use
  17552. // this value if it can reuse a single array for each call to read().
  17553. //
  17554. // - |null|. This indicates that the caller needs this function to create
  17555. // the array in which any args are stored in. If there are zero args,
  17556. // this function will leave |operation.args| as |null| (thus avoiding
  17557. // allocations that would occur if we used an empty array to represent
  17558. // zero arguments). Otherwise, it will replace |null| with a new array
  17559. // containing the arguments. The caller should use this value if it
  17560. // cannot reuse an array for each call to read().
  17561. //
  17562. // These two modes are present because this function is very hot and so
  17563. // avoiding allocations where possible is worthwhile.
  17564. //
  17565. read: function EvaluatorPreprocessor_read(operation) {
  17566. var args = operation.args;
  17567. while (true) {
  17568. var obj = this.parser.getObj();
  17569. if (isCmd(obj)) {
  17570. var cmd = obj.cmd;
  17571. // Check that the command is valid
  17572. var opSpec = OP_MAP[cmd];
  17573. if (!opSpec) {
  17574. warn('Unknown command "' + cmd + '"');
  17575. continue;
  17576. }
  17577. var fn = opSpec.id;
  17578. var numArgs = opSpec.numArgs;
  17579. var argsLength = args !== null ? args.length : 0;
  17580. if (!opSpec.variableArgs) {
  17581. // Postscript commands can be nested, e.g. /F2 /GS2 gs 5.711 Tf
  17582. if (argsLength !== numArgs) {
  17583. var nonProcessedArgs = this.nonProcessedArgs;
  17584. while (argsLength > numArgs) {
  17585. nonProcessedArgs.push(args.shift());
  17586. argsLength--;
  17587. }
  17588. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  17589. if (!args) {
  17590. args = [];
  17591. }
  17592. args.unshift(nonProcessedArgs.pop());
  17593. argsLength++;
  17594. }
  17595. }
  17596. if (argsLength < numArgs) {
  17597. // If we receive too few args, it's not possible to possible
  17598. // to execute the command, so skip the command
  17599. info('Command ' + fn + ': because expected ' +
  17600. numArgs + ' args, but received ' + argsLength +
  17601. ' args; skipping');
  17602. args = null;
  17603. continue;
  17604. }
  17605. } else if (argsLength > numArgs) {
  17606. info('Command ' + fn + ': expected [0,' + numArgs +
  17607. '] args, but received ' + argsLength + ' args');
  17608. }
  17609. // TODO figure out how to type-check vararg functions
  17610. this.preprocessCommand(fn, args);
  17611. operation.fn = fn;
  17612. operation.args = args;
  17613. return true;
  17614. } else {
  17615. if (isEOF(obj)) {
  17616. return false; // no more commands
  17617. }
  17618. // argument
  17619. if (obj !== null) {
  17620. if (!args) {
  17621. args = [];
  17622. }
  17623. args.push((obj instanceof Dict ? obj.getAll() : obj));
  17624. assert(args.length <= 33, 'Too many arguments');
  17625. }
  17626. }
  17627. }
  17628. },
  17629. preprocessCommand:
  17630. function EvaluatorPreprocessor_preprocessCommand(fn, args) {
  17631. switch (fn | 0) {
  17632. case OPS.save:
  17633. this.stateManager.save();
  17634. break;
  17635. case OPS.restore:
  17636. this.stateManager.restore();
  17637. break;
  17638. case OPS.transform:
  17639. this.stateManager.transform(args);
  17640. break;
  17641. }
  17642. }
  17643. };
  17644. return EvaluatorPreprocessor;
  17645. })();
  17646. var QueueOptimizer = (function QueueOptimizerClosure() {
  17647. function addState(parentState, pattern, fn) {
  17648. var state = parentState;
  17649. for (var i = 0, ii = pattern.length - 1; i < ii; i++) {
  17650. var item = pattern[i];
  17651. state = (state[item] || (state[item] = []));
  17652. }
  17653. state[pattern[pattern.length - 1]] = fn;
  17654. }
  17655. function handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
  17656. argsArray) {
  17657. // Handles special case of mainly LaTeX documents which use image masks to
  17658. // draw lines with the current fill style.
  17659. // 'count' groups of (save, transform, paintImageMaskXObject, restore)+
  17660. // have been found at iFirstSave.
  17661. var iFirstPIMXO = iFirstSave + 2;
  17662. for (var i = 0; i < count; i++) {
  17663. var arg = argsArray[iFirstPIMXO + 4 * i];
  17664. var imageMask = arg.length === 1 && arg[0];
  17665. if (imageMask && imageMask.width === 1 && imageMask.height === 1 &&
  17666. (!imageMask.data.length ||
  17667. (imageMask.data.length === 1 && imageMask.data[0] === 0))) {
  17668. fnArray[iFirstPIMXO + 4 * i] = OPS.paintSolidColorImageMask;
  17669. continue;
  17670. }
  17671. break;
  17672. }
  17673. return count - i;
  17674. }
  17675. var InitialState = [];
  17676. // This replaces (save, transform, paintInlineImageXObject, restore)+
  17677. // sequences with one |paintInlineImageXObjectGroup| operation.
  17678. addState(InitialState,
  17679. [OPS.save, OPS.transform, OPS.paintInlineImageXObject, OPS.restore],
  17680. function foundInlineImageGroup(context) {
  17681. var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
  17682. var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
  17683. var MAX_WIDTH = 1000;
  17684. var IMAGE_PADDING = 1;
  17685. var fnArray = context.fnArray, argsArray = context.argsArray;
  17686. var curr = context.iCurr;
  17687. var iFirstSave = curr - 3;
  17688. var iFirstTransform = curr - 2;
  17689. var iFirstPIIXO = curr - 1;
  17690. // Look for the quartets.
  17691. var i = iFirstSave + 4;
  17692. var ii = fnArray.length;
  17693. while (i + 3 < ii) {
  17694. if (fnArray[i] !== OPS.save ||
  17695. fnArray[i + 1] !== OPS.transform ||
  17696. fnArray[i + 2] !== OPS.paintInlineImageXObject ||
  17697. fnArray[i + 3] !== OPS.restore) {
  17698. break; // ops don't match
  17699. }
  17700. i += 4;
  17701. }
  17702. // At this point, i is the index of the first op past the last valid
  17703. // quartet.
  17704. var count = Math.min((i - iFirstSave) / 4,
  17705. MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);
  17706. if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {
  17707. return i;
  17708. }
  17709. // assuming that heights of those image is too small (~1 pixel)
  17710. // packing as much as possible by lines
  17711. var maxX = 0;
  17712. var map = [], maxLineHeight = 0;
  17713. var currentX = IMAGE_PADDING, currentY = IMAGE_PADDING;
  17714. var q;
  17715. for (q = 0; q < count; q++) {
  17716. var transform = argsArray[iFirstTransform + (q << 2)];
  17717. var img = argsArray[iFirstPIIXO + (q << 2)][0];
  17718. if (currentX + img.width > MAX_WIDTH) {
  17719. // starting new line
  17720. maxX = Math.max(maxX, currentX);
  17721. currentY += maxLineHeight + 2 * IMAGE_PADDING;
  17722. currentX = 0;
  17723. maxLineHeight = 0;
  17724. }
  17725. map.push({
  17726. transform: transform,
  17727. x: currentX, y: currentY,
  17728. w: img.width, h: img.height
  17729. });
  17730. currentX += img.width + 2 * IMAGE_PADDING;
  17731. maxLineHeight = Math.max(maxLineHeight, img.height);
  17732. }
  17733. var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;
  17734. var imgHeight = currentY + maxLineHeight + IMAGE_PADDING;
  17735. var imgData = new Uint8Array(imgWidth * imgHeight * 4);
  17736. var imgRowSize = imgWidth << 2;
  17737. for (q = 0; q < count; q++) {
  17738. var data = argsArray[iFirstPIIXO + (q << 2)][0].data;
  17739. // Copy image by lines and extends pixels into padding.
  17740. var rowSize = map[q].w << 2;
  17741. var dataOffset = 0;
  17742. var offset = (map[q].x + map[q].y * imgWidth) << 2;
  17743. imgData.set(data.subarray(0, rowSize), offset - imgRowSize);
  17744. for (var k = 0, kk = map[q].h; k < kk; k++) {
  17745. imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);
  17746. dataOffset += rowSize;
  17747. offset += imgRowSize;
  17748. }
  17749. imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);
  17750. while (offset >= 0) {
  17751. data[offset - 4] = data[offset];
  17752. data[offset - 3] = data[offset + 1];
  17753. data[offset - 2] = data[offset + 2];
  17754. data[offset - 1] = data[offset + 3];
  17755. data[offset + rowSize] = data[offset + rowSize - 4];
  17756. data[offset + rowSize + 1] = data[offset + rowSize - 3];
  17757. data[offset + rowSize + 2] = data[offset + rowSize - 2];
  17758. data[offset + rowSize + 3] = data[offset + rowSize - 1];
  17759. offset -= imgRowSize;
  17760. }
  17761. }
  17762. // Replace queue items.
  17763. fnArray.splice(iFirstSave, count * 4, OPS.paintInlineImageXObjectGroup);
  17764. argsArray.splice(iFirstSave, count * 4,
  17765. [{ width: imgWidth, height: imgHeight, kind: ImageKind.RGBA_32BPP,
  17766. data: imgData }, map]);
  17767. return iFirstSave + 1;
  17768. });
  17769. // This replaces (save, transform, paintImageMaskXObject, restore)+
  17770. // sequences with one |paintImageMaskXObjectGroup| or one
  17771. // |paintImageMaskXObjectRepeat| operation.
  17772. addState(InitialState,
  17773. [OPS.save, OPS.transform, OPS.paintImageMaskXObject, OPS.restore],
  17774. function foundImageMaskGroup(context) {
  17775. var MIN_IMAGES_IN_MASKS_BLOCK = 10;
  17776. var MAX_IMAGES_IN_MASKS_BLOCK = 100;
  17777. var MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;
  17778. var fnArray = context.fnArray, argsArray = context.argsArray;
  17779. var curr = context.iCurr;
  17780. var iFirstSave = curr - 3;
  17781. var iFirstTransform = curr - 2;
  17782. var iFirstPIMXO = curr - 1;
  17783. // Look for the quartets.
  17784. var i = iFirstSave + 4;
  17785. var ii = fnArray.length;
  17786. while (i + 3 < ii) {
  17787. if (fnArray[i] !== OPS.save ||
  17788. fnArray[i + 1] !== OPS.transform ||
  17789. fnArray[i + 2] !== OPS.paintImageMaskXObject ||
  17790. fnArray[i + 3] !== OPS.restore) {
  17791. break; // ops don't match
  17792. }
  17793. i += 4;
  17794. }
  17795. // At this point, i is the index of the first op past the last valid
  17796. // quartet.
  17797. var count = (i - iFirstSave) / 4;
  17798. count = handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
  17799. argsArray);
  17800. if (count < MIN_IMAGES_IN_MASKS_BLOCK) {
  17801. return i;
  17802. }
  17803. var q;
  17804. var isSameImage = false;
  17805. var iTransform, transformArgs;
  17806. var firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
  17807. if (argsArray[iFirstTransform][1] === 0 &&
  17808. argsArray[iFirstTransform][2] === 0) {
  17809. isSameImage = true;
  17810. var firstTransformArg0 = argsArray[iFirstTransform][0];
  17811. var firstTransformArg3 = argsArray[iFirstTransform][3];
  17812. iTransform = iFirstTransform + 4;
  17813. var iPIMXO = iFirstPIMXO + 4;
  17814. for (q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) {
  17815. transformArgs = argsArray[iTransform];
  17816. if (argsArray[iPIMXO][0] !== firstPIMXOArg0 ||
  17817. transformArgs[0] !== firstTransformArg0 ||
  17818. transformArgs[1] !== 0 ||
  17819. transformArgs[2] !== 0 ||
  17820. transformArgs[3] !== firstTransformArg3) {
  17821. if (q < MIN_IMAGES_IN_MASKS_BLOCK) {
  17822. isSameImage = false;
  17823. } else {
  17824. count = q;
  17825. }
  17826. break; // different image or transform
  17827. }
  17828. }
  17829. }
  17830. if (isSameImage) {
  17831. count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);
  17832. var positions = new Float32Array(count * 2);
  17833. iTransform = iFirstTransform;
  17834. for (q = 0; q < count; q++, iTransform += 4) {
  17835. transformArgs = argsArray[iTransform];
  17836. positions[(q << 1)] = transformArgs[4];
  17837. positions[(q << 1) + 1] = transformArgs[5];
  17838. }
  17839. // Replace queue items.
  17840. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectRepeat);
  17841. argsArray.splice(iFirstSave, count * 4,
  17842. [firstPIMXOArg0, firstTransformArg0, firstTransformArg3, positions]);
  17843. } else {
  17844. count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);
  17845. var images = [];
  17846. for (q = 0; q < count; q++) {
  17847. transformArgs = argsArray[iFirstTransform + (q << 2)];
  17848. var maskParams = argsArray[iFirstPIMXO + (q << 2)][0];
  17849. images.push({ data: maskParams.data, width: maskParams.width,
  17850. height: maskParams.height,
  17851. transform: transformArgs });
  17852. }
  17853. // Replace queue items.
  17854. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectGroup);
  17855. argsArray.splice(iFirstSave, count * 4, [images]);
  17856. }
  17857. return iFirstSave + 1;
  17858. });
  17859. // This replaces (save, transform, paintImageXObject, restore)+ sequences
  17860. // with one paintImageXObjectRepeat operation, if the |transform| and
  17861. // |paintImageXObjectRepeat| ops are appropriate.
  17862. addState(InitialState,
  17863. [OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore],
  17864. function (context) {
  17865. var MIN_IMAGES_IN_BLOCK = 3;
  17866. var MAX_IMAGES_IN_BLOCK = 1000;
  17867. var fnArray = context.fnArray, argsArray = context.argsArray;
  17868. var curr = context.iCurr;
  17869. var iFirstSave = curr - 3;
  17870. var iFirstTransform = curr - 2;
  17871. var iFirstPIXO = curr - 1;
  17872. var iFirstRestore = curr;
  17873. if (argsArray[iFirstTransform][1] !== 0 ||
  17874. argsArray[iFirstTransform][2] !== 0) {
  17875. return iFirstRestore + 1; // transform has the wrong form
  17876. }
  17877. // Look for the quartets.
  17878. var firstPIXOArg0 = argsArray[iFirstPIXO][0];
  17879. var firstTransformArg0 = argsArray[iFirstTransform][0];
  17880. var firstTransformArg3 = argsArray[iFirstTransform][3];
  17881. var i = iFirstSave + 4;
  17882. var ii = fnArray.length;
  17883. while (i + 3 < ii) {
  17884. if (fnArray[i] !== OPS.save ||
  17885. fnArray[i + 1] !== OPS.transform ||
  17886. fnArray[i + 2] !== OPS.paintImageXObject ||
  17887. fnArray[i + 3] !== OPS.restore) {
  17888. break; // ops don't match
  17889. }
  17890. if (argsArray[i + 1][0] !== firstTransformArg0 ||
  17891. argsArray[i + 1][1] !== 0 ||
  17892. argsArray[i + 1][2] !== 0 ||
  17893. argsArray[i + 1][3] !== firstTransformArg3) {
  17894. break; // transforms don't match
  17895. }
  17896. if (argsArray[i + 2][0] !== firstPIXOArg0) {
  17897. break; // images don't match
  17898. }
  17899. i += 4;
  17900. }
  17901. // At this point, i is the index of the first op past the last valid
  17902. // quartet.
  17903. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_BLOCK);
  17904. if (count < MIN_IMAGES_IN_BLOCK) {
  17905. return i;
  17906. }
  17907. // Extract the (x,y) positions from all of the matching transforms.
  17908. var positions = new Float32Array(count * 2);
  17909. var iTransform = iFirstTransform;
  17910. for (var q = 0; q < count; q++, iTransform += 4) {
  17911. var transformArgs = argsArray[iTransform];
  17912. positions[(q << 1)] = transformArgs[4];
  17913. positions[(q << 1) + 1] = transformArgs[5];
  17914. }
  17915. // Replace queue items.
  17916. var args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3,
  17917. positions];
  17918. fnArray.splice(iFirstSave, count * 4, OPS.paintImageXObjectRepeat);
  17919. argsArray.splice(iFirstSave, count * 4, args);
  17920. return iFirstSave + 1;
  17921. });
  17922. // This replaces (beginText, setFont, setTextMatrix, showText, endText)+
  17923. // sequences with (beginText, setFont, (setTextMatrix, showText)+, endText)+
  17924. // sequences, if the font for each one is the same.
  17925. addState(InitialState,
  17926. [OPS.beginText, OPS.setFont, OPS.setTextMatrix, OPS.showText, OPS.endText],
  17927. function (context) {
  17928. var MIN_CHARS_IN_BLOCK = 3;
  17929. var MAX_CHARS_IN_BLOCK = 1000;
  17930. var fnArray = context.fnArray, argsArray = context.argsArray;
  17931. var curr = context.iCurr;
  17932. var iFirstBeginText = curr - 4;
  17933. var iFirstSetFont = curr - 3;
  17934. var iFirstSetTextMatrix = curr - 2;
  17935. var iFirstShowText = curr - 1;
  17936. var iFirstEndText = curr;
  17937. // Look for the quintets.
  17938. var firstSetFontArg0 = argsArray[iFirstSetFont][0];
  17939. var firstSetFontArg1 = argsArray[iFirstSetFont][1];
  17940. var i = iFirstBeginText + 5;
  17941. var ii = fnArray.length;
  17942. while (i + 4 < ii) {
  17943. if (fnArray[i] !== OPS.beginText ||
  17944. fnArray[i + 1] !== OPS.setFont ||
  17945. fnArray[i + 2] !== OPS.setTextMatrix ||
  17946. fnArray[i + 3] !== OPS.showText ||
  17947. fnArray[i + 4] !== OPS.endText) {
  17948. break; // ops don't match
  17949. }
  17950. if (argsArray[i + 1][0] !== firstSetFontArg0 ||
  17951. argsArray[i + 1][1] !== firstSetFontArg1) {
  17952. break; // fonts don't match
  17953. }
  17954. i += 5;
  17955. }
  17956. // At this point, i is the index of the first op past the last valid
  17957. // quintet.
  17958. var count = Math.min(((i - iFirstBeginText) / 5), MAX_CHARS_IN_BLOCK);
  17959. if (count < MIN_CHARS_IN_BLOCK) {
  17960. return i;
  17961. }
  17962. // If the preceding quintet is (<something>, setFont, setTextMatrix,
  17963. // showText, endText), include that as well. (E.g. <something> might be
  17964. // |dependency|.)
  17965. var iFirst = iFirstBeginText;
  17966. if (iFirstBeginText >= 4 &&
  17967. fnArray[iFirstBeginText - 4] === fnArray[iFirstSetFont] &&
  17968. fnArray[iFirstBeginText - 3] === fnArray[iFirstSetTextMatrix] &&
  17969. fnArray[iFirstBeginText - 2] === fnArray[iFirstShowText] &&
  17970. fnArray[iFirstBeginText - 1] === fnArray[iFirstEndText] &&
  17971. argsArray[iFirstBeginText - 4][0] === firstSetFontArg0 &&
  17972. argsArray[iFirstBeginText - 4][1] === firstSetFontArg1) {
  17973. count++;
  17974. iFirst -= 5;
  17975. }
  17976. // Remove (endText, beginText, setFont) trios.
  17977. var iEndText = iFirst + 4;
  17978. for (var q = 1; q < count; q++) {
  17979. fnArray.splice(iEndText, 3);
  17980. argsArray.splice(iEndText, 3);
  17981. iEndText += 2;
  17982. }
  17983. return iEndText + 1;
  17984. });
  17985. function QueueOptimizer() {}
  17986. QueueOptimizer.prototype = {
  17987. optimize: function QueueOptimizer_optimize(queue) {
  17988. var fnArray = queue.fnArray, argsArray = queue.argsArray;
  17989. var context = {
  17990. iCurr: 0,
  17991. fnArray: fnArray,
  17992. argsArray: argsArray
  17993. };
  17994. var state;
  17995. var i = 0, ii = fnArray.length;
  17996. while (i < ii) {
  17997. state = (state || InitialState)[fnArray[i]];
  17998. if (typeof state === 'function') { // we found some handler
  17999. context.iCurr = i;
  18000. // state() returns the index of the first non-matching op (if we
  18001. // didn't match) or the first op past the modified ops (if we did
  18002. // match and replace).
  18003. i = state(context);
  18004. state = undefined; // reset the state machine
  18005. ii = context.fnArray.length;
  18006. } else {
  18007. i++;
  18008. }
  18009. }
  18010. }
  18011. };
  18012. return QueueOptimizer;
  18013. })();
  18014. var BUILT_IN_CMAPS = [
  18015. // << Start unicode maps.
  18016. 'Adobe-GB1-UCS2',
  18017. 'Adobe-CNS1-UCS2',
  18018. 'Adobe-Japan1-UCS2',
  18019. 'Adobe-Korea1-UCS2',
  18020. // >> End unicode maps.
  18021. '78-EUC-H',
  18022. '78-EUC-V',
  18023. '78-H',
  18024. '78-RKSJ-H',
  18025. '78-RKSJ-V',
  18026. '78-V',
  18027. '78ms-RKSJ-H',
  18028. '78ms-RKSJ-V',
  18029. '83pv-RKSJ-H',
  18030. '90ms-RKSJ-H',
  18031. '90ms-RKSJ-V',
  18032. '90msp-RKSJ-H',
  18033. '90msp-RKSJ-V',
  18034. '90pv-RKSJ-H',
  18035. '90pv-RKSJ-V',
  18036. 'Add-H',
  18037. 'Add-RKSJ-H',
  18038. 'Add-RKSJ-V',
  18039. 'Add-V',
  18040. 'Adobe-CNS1-0',
  18041. 'Adobe-CNS1-1',
  18042. 'Adobe-CNS1-2',
  18043. 'Adobe-CNS1-3',
  18044. 'Adobe-CNS1-4',
  18045. 'Adobe-CNS1-5',
  18046. 'Adobe-CNS1-6',
  18047. 'Adobe-GB1-0',
  18048. 'Adobe-GB1-1',
  18049. 'Adobe-GB1-2',
  18050. 'Adobe-GB1-3',
  18051. 'Adobe-GB1-4',
  18052. 'Adobe-GB1-5',
  18053. 'Adobe-Japan1-0',
  18054. 'Adobe-Japan1-1',
  18055. 'Adobe-Japan1-2',
  18056. 'Adobe-Japan1-3',
  18057. 'Adobe-Japan1-4',
  18058. 'Adobe-Japan1-5',
  18059. 'Adobe-Japan1-6',
  18060. 'Adobe-Korea1-0',
  18061. 'Adobe-Korea1-1',
  18062. 'Adobe-Korea1-2',
  18063. 'B5-H',
  18064. 'B5-V',
  18065. 'B5pc-H',
  18066. 'B5pc-V',
  18067. 'CNS-EUC-H',
  18068. 'CNS-EUC-V',
  18069. 'CNS1-H',
  18070. 'CNS1-V',
  18071. 'CNS2-H',
  18072. 'CNS2-V',
  18073. 'ETHK-B5-H',
  18074. 'ETHK-B5-V',
  18075. 'ETen-B5-H',
  18076. 'ETen-B5-V',
  18077. 'ETenms-B5-H',
  18078. 'ETenms-B5-V',
  18079. 'EUC-H',
  18080. 'EUC-V',
  18081. 'Ext-H',
  18082. 'Ext-RKSJ-H',
  18083. 'Ext-RKSJ-V',
  18084. 'Ext-V',
  18085. 'GB-EUC-H',
  18086. 'GB-EUC-V',
  18087. 'GB-H',
  18088. 'GB-V',
  18089. 'GBK-EUC-H',
  18090. 'GBK-EUC-V',
  18091. 'GBK2K-H',
  18092. 'GBK2K-V',
  18093. 'GBKp-EUC-H',
  18094. 'GBKp-EUC-V',
  18095. 'GBT-EUC-H',
  18096. 'GBT-EUC-V',
  18097. 'GBT-H',
  18098. 'GBT-V',
  18099. 'GBTpc-EUC-H',
  18100. 'GBTpc-EUC-V',
  18101. 'GBpc-EUC-H',
  18102. 'GBpc-EUC-V',
  18103. 'H',
  18104. 'HKdla-B5-H',
  18105. 'HKdla-B5-V',
  18106. 'HKdlb-B5-H',
  18107. 'HKdlb-B5-V',
  18108. 'HKgccs-B5-H',
  18109. 'HKgccs-B5-V',
  18110. 'HKm314-B5-H',
  18111. 'HKm314-B5-V',
  18112. 'HKm471-B5-H',
  18113. 'HKm471-B5-V',
  18114. 'HKscs-B5-H',
  18115. 'HKscs-B5-V',
  18116. 'Hankaku',
  18117. 'Hiragana',
  18118. 'KSC-EUC-H',
  18119. 'KSC-EUC-V',
  18120. 'KSC-H',
  18121. 'KSC-Johab-H',
  18122. 'KSC-Johab-V',
  18123. 'KSC-V',
  18124. 'KSCms-UHC-H',
  18125. 'KSCms-UHC-HW-H',
  18126. 'KSCms-UHC-HW-V',
  18127. 'KSCms-UHC-V',
  18128. 'KSCpc-EUC-H',
  18129. 'KSCpc-EUC-V',
  18130. 'Katakana',
  18131. 'NWP-H',
  18132. 'NWP-V',
  18133. 'RKSJ-H',
  18134. 'RKSJ-V',
  18135. 'Roman',
  18136. 'UniCNS-UCS2-H',
  18137. 'UniCNS-UCS2-V',
  18138. 'UniCNS-UTF16-H',
  18139. 'UniCNS-UTF16-V',
  18140. 'UniCNS-UTF32-H',
  18141. 'UniCNS-UTF32-V',
  18142. 'UniCNS-UTF8-H',
  18143. 'UniCNS-UTF8-V',
  18144. 'UniGB-UCS2-H',
  18145. 'UniGB-UCS2-V',
  18146. 'UniGB-UTF16-H',
  18147. 'UniGB-UTF16-V',
  18148. 'UniGB-UTF32-H',
  18149. 'UniGB-UTF32-V',
  18150. 'UniGB-UTF8-H',
  18151. 'UniGB-UTF8-V',
  18152. 'UniJIS-UCS2-H',
  18153. 'UniJIS-UCS2-HW-H',
  18154. 'UniJIS-UCS2-HW-V',
  18155. 'UniJIS-UCS2-V',
  18156. 'UniJIS-UTF16-H',
  18157. 'UniJIS-UTF16-V',
  18158. 'UniJIS-UTF32-H',
  18159. 'UniJIS-UTF32-V',
  18160. 'UniJIS-UTF8-H',
  18161. 'UniJIS-UTF8-V',
  18162. 'UniJIS2004-UTF16-H',
  18163. 'UniJIS2004-UTF16-V',
  18164. 'UniJIS2004-UTF32-H',
  18165. 'UniJIS2004-UTF32-V',
  18166. 'UniJIS2004-UTF8-H',
  18167. 'UniJIS2004-UTF8-V',
  18168. 'UniJISPro-UCS2-HW-V',
  18169. 'UniJISPro-UCS2-V',
  18170. 'UniJISPro-UTF8-V',
  18171. 'UniJISX0213-UTF32-H',
  18172. 'UniJISX0213-UTF32-V',
  18173. 'UniJISX02132004-UTF32-H',
  18174. 'UniJISX02132004-UTF32-V',
  18175. 'UniKS-UCS2-H',
  18176. 'UniKS-UCS2-V',
  18177. 'UniKS-UTF16-H',
  18178. 'UniKS-UTF16-V',
  18179. 'UniKS-UTF32-H',
  18180. 'UniKS-UTF32-V',
  18181. 'UniKS-UTF8-H',
  18182. 'UniKS-UTF8-V',
  18183. 'V',
  18184. 'WP-Symbol'];
  18185. // CMap, not to be confused with TrueType's cmap.
  18186. var CMap = (function CMapClosure() {
  18187. function CMap(builtInCMap) {
  18188. // Codespace ranges are stored as follows:
  18189. // [[1BytePairs], [2BytePairs], [3BytePairs], [4BytePairs]]
  18190. // where nBytePairs are ranges e.g. [low1, high1, low2, high2, ...]
  18191. this.codespaceRanges = [[], [], [], []];
  18192. this.numCodespaceRanges = 0;
  18193. // Map entries have one of two forms.
  18194. // - cid chars are 16-bit unsigned integers, stored as integers.
  18195. // - bf chars are variable-length byte sequences, stored as strings, with
  18196. // one byte per character.
  18197. this._map = [];
  18198. this.name = '';
  18199. this.vertical = false;
  18200. this.useCMap = null;
  18201. this.builtInCMap = builtInCMap;
  18202. }
  18203. CMap.prototype = {
  18204. addCodespaceRange: function(n, low, high) {
  18205. this.codespaceRanges[n - 1].push(low, high);
  18206. this.numCodespaceRanges++;
  18207. },
  18208. mapCidRange: function(low, high, dstLow) {
  18209. while (low <= high) {
  18210. this._map[low++] = dstLow++;
  18211. }
  18212. },
  18213. mapBfRange: function(low, high, dstLow) {
  18214. var lastByte = dstLow.length - 1;
  18215. while (low <= high) {
  18216. this._map[low++] = dstLow;
  18217. // Only the last byte has to be incremented.
  18218. dstLow = dstLow.substr(0, lastByte) +
  18219. String.fromCharCode(dstLow.charCodeAt(lastByte) + 1);
  18220. }
  18221. },
  18222. mapBfRangeToArray: function(low, high, array) {
  18223. var i = 0, ii = array.length;
  18224. while (low <= high && i < ii) {
  18225. this._map[low] = array[i++];
  18226. ++low;
  18227. }
  18228. },
  18229. // This is used for both bf and cid chars.
  18230. mapOne: function(src, dst) {
  18231. this._map[src] = dst;
  18232. },
  18233. lookup: function(code) {
  18234. return this._map[code];
  18235. },
  18236. contains: function(code) {
  18237. return this._map[code] !== undefined;
  18238. },
  18239. forEach: function(callback) {
  18240. // Most maps have fewer than 65536 entries, and for those we use normal
  18241. // array iteration. But really sparse tables are possible -- e.g. with
  18242. // indices in the *billions*. For such tables we use for..in, which isn't
  18243. // ideal because it stringifies the indices for all present elements, but
  18244. // it does avoid iterating over every undefined entry.
  18245. var map = this._map;
  18246. var length = map.length;
  18247. var i;
  18248. if (length <= 0x10000) {
  18249. for (i = 0; i < length; i++) {
  18250. if (map[i] !== undefined) {
  18251. callback(i, map[i]);
  18252. }
  18253. }
  18254. } else {
  18255. for (i in this._map) {
  18256. callback(i, map[i]);
  18257. }
  18258. }
  18259. },
  18260. charCodeOf: function(value) {
  18261. return this._map.indexOf(value);
  18262. },
  18263. getMap: function() {
  18264. return this._map;
  18265. },
  18266. readCharCode: function(str, offset, out) {
  18267. var c = 0;
  18268. var codespaceRanges = this.codespaceRanges;
  18269. var codespaceRangesLen = this.codespaceRanges.length;
  18270. // 9.7.6.2 CMap Mapping
  18271. // The code length is at most 4.
  18272. for (var n = 0; n < codespaceRangesLen; n++) {
  18273. c = ((c << 8) | str.charCodeAt(offset + n)) >>> 0;
  18274. // Check each codespace range to see if it falls within.
  18275. var codespaceRange = codespaceRanges[n];
  18276. for (var k = 0, kk = codespaceRange.length; k < kk;) {
  18277. var low = codespaceRange[k++];
  18278. var high = codespaceRange[k++];
  18279. if (c >= low && c <= high) {
  18280. out.charcode = c;
  18281. out.length = n + 1;
  18282. return;
  18283. }
  18284. }
  18285. }
  18286. out.charcode = 0;
  18287. out.length = 1;
  18288. },
  18289. get length() {
  18290. return this._map.length;
  18291. },
  18292. get isIdentityCMap() {
  18293. if (!(this.name === 'Identity-H' || this.name === 'Identity-V')) {
  18294. return false;
  18295. }
  18296. if (this._map.length !== 0x10000) {
  18297. return false;
  18298. }
  18299. for (var i = 0; i < 0x10000; i++) {
  18300. if (this._map[i] !== i) {
  18301. return false;
  18302. }
  18303. }
  18304. return true;
  18305. }
  18306. };
  18307. return CMap;
  18308. })();
  18309. // A special case of CMap, where the _map array implicitly has a length of
  18310. // 65536 and each element is equal to its index.
  18311. var IdentityCMap = (function IdentityCMapClosure() {
  18312. function IdentityCMap(vertical, n) {
  18313. CMap.call(this);
  18314. this.vertical = vertical;
  18315. this.addCodespaceRange(n, 0, 0xffff);
  18316. }
  18317. Util.inherit(IdentityCMap, CMap, {});
  18318. IdentityCMap.prototype = {
  18319. addCodespaceRange: CMap.prototype.addCodespaceRange,
  18320. mapCidRange: function(low, high, dstLow) {
  18321. error('should not call mapCidRange');
  18322. },
  18323. mapBfRange: function(low, high, dstLow) {
  18324. error('should not call mapBfRange');
  18325. },
  18326. mapBfRangeToArray: function(low, high, array) {
  18327. error('should not call mapBfRangeToArray');
  18328. },
  18329. mapOne: function(src, dst) {
  18330. error('should not call mapCidOne');
  18331. },
  18332. lookup: function(code) {
  18333. return (isInt(code) && code <= 0xffff) ? code : undefined;
  18334. },
  18335. contains: function(code) {
  18336. return isInt(code) && code <= 0xffff;
  18337. },
  18338. forEach: function(callback) {
  18339. for (var i = 0; i <= 0xffff; i++) {
  18340. callback(i, i);
  18341. }
  18342. },
  18343. charCodeOf: function(value) {
  18344. return (isInt(value) && value <= 0xffff) ? value : -1;
  18345. },
  18346. getMap: function() {
  18347. // Sometimes identity maps must be instantiated, but it's rare.
  18348. var map = new Array(0x10000);
  18349. for (var i = 0; i <= 0xffff; i++) {
  18350. map[i] = i;
  18351. }
  18352. return map;
  18353. },
  18354. readCharCode: CMap.prototype.readCharCode,
  18355. get length() {
  18356. return 0x10000;
  18357. },
  18358. get isIdentityCMap() {
  18359. error('should not access .isIdentityCMap');
  18360. }
  18361. };
  18362. return IdentityCMap;
  18363. })();
  18364. var BinaryCMapReader = (function BinaryCMapReaderClosure() {
  18365. function fetchBinaryData(url) {
  18366. var nonBinaryRequest = PDFJS.disableWorker;
  18367. var request = new XMLHttpRequest();
  18368. request.open('GET', url, false);
  18369. if (!nonBinaryRequest) {
  18370. try {
  18371. request.responseType = 'arraybuffer';
  18372. nonBinaryRequest = request.responseType !== 'arraybuffer';
  18373. } catch (e) {
  18374. nonBinaryRequest = true;
  18375. }
  18376. }
  18377. if (nonBinaryRequest && request.overrideMimeType) {
  18378. request.overrideMimeType('text/plain; charset=x-user-defined');
  18379. }
  18380. request.send(null);
  18381. if (nonBinaryRequest ? !request.responseText : !request.response) {
  18382. error('Unable to get binary cMap at: ' + url);
  18383. }
  18384. if (nonBinaryRequest) {
  18385. var data = Array.prototype.map.call(request.responseText, function (ch) {
  18386. return ch.charCodeAt(0) & 255;
  18387. });
  18388. return new Uint8Array(data);
  18389. }
  18390. return new Uint8Array(request.response);
  18391. }
  18392. function hexToInt(a, size) {
  18393. var n = 0;
  18394. for (var i = 0; i <= size; i++) {
  18395. n = (n << 8) | a[i];
  18396. }
  18397. return n >>> 0;
  18398. }
  18399. function hexToStr(a, size) {
  18400. // This code is hot. Special-case some common values to avoid creating an
  18401. // object with subarray().
  18402. if (size === 1) {
  18403. return String.fromCharCode(a[0], a[1]);
  18404. }
  18405. if (size === 3) {
  18406. return String.fromCharCode(a[0], a[1], a[2], a[3]);
  18407. }
  18408. return String.fromCharCode.apply(null, a.subarray(0, size + 1));
  18409. }
  18410. function addHex(a, b, size) {
  18411. var c = 0;
  18412. for (var i = size; i >= 0; i--) {
  18413. c += a[i] + b[i];
  18414. a[i] = c & 255;
  18415. c >>= 8;
  18416. }
  18417. }
  18418. function incHex(a, size) {
  18419. var c = 1;
  18420. for (var i = size; i >= 0 && c > 0; i--) {
  18421. c += a[i];
  18422. a[i] = c & 255;
  18423. c >>= 8;
  18424. }
  18425. }
  18426. var MAX_NUM_SIZE = 16;
  18427. var MAX_ENCODED_NUM_SIZE = 19; // ceil(MAX_NUM_SIZE * 7 / 8)
  18428. function BinaryCMapStream(data) {
  18429. this.buffer = data;
  18430. this.pos = 0;
  18431. this.end = data.length;
  18432. this.tmpBuf = new Uint8Array(MAX_ENCODED_NUM_SIZE);
  18433. }
  18434. BinaryCMapStream.prototype = {
  18435. readByte: function () {
  18436. if (this.pos >= this.end) {
  18437. return -1;
  18438. }
  18439. return this.buffer[this.pos++];
  18440. },
  18441. readNumber: function () {
  18442. var n = 0;
  18443. var last;
  18444. do {
  18445. var b = this.readByte();
  18446. if (b < 0) {
  18447. error('unexpected EOF in bcmap');
  18448. }
  18449. last = !(b & 0x80);
  18450. n = (n << 7) | (b & 0x7F);
  18451. } while (!last);
  18452. return n;
  18453. },
  18454. readSigned: function () {
  18455. var n = this.readNumber();
  18456. return (n & 1) ? ~(n >>> 1) : n >>> 1;
  18457. },
  18458. readHex: function (num, size) {
  18459. num.set(this.buffer.subarray(this.pos,
  18460. this.pos + size + 1));
  18461. this.pos += size + 1;
  18462. },
  18463. readHexNumber: function (num, size) {
  18464. var last;
  18465. var stack = this.tmpBuf, sp = 0;
  18466. do {
  18467. var b = this.readByte();
  18468. if (b < 0) {
  18469. error('unexpected EOF in bcmap');
  18470. }
  18471. last = !(b & 0x80);
  18472. stack[sp++] = b & 0x7F;
  18473. } while (!last);
  18474. var i = size, buffer = 0, bufferSize = 0;
  18475. while (i >= 0) {
  18476. while (bufferSize < 8 && stack.length > 0) {
  18477. buffer = (stack[--sp] << bufferSize) | buffer;
  18478. bufferSize += 7;
  18479. }
  18480. num[i] = buffer & 255;
  18481. i--;
  18482. buffer >>= 8;
  18483. bufferSize -= 8;
  18484. }
  18485. },
  18486. readHexSigned: function (num, size) {
  18487. this.readHexNumber(num, size);
  18488. var sign = num[size] & 1 ? 255 : 0;
  18489. var c = 0;
  18490. for (var i = 0; i <= size; i++) {
  18491. c = ((c & 1) << 8) | num[i];
  18492. num[i] = (c >> 1) ^ sign;
  18493. }
  18494. },
  18495. readString: function () {
  18496. var len = this.readNumber();
  18497. var s = '';
  18498. for (var i = 0; i < len; i++) {
  18499. s += String.fromCharCode(this.readNumber());
  18500. }
  18501. return s;
  18502. }
  18503. };
  18504. function processBinaryCMap(url, cMap, extend) {
  18505. var data = fetchBinaryData(url);
  18506. var stream = new BinaryCMapStream(data);
  18507. var header = stream.readByte();
  18508. cMap.vertical = !!(header & 1);
  18509. var useCMap = null;
  18510. var start = new Uint8Array(MAX_NUM_SIZE);
  18511. var end = new Uint8Array(MAX_NUM_SIZE);
  18512. var char = new Uint8Array(MAX_NUM_SIZE);
  18513. var charCode = new Uint8Array(MAX_NUM_SIZE);
  18514. var tmp = new Uint8Array(MAX_NUM_SIZE);
  18515. var code;
  18516. var b;
  18517. while ((b = stream.readByte()) >= 0) {
  18518. var type = b >> 5;
  18519. if (type === 7) { // metadata, e.g. comment or usecmap
  18520. switch (b & 0x1F) {
  18521. case 0:
  18522. stream.readString(); // skipping comment
  18523. break;
  18524. case 1:
  18525. useCMap = stream.readString();
  18526. break;
  18527. }
  18528. continue;
  18529. }
  18530. var sequence = !!(b & 0x10);
  18531. var dataSize = b & 15;
  18532. assert(dataSize + 1 <= MAX_NUM_SIZE);
  18533. var ucs2DataSize = 1;
  18534. var subitemsCount = stream.readNumber();
  18535. var i;
  18536. switch (type) {
  18537. case 0: // codespacerange
  18538. stream.readHex(start, dataSize);
  18539. stream.readHexNumber(end, dataSize);
  18540. addHex(end, start, dataSize);
  18541. cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
  18542. hexToInt(end, dataSize));
  18543. for (i = 1; i < subitemsCount; i++) {
  18544. incHex(end, dataSize);
  18545. stream.readHexNumber(start, dataSize);
  18546. addHex(start, end, dataSize);
  18547. stream.readHexNumber(end, dataSize);
  18548. addHex(end, start, dataSize);
  18549. cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
  18550. hexToInt(end, dataSize));
  18551. }
  18552. break;
  18553. case 1: // notdefrange
  18554. stream.readHex(start, dataSize);
  18555. stream.readHexNumber(end, dataSize);
  18556. addHex(end, start, dataSize);
  18557. code = stream.readNumber();
  18558. // undefined range, skipping
  18559. for (i = 1; i < subitemsCount; i++) {
  18560. incHex(end, dataSize);
  18561. stream.readHexNumber(start, dataSize);
  18562. addHex(start, end, dataSize);
  18563. stream.readHexNumber(end, dataSize);
  18564. addHex(end, start, dataSize);
  18565. code = stream.readNumber();
  18566. // nop
  18567. }
  18568. break;
  18569. case 2: // cidchar
  18570. stream.readHex(char, dataSize);
  18571. code = stream.readNumber();
  18572. cMap.mapOne(hexToInt(char, dataSize), code);
  18573. for (i = 1; i < subitemsCount; i++) {
  18574. incHex(char, dataSize);
  18575. if (!sequence) {
  18576. stream.readHexNumber(tmp, dataSize);
  18577. addHex(char, tmp, dataSize);
  18578. }
  18579. code = stream.readSigned() + (code + 1);
  18580. cMap.mapOne(hexToInt(char, dataSize), code);
  18581. }
  18582. break;
  18583. case 3: // cidrange
  18584. stream.readHex(start, dataSize);
  18585. stream.readHexNumber(end, dataSize);
  18586. addHex(end, start, dataSize);
  18587. code = stream.readNumber();
  18588. cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
  18589. code);
  18590. for (i = 1; i < subitemsCount; i++) {
  18591. incHex(end, dataSize);
  18592. if (!sequence) {
  18593. stream.readHexNumber(start, dataSize);
  18594. addHex(start, end, dataSize);
  18595. } else {
  18596. start.set(end);
  18597. }
  18598. stream.readHexNumber(end, dataSize);
  18599. addHex(end, start, dataSize);
  18600. code = stream.readNumber();
  18601. cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
  18602. code);
  18603. }
  18604. break;
  18605. case 4: // bfchar
  18606. stream.readHex(char, ucs2DataSize);
  18607. stream.readHex(charCode, dataSize);
  18608. cMap.mapOne(hexToInt(char, ucs2DataSize),
  18609. hexToStr(charCode, dataSize));
  18610. for (i = 1; i < subitemsCount; i++) {
  18611. incHex(char, ucs2DataSize);
  18612. if (!sequence) {
  18613. stream.readHexNumber(tmp, ucs2DataSize);
  18614. addHex(char, tmp, ucs2DataSize);
  18615. }
  18616. incHex(charCode, dataSize);
  18617. stream.readHexSigned(tmp, dataSize);
  18618. addHex(charCode, tmp, dataSize);
  18619. cMap.mapOne(hexToInt(char, ucs2DataSize),
  18620. hexToStr(charCode, dataSize));
  18621. }
  18622. break;
  18623. case 5: // bfrange
  18624. stream.readHex(start, ucs2DataSize);
  18625. stream.readHexNumber(end, ucs2DataSize);
  18626. addHex(end, start, ucs2DataSize);
  18627. stream.readHex(charCode, dataSize);
  18628. cMap.mapBfRange(hexToInt(start, ucs2DataSize),
  18629. hexToInt(end, ucs2DataSize),
  18630. hexToStr(charCode, dataSize));
  18631. for (i = 1; i < subitemsCount; i++) {
  18632. incHex(end, ucs2DataSize);
  18633. if (!sequence) {
  18634. stream.readHexNumber(start, ucs2DataSize);
  18635. addHex(start, end, ucs2DataSize);
  18636. } else {
  18637. start.set(end);
  18638. }
  18639. stream.readHexNumber(end, ucs2DataSize);
  18640. addHex(end, start, ucs2DataSize);
  18641. stream.readHex(charCode, dataSize);
  18642. cMap.mapBfRange(hexToInt(start, ucs2DataSize),
  18643. hexToInt(end, ucs2DataSize),
  18644. hexToStr(charCode, dataSize));
  18645. }
  18646. break;
  18647. default:
  18648. error('Unknown type: ' + type);
  18649. break;
  18650. }
  18651. }
  18652. if (useCMap) {
  18653. extend(useCMap);
  18654. }
  18655. return cMap;
  18656. }
  18657. function BinaryCMapReader() {}
  18658. BinaryCMapReader.prototype = {
  18659. read: processBinaryCMap
  18660. };
  18661. return BinaryCMapReader;
  18662. })();
  18663. var CMapFactory = (function CMapFactoryClosure() {
  18664. function strToInt(str) {
  18665. var a = 0;
  18666. for (var i = 0; i < str.length; i++) {
  18667. a = (a << 8) | str.charCodeAt(i);
  18668. }
  18669. return a >>> 0;
  18670. }
  18671. function expectString(obj) {
  18672. if (!isString(obj)) {
  18673. error('Malformed CMap: expected string.');
  18674. }
  18675. }
  18676. function expectInt(obj) {
  18677. if (!isInt(obj)) {
  18678. error('Malformed CMap: expected int.');
  18679. }
  18680. }
  18681. function parseBfChar(cMap, lexer) {
  18682. while (true) {
  18683. var obj = lexer.getObj();
  18684. if (isEOF(obj)) {
  18685. break;
  18686. }
  18687. if (isCmd(obj, 'endbfchar')) {
  18688. return;
  18689. }
  18690. expectString(obj);
  18691. var src = strToInt(obj);
  18692. obj = lexer.getObj();
  18693. // TODO are /dstName used?
  18694. expectString(obj);
  18695. var dst = obj;
  18696. cMap.mapOne(src, dst);
  18697. }
  18698. }
  18699. function parseBfRange(cMap, lexer) {
  18700. while (true) {
  18701. var obj = lexer.getObj();
  18702. if (isEOF(obj)) {
  18703. break;
  18704. }
  18705. if (isCmd(obj, 'endbfrange')) {
  18706. return;
  18707. }
  18708. expectString(obj);
  18709. var low = strToInt(obj);
  18710. obj = lexer.getObj();
  18711. expectString(obj);
  18712. var high = strToInt(obj);
  18713. obj = lexer.getObj();
  18714. if (isInt(obj) || isString(obj)) {
  18715. var dstLow = isInt(obj) ? String.fromCharCode(obj) : obj;
  18716. cMap.mapBfRange(low, high, dstLow);
  18717. } else if (isCmd(obj, '[')) {
  18718. obj = lexer.getObj();
  18719. var array = [];
  18720. while (!isCmd(obj, ']') && !isEOF(obj)) {
  18721. array.push(obj);
  18722. obj = lexer.getObj();
  18723. }
  18724. cMap.mapBfRangeToArray(low, high, array);
  18725. } else {
  18726. break;
  18727. }
  18728. }
  18729. error('Invalid bf range.');
  18730. }
  18731. function parseCidChar(cMap, lexer) {
  18732. while (true) {
  18733. var obj = lexer.getObj();
  18734. if (isEOF(obj)) {
  18735. break;
  18736. }
  18737. if (isCmd(obj, 'endcidchar')) {
  18738. return;
  18739. }
  18740. expectString(obj);
  18741. var src = strToInt(obj);
  18742. obj = lexer.getObj();
  18743. expectInt(obj);
  18744. var dst = obj;
  18745. cMap.mapOne(src, dst);
  18746. }
  18747. }
  18748. function parseCidRange(cMap, lexer) {
  18749. while (true) {
  18750. var obj = lexer.getObj();
  18751. if (isEOF(obj)) {
  18752. break;
  18753. }
  18754. if (isCmd(obj, 'endcidrange')) {
  18755. return;
  18756. }
  18757. expectString(obj);
  18758. var low = strToInt(obj);
  18759. obj = lexer.getObj();
  18760. expectString(obj);
  18761. var high = strToInt(obj);
  18762. obj = lexer.getObj();
  18763. expectInt(obj);
  18764. var dstLow = obj;
  18765. cMap.mapCidRange(low, high, dstLow);
  18766. }
  18767. }
  18768. function parseCodespaceRange(cMap, lexer) {
  18769. while (true) {
  18770. var obj = lexer.getObj();
  18771. if (isEOF(obj)) {
  18772. break;
  18773. }
  18774. if (isCmd(obj, 'endcodespacerange')) {
  18775. return;
  18776. }
  18777. if (!isString(obj)) {
  18778. break;
  18779. }
  18780. var low = strToInt(obj);
  18781. obj = lexer.getObj();
  18782. if (!isString(obj)) {
  18783. break;
  18784. }
  18785. var high = strToInt(obj);
  18786. cMap.addCodespaceRange(obj.length, low, high);
  18787. }
  18788. error('Invalid codespace range.');
  18789. }
  18790. function parseWMode(cMap, lexer) {
  18791. var obj = lexer.getObj();
  18792. if (isInt(obj)) {
  18793. cMap.vertical = !!obj;
  18794. }
  18795. }
  18796. function parseCMapName(cMap, lexer) {
  18797. var obj = lexer.getObj();
  18798. if (isName(obj) && isString(obj.name)) {
  18799. cMap.name = obj.name;
  18800. }
  18801. }
  18802. function parseCMap(cMap, lexer, builtInCMapParams, useCMap) {
  18803. var previous;
  18804. var embededUseCMap;
  18805. objLoop: while (true) {
  18806. var obj = lexer.getObj();
  18807. if (isEOF(obj)) {
  18808. break;
  18809. } else if (isName(obj)) {
  18810. if (obj.name === 'WMode') {
  18811. parseWMode(cMap, lexer);
  18812. } else if (obj.name === 'CMapName') {
  18813. parseCMapName(cMap, lexer);
  18814. }
  18815. previous = obj;
  18816. } else if (isCmd(obj)) {
  18817. switch (obj.cmd) {
  18818. case 'endcmap':
  18819. break objLoop;
  18820. case 'usecmap':
  18821. if (isName(previous)) {
  18822. embededUseCMap = previous.name;
  18823. }
  18824. break;
  18825. case 'begincodespacerange':
  18826. parseCodespaceRange(cMap, lexer);
  18827. break;
  18828. case 'beginbfchar':
  18829. parseBfChar(cMap, lexer);
  18830. break;
  18831. case 'begincidchar':
  18832. parseCidChar(cMap, lexer);
  18833. break;
  18834. case 'beginbfrange':
  18835. parseBfRange(cMap, lexer);
  18836. break;
  18837. case 'begincidrange':
  18838. parseCidRange(cMap, lexer);
  18839. break;
  18840. }
  18841. }
  18842. }
  18843. if (!useCMap && embededUseCMap) {
  18844. // Load the usecmap definition from the file only if there wasn't one
  18845. // specified.
  18846. useCMap = embededUseCMap;
  18847. }
  18848. if (useCMap) {
  18849. extendCMap(cMap, builtInCMapParams, useCMap);
  18850. }
  18851. }
  18852. function extendCMap(cMap, builtInCMapParams, useCMap) {
  18853. cMap.useCMap = createBuiltInCMap(useCMap, builtInCMapParams);
  18854. // If there aren't any code space ranges defined clone all the parent ones
  18855. // into this cMap.
  18856. if (cMap.numCodespaceRanges === 0) {
  18857. var useCodespaceRanges = cMap.useCMap.codespaceRanges;
  18858. for (var i = 0; i < useCodespaceRanges.length; i++) {
  18859. cMap.codespaceRanges[i] = useCodespaceRanges[i].slice();
  18860. }
  18861. cMap.numCodespaceRanges = cMap.useCMap.numCodespaceRanges;
  18862. }
  18863. // Merge the map into the current one, making sure not to override
  18864. // any previously defined entries.
  18865. cMap.useCMap.forEach(function(key, value) {
  18866. if (!cMap.contains(key)) {
  18867. cMap.mapOne(key, cMap.useCMap.lookup(key));
  18868. }
  18869. });
  18870. }
  18871. function parseBinaryCMap(name, builtInCMapParams) {
  18872. var url = builtInCMapParams.url + name + '.bcmap';
  18873. var cMap = new CMap(true);
  18874. new BinaryCMapReader().read(url, cMap, function (useCMap) {
  18875. extendCMap(cMap, builtInCMapParams, useCMap);
  18876. });
  18877. return cMap;
  18878. }
  18879. function createBuiltInCMap(name, builtInCMapParams) {
  18880. if (name === 'Identity-H') {
  18881. return new IdentityCMap(false, 2);
  18882. } else if (name === 'Identity-V') {
  18883. return new IdentityCMap(true, 2);
  18884. }
  18885. if (BUILT_IN_CMAPS.indexOf(name) === -1) {
  18886. error('Unknown cMap name: ' + name);
  18887. }
  18888. assert(builtInCMapParams, 'built-in cMap parameters are not provided');
  18889. if (builtInCMapParams.packed) {
  18890. return parseBinaryCMap(name, builtInCMapParams);
  18891. }
  18892. var request = new XMLHttpRequest();
  18893. var url = builtInCMapParams.url + name;
  18894. request.open('GET', url, false);
  18895. request.send(null);
  18896. if (!request.responseText) {
  18897. error('Unable to get cMap at: ' + url);
  18898. }
  18899. var cMap = new CMap(true);
  18900. var lexer = new Lexer(new StringStream(request.responseText));
  18901. parseCMap(cMap, lexer, builtInCMapParams, null);
  18902. return cMap;
  18903. }
  18904. return {
  18905. create: function (encoding, builtInCMapParams, useCMap) {
  18906. if (isName(encoding)) {
  18907. return createBuiltInCMap(encoding.name, builtInCMapParams);
  18908. } else if (isStream(encoding)) {
  18909. var cMap = new CMap();
  18910. var lexer = new Lexer(encoding);
  18911. try {
  18912. parseCMap(cMap, lexer, builtInCMapParams, useCMap);
  18913. } catch (e) {
  18914. warn('Invalid CMap data. ' + e);
  18915. }
  18916. if (cMap.isIdentityCMap) {
  18917. return createBuiltInCMap(cMap.name, builtInCMapParams);
  18918. }
  18919. return cMap;
  18920. }
  18921. error('Encoding required.');
  18922. }
  18923. };
  18924. })();
  18925. // Unicode Private Use Area
  18926. var PRIVATE_USE_OFFSET_START = 0xE000;
  18927. var PRIVATE_USE_OFFSET_END = 0xF8FF;
  18928. var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false;
  18929. // PDF Glyph Space Units are one Thousandth of a TextSpace Unit
  18930. // except for Type 3 fonts
  18931. var PDF_GLYPH_SPACE_UNITS = 1000;
  18932. // Hinting is currently disabled due to unknown problems on windows
  18933. // in tracemonkey and various other pdfs with type1 fonts.
  18934. var HINTING_ENABLED = false;
  18935. // Accented charactars are not displayed properly on windows, using this flag
  18936. // to control analysis of seac charstrings.
  18937. var SEAC_ANALYSIS_ENABLED = false;
  18938. var FontFlags = {
  18939. FixedPitch: 1,
  18940. Serif: 2,
  18941. Symbolic: 4,
  18942. Script: 8,
  18943. Nonsymbolic: 32,
  18944. Italic: 64,
  18945. AllCap: 65536,
  18946. SmallCap: 131072,
  18947. ForceBold: 262144
  18948. };
  18949. var Encodings = {
  18950. ExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18951. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18952. 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle',
  18953. 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
  18954. 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
  18955. 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
  18956. 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
  18957. 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon',
  18958. 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior',
  18959. 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior',
  18960. 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior',
  18961. 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior',
  18962. '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '',
  18963. 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
  18964. 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
  18965. 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
  18966. 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
  18967. 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
  18968. 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '',
  18969. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18970. '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
  18971. '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall',
  18972. 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '',
  18973. 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall',
  18974. 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters',
  18975. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
  18976. 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior',
  18977. 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior',
  18978. 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior',
  18979. 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior',
  18980. 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior',
  18981. 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior',
  18982. 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall',
  18983. 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall',
  18984. 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
  18985. 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  18986. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
  18987. 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
  18988. 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  18989. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
  18990. 'Ydieresissmall'],
  18991. MacExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18992. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18993. 'space', 'exclamsmall', 'Hungarumlautsmall', 'centoldstyle',
  18994. 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall',
  18995. 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  18996. 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle',
  18997. 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle',
  18998. 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle',
  18999. 'nineoldstyle', 'colon', 'semicolon', '', 'threequartersemdash', '',
  19000. 'questionsmall', '', '', '', '', 'Ethsmall', '', '', 'onequarter',
  19001. 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
  19002. 'seveneighths', 'onethird', 'twothirds', '', '', '', '', '', '', 'ff',
  19003. 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior',
  19004. 'Circumflexsmall', 'hypheninferior', 'Gravesmall', 'Asmall', 'Bsmall',
  19005. 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
  19006. 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
  19007. 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  19008. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
  19009. 'Tildesmall', '', '', 'asuperior', 'centsuperior', '', '', '', '',
  19010. 'Aacutesmall', 'Agravesmall', 'Acircumflexsmall', 'Adieresissmall',
  19011. 'Atildesmall', 'Aringsmall', 'Ccedillasmall', 'Eacutesmall', 'Egravesmall',
  19012. 'Ecircumflexsmall', 'Edieresissmall', 'Iacutesmall', 'Igravesmall',
  19013. 'Icircumflexsmall', 'Idieresissmall', 'Ntildesmall', 'Oacutesmall',
  19014. 'Ogravesmall', 'Ocircumflexsmall', 'Odieresissmall', 'Otildesmall',
  19015. 'Uacutesmall', 'Ugravesmall', 'Ucircumflexsmall', 'Udieresissmall', '',
  19016. 'eightsuperior', 'fourinferior', 'threeinferior', 'sixinferior',
  19017. 'eightinferior', 'seveninferior', 'Scaronsmall', '', 'centinferior',
  19018. 'twoinferior', '', 'Dieresissmall', '', 'Caronsmall', 'osuperior',
  19019. 'fiveinferior', '', 'commainferior', 'periodinferior', 'Yacutesmall', '',
  19020. 'dollarinferior', '', 'Thornsmall', '', 'nineinferior', 'zeroinferior',
  19021. 'Zcaronsmall', 'AEsmall', 'Oslashsmall', 'questiondownsmall',
  19022. 'oneinferior', 'Lslashsmall', '', '', '', '', '', '', 'Cedillasmall', '',
  19023. '', '', '', '', 'OEsmall', 'figuredash', 'hyphensuperior', '', '', '', '',
  19024. 'exclamdownsmall', '', 'Ydieresissmall', '', 'onesuperior', 'twosuperior',
  19025. 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
  19026. 'sevensuperior', 'ninesuperior', 'zerosuperior', '', 'esuperior',
  19027. 'rsuperior', 'tsuperior', '', '', 'isuperior', 'ssuperior', 'dsuperior',
  19028. '', '', '', '', '', 'lsuperior', 'Ogoneksmall', 'Brevesmall',
  19029. 'Macronsmall', 'bsuperior', 'nsuperior', 'msuperior', 'commasuperior',
  19030. 'periodsuperior', 'Dotaccentsmall', 'Ringsmall'],
  19031. MacRomanEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19032. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19033. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  19034. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus',
  19035. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  19036. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  19037. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  19038. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  19039. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  19040. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  19041. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  19042. 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '',
  19043. 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis',
  19044. 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde',
  19045. 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  19046. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute',
  19047. 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave',
  19048. 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling',
  19049. 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright',
  19050. 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity',
  19051. 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff',
  19052. 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine',
  19053. 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot',
  19054. 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft',
  19055. 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE',
  19056. 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft',
  19057. 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction',
  19058. 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl',
  19059. 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand',
  19060. 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute',
  19061. 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple',
  19062. 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex',
  19063. 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut',
  19064. 'ogonek', 'caron'],
  19065. StandardEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19066. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19067. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  19068. 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
  19069. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  19070. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  19071. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  19072. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  19073. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  19074. 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f',
  19075. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
  19076. 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  19077. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19078. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdown',
  19079. 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  19080. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  19081. 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', 'daggerdbl',
  19082. 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase',
  19083. 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
  19084. 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex',
  19085. 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla',
  19086. '', 'hungarumlaut', 'ogonek', 'caron', 'emdash', '', '', '', '', '', '',
  19087. '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '',
  19088. '', '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae',
  19089. '', '', '', 'dotlessi', '', '', 'lslash', 'oslash', 'oe', 'germandbls'],
  19090. WinAnsiEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19091. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19092. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  19093. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus',
  19094. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  19095. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  19096. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  19097. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  19098. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  19099. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  19100. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  19101. 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  19102. 'bullet', 'Euro', 'bullet', 'quotesinglbase', 'florin', 'quotedblbase',
  19103. 'ellipsis', 'dagger', 'daggerdbl', 'circumflex', 'perthousand', 'Scaron',
  19104. 'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', 'quoteleft',
  19105. 'quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash',
  19106. 'emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', 'oe', 'bullet',
  19107. 'zcaron', 'Ydieresis', 'space', 'exclamdown', 'cent', 'sterling',
  19108. 'currency', 'yen', 'brokenbar', 'section', 'dieresis', 'copyright',
  19109. 'ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', 'registered',
  19110. 'macron', 'degree', 'plusminus', 'twosuperior', 'threesuperior', 'acute',
  19111. 'mu', 'paragraph', 'periodcentered', 'cedilla', 'onesuperior',
  19112. 'ordmasculine', 'guillemotright', 'onequarter', 'onehalf', 'threequarters',
  19113. 'questiondown', 'Agrave', 'Aacute', 'Acircumflex', 'Atilde', 'Adieresis',
  19114. 'Aring', 'AE', 'Ccedilla', 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis',
  19115. 'Igrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve',
  19116. 'Oacute', 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash',
  19117. 'Ugrave', 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn',
  19118. 'germandbls', 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis',
  19119. 'aring', 'ae', 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis',
  19120. 'igrave', 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve',
  19121. 'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash',
  19122. 'ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn',
  19123. 'ydieresis'],
  19124. SymbolSetEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19125. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19126. 'space', 'exclam', 'universal', 'numbersign', 'existential', 'percent',
  19127. 'ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus',
  19128. 'comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
  19129. 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  19130. 'equal', 'greater', 'question', 'congruent', 'Alpha', 'Beta', 'Chi',
  19131. 'Delta', 'Epsilon', 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa',
  19132. 'Lambda', 'Mu', 'Nu', 'Omicron', 'Pi', 'Theta', 'Rho', 'Sigma', 'Tau',
  19133. 'Upsilon', 'sigma1', 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft',
  19134. 'therefore', 'bracketright', 'perpendicular', 'underscore', 'radicalex',
  19135. 'alpha', 'beta', 'chi', 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota',
  19136. 'phi1', 'kappa', 'lambda', 'mu', 'nu', 'omicron', 'pi', 'theta', 'rho',
  19137. 'sigma', 'tau', 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta',
  19138. 'braceleft', 'bar', 'braceright', 'similar', '', '', '', '', '', '', '',
  19139. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19140. '', '', '', '', '', '', '', 'Euro', 'Upsilon1', 'minute', 'lessequal',
  19141. 'fraction', 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade',
  19142. 'arrowboth', 'arrowleft', 'arrowup', 'arrowright', 'arrowdown', 'degree',
  19143. 'plusminus', 'second', 'greaterequal', 'multiply', 'proportional',
  19144. 'partialdiff', 'bullet', 'divide', 'notequal', 'equivalence',
  19145. 'approxequal', 'ellipsis', 'arrowvertex', 'arrowhorizex', 'carriagereturn',
  19146. 'aleph', 'Ifraktur', 'Rfraktur', 'weierstrass', 'circlemultiply',
  19147. 'circleplus', 'emptyset', 'intersection', 'union', 'propersuperset',
  19148. 'reflexsuperset', 'notsubset', 'propersubset', 'reflexsubset', 'element',
  19149. 'notelement', 'angle', 'gradient', 'registerserif', 'copyrightserif',
  19150. 'trademarkserif', 'product', 'radical', 'dotmath', 'logicalnot',
  19151. 'logicaland', 'logicalor', 'arrowdblboth', 'arrowdblleft', 'arrowdblup',
  19152. 'arrowdblright', 'arrowdbldown', 'lozenge', 'angleleft', 'registersans',
  19153. 'copyrightsans', 'trademarksans', 'summation', 'parenlefttp',
  19154. 'parenleftex', 'parenleftbt', 'bracketlefttp', 'bracketleftex',
  19155. 'bracketleftbt', 'bracelefttp', 'braceleftmid', 'braceleftbt', 'braceex',
  19156. '', 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt',
  19157. 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp',
  19158. 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid',
  19159. 'bracerightbt'],
  19160. ZapfDingbatsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19161. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19162. 'space', 'a1', 'a2', 'a202', 'a3', 'a4', 'a5', 'a119', 'a118', 'a117',
  19163. 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a105', 'a17', 'a18', 'a19',
  19164. 'a20', 'a21', 'a22', 'a23', 'a24', 'a25', 'a26', 'a27', 'a28', 'a6', 'a7',
  19165. 'a8', 'a9', 'a10', 'a29', 'a30', 'a31', 'a32', 'a33', 'a34', 'a35', 'a36',
  19166. 'a37', 'a38', 'a39', 'a40', 'a41', 'a42', 'a43', 'a44', 'a45', 'a46',
  19167. 'a47', 'a48', 'a49', 'a50', 'a51', 'a52', 'a53', 'a54', 'a55', 'a56',
  19168. 'a57', 'a58', 'a59', 'a60', 'a61', 'a62', 'a63', 'a64', 'a65', 'a66',
  19169. 'a67', 'a68', 'a69', 'a70', 'a71', 'a72', 'a73', 'a74', 'a203', 'a75',
  19170. 'a204', 'a76', 'a77', 'a78', 'a79', 'a81', 'a82', 'a83', 'a84', 'a97',
  19171. 'a98', 'a99', 'a100', '', 'a89', 'a90', 'a93', 'a94', 'a91', 'a92', 'a205',
  19172. 'a85', 'a206', 'a86', 'a87', 'a88', 'a95', 'a96', '', '', '', '', '', '',
  19173. '', '', '', '', '', '', '', '', '', '', '', '', '', 'a101', 'a102', 'a103',
  19174. 'a104', 'a106', 'a107', 'a108', 'a112', 'a111', 'a110', 'a109', 'a120',
  19175. 'a121', 'a122', 'a123', 'a124', 'a125', 'a126', 'a127', 'a128', 'a129',
  19176. 'a130', 'a131', 'a132', 'a133', 'a134', 'a135', 'a136', 'a137', 'a138',
  19177. 'a139', 'a140', 'a141', 'a142', 'a143', 'a144', 'a145', 'a146', 'a147',
  19178. 'a148', 'a149', 'a150', 'a151', 'a152', 'a153', 'a154', 'a155', 'a156',
  19179. 'a157', 'a158', 'a159', 'a160', 'a161', 'a163', 'a164', 'a196', 'a165',
  19180. 'a192', 'a166', 'a167', 'a168', 'a169', 'a170', 'a171', 'a172', 'a173',
  19181. 'a162', 'a174', 'a175', 'a176', 'a177', 'a178', 'a179', 'a193', 'a180',
  19182. 'a199', 'a181', 'a200', 'a182', '', 'a201', 'a183', 'a184', 'a197', 'a185',
  19183. 'a194', 'a198', 'a186', 'a195', 'a187', 'a188', 'a189', 'a190', 'a191']
  19184. };
  19185. /**
  19186. * Hold a map of decoded fonts and of the standard fourteen Type1
  19187. * fonts and their acronyms.
  19188. */
  19189. var stdFontMap = {
  19190. 'ArialNarrow': 'Helvetica',
  19191. 'ArialNarrow-Bold': 'Helvetica-Bold',
  19192. 'ArialNarrow-BoldItalic': 'Helvetica-BoldOblique',
  19193. 'ArialNarrow-Italic': 'Helvetica-Oblique',
  19194. 'ArialBlack': 'Helvetica',
  19195. 'ArialBlack-Bold': 'Helvetica-Bold',
  19196. 'ArialBlack-BoldItalic': 'Helvetica-BoldOblique',
  19197. 'ArialBlack-Italic': 'Helvetica-Oblique',
  19198. 'Arial': 'Helvetica',
  19199. 'Arial-Bold': 'Helvetica-Bold',
  19200. 'Arial-BoldItalic': 'Helvetica-BoldOblique',
  19201. 'Arial-Italic': 'Helvetica-Oblique',
  19202. 'Arial-BoldItalicMT': 'Helvetica-BoldOblique',
  19203. 'Arial-BoldMT': 'Helvetica-Bold',
  19204. 'Arial-ItalicMT': 'Helvetica-Oblique',
  19205. 'ArialMT': 'Helvetica',
  19206. 'Courier-Bold': 'Courier-Bold',
  19207. 'Courier-BoldItalic': 'Courier-BoldOblique',
  19208. 'Courier-Italic': 'Courier-Oblique',
  19209. 'CourierNew': 'Courier',
  19210. 'CourierNew-Bold': 'Courier-Bold',
  19211. 'CourierNew-BoldItalic': 'Courier-BoldOblique',
  19212. 'CourierNew-Italic': 'Courier-Oblique',
  19213. 'CourierNewPS-BoldItalicMT': 'Courier-BoldOblique',
  19214. 'CourierNewPS-BoldMT': 'Courier-Bold',
  19215. 'CourierNewPS-ItalicMT': 'Courier-Oblique',
  19216. 'CourierNewPSMT': 'Courier',
  19217. 'Helvetica': 'Helvetica',
  19218. 'Helvetica-Bold': 'Helvetica-Bold',
  19219. 'Helvetica-BoldItalic': 'Helvetica-BoldOblique',
  19220. 'Helvetica-BoldOblique': 'Helvetica-BoldOblique',
  19221. 'Helvetica-Italic': 'Helvetica-Oblique',
  19222. 'Helvetica-Oblique':'Helvetica-Oblique',
  19223. 'Symbol-Bold': 'Symbol',
  19224. 'Symbol-BoldItalic': 'Symbol',
  19225. 'Symbol-Italic': 'Symbol',
  19226. 'TimesNewRoman': 'Times-Roman',
  19227. 'TimesNewRoman-Bold': 'Times-Bold',
  19228. 'TimesNewRoman-BoldItalic': 'Times-BoldItalic',
  19229. 'TimesNewRoman-Italic': 'Times-Italic',
  19230. 'TimesNewRomanPS': 'Times-Roman',
  19231. 'TimesNewRomanPS-Bold': 'Times-Bold',
  19232. 'TimesNewRomanPS-BoldItalic': 'Times-BoldItalic',
  19233. 'TimesNewRomanPS-BoldItalicMT': 'Times-BoldItalic',
  19234. 'TimesNewRomanPS-BoldMT': 'Times-Bold',
  19235. 'TimesNewRomanPS-Italic': 'Times-Italic',
  19236. 'TimesNewRomanPS-ItalicMT': 'Times-Italic',
  19237. 'TimesNewRomanPSMT': 'Times-Roman',
  19238. 'TimesNewRomanPSMT-Bold': 'Times-Bold',
  19239. 'TimesNewRomanPSMT-BoldItalic': 'Times-BoldItalic',
  19240. 'TimesNewRomanPSMT-Italic': 'Times-Italic'
  19241. };
  19242. /**
  19243. * Holds the map of the non-standard fonts that might be included as a standard
  19244. * fonts without glyph data.
  19245. */
  19246. var nonStdFontMap = {
  19247. 'CenturyGothic': 'Helvetica',
  19248. 'CenturyGothic-Bold': 'Helvetica-Bold',
  19249. 'CenturyGothic-BoldItalic': 'Helvetica-BoldOblique',
  19250. 'CenturyGothic-Italic': 'Helvetica-Oblique',
  19251. 'ComicSansMS': 'Comic Sans MS',
  19252. 'ComicSansMS-Bold': 'Comic Sans MS-Bold',
  19253. 'ComicSansMS-BoldItalic': 'Comic Sans MS-BoldItalic',
  19254. 'ComicSansMS-Italic': 'Comic Sans MS-Italic',
  19255. 'LucidaConsole': 'Courier',
  19256. 'LucidaConsole-Bold': 'Courier-Bold',
  19257. 'LucidaConsole-BoldItalic': 'Courier-BoldOblique',
  19258. 'LucidaConsole-Italic': 'Courier-Oblique',
  19259. 'MS-Gothic': 'MS Gothic',
  19260. 'MS-Gothic-Bold': 'MS Gothic-Bold',
  19261. 'MS-Gothic-BoldItalic': 'MS Gothic-BoldItalic',
  19262. 'MS-Gothic-Italic': 'MS Gothic-Italic',
  19263. 'MS-Mincho': 'MS Mincho',
  19264. 'MS-Mincho-Bold': 'MS Mincho-Bold',
  19265. 'MS-Mincho-BoldItalic': 'MS Mincho-BoldItalic',
  19266. 'MS-Mincho-Italic': 'MS Mincho-Italic',
  19267. 'MS-PGothic': 'MS PGothic',
  19268. 'MS-PGothic-Bold': 'MS PGothic-Bold',
  19269. 'MS-PGothic-BoldItalic': 'MS PGothic-BoldItalic',
  19270. 'MS-PGothic-Italic': 'MS PGothic-Italic',
  19271. 'MS-PMincho': 'MS PMincho',
  19272. 'MS-PMincho-Bold': 'MS PMincho-Bold',
  19273. 'MS-PMincho-BoldItalic': 'MS PMincho-BoldItalic',
  19274. 'MS-PMincho-Italic': 'MS PMincho-Italic',
  19275. 'Wingdings': 'ZapfDingbats'
  19276. };
  19277. var serifFonts = {
  19278. 'Adobe Jenson': true, 'Adobe Text': true, 'Albertus': true,
  19279. 'Aldus': true, 'Alexandria': true, 'Algerian': true,
  19280. 'American Typewriter': true, 'Antiqua': true, 'Apex': true,
  19281. 'Arno': true, 'Aster': true, 'Aurora': true,
  19282. 'Baskerville': true, 'Bell': true, 'Bembo': true,
  19283. 'Bembo Schoolbook': true, 'Benguiat': true, 'Berkeley Old Style': true,
  19284. 'Bernhard Modern': true, 'Berthold City': true, 'Bodoni': true,
  19285. 'Bauer Bodoni': true, 'Book Antiqua': true, 'Bookman': true,
  19286. 'Bordeaux Roman': true, 'Californian FB': true, 'Calisto': true,
  19287. 'Calvert': true, 'Capitals': true, 'Cambria': true,
  19288. 'Cartier': true, 'Caslon': true, 'Catull': true,
  19289. 'Centaur': true, 'Century Old Style': true, 'Century Schoolbook': true,
  19290. 'Chaparral': true, 'Charis SIL': true, 'Cheltenham': true,
  19291. 'Cholla Slab': true, 'Clarendon': true, 'Clearface': true,
  19292. 'Cochin': true, 'Colonna': true, 'Computer Modern': true,
  19293. 'Concrete Roman': true, 'Constantia': true, 'Cooper Black': true,
  19294. 'Corona': true, 'Ecotype': true, 'Egyptienne': true,
  19295. 'Elephant': true, 'Excelsior': true, 'Fairfield': true,
  19296. 'FF Scala': true, 'Folkard': true, 'Footlight': true,
  19297. 'FreeSerif': true, 'Friz Quadrata': true, 'Garamond': true,
  19298. 'Gentium': true, 'Georgia': true, 'Gloucester': true,
  19299. 'Goudy Old Style': true, 'Goudy Schoolbook': true, 'Goudy Pro Font': true,
  19300. 'Granjon': true, 'Guardian Egyptian': true, 'Heather': true,
  19301. 'Hercules': true, 'High Tower Text': true, 'Hiroshige': true,
  19302. 'Hoefler Text': true, 'Humana Serif': true, 'Imprint': true,
  19303. 'Ionic No. 5': true, 'Janson': true, 'Joanna': true,
  19304. 'Korinna': true, 'Lexicon': true, 'Liberation Serif': true,
  19305. 'Linux Libertine': true, 'Literaturnaya': true, 'Lucida': true,
  19306. 'Lucida Bright': true, 'Melior': true, 'Memphis': true,
  19307. 'Miller': true, 'Minion': true, 'Modern': true,
  19308. 'Mona Lisa': true, 'Mrs Eaves': true, 'MS Serif': true,
  19309. 'Museo Slab': true, 'New York': true, 'Nimbus Roman': true,
  19310. 'NPS Rawlinson Roadway': true, 'Palatino': true, 'Perpetua': true,
  19311. 'Plantin': true, 'Plantin Schoolbook': true, 'Playbill': true,
  19312. 'Poor Richard': true, 'Rawlinson Roadway': true, 'Renault': true,
  19313. 'Requiem': true, 'Rockwell': true, 'Roman': true,
  19314. 'Rotis Serif': true, 'Sabon': true, 'Scala': true,
  19315. 'Seagull': true, 'Sistina': true, 'Souvenir': true,
  19316. 'STIX': true, 'Stone Informal': true, 'Stone Serif': true,
  19317. 'Sylfaen': true, 'Times': true, 'Trajan': true,
  19318. 'Trinité': true, 'Trump Mediaeval': true, 'Utopia': true,
  19319. 'Vale Type': true, 'Bitstream Vera': true, 'Vera Serif': true,
  19320. 'Versailles': true, 'Wanted': true, 'Weiss': true,
  19321. 'Wide Latin': true, 'Windsor': true, 'XITS': true
  19322. };
  19323. var symbolsFonts = {
  19324. 'Dingbats': true, 'Symbol': true, 'ZapfDingbats': true
  19325. };
  19326. // Glyph map for well-known standard fonts. Sometimes Ghostscript uses CID fonts
  19327. // but does not embed the CID to GID mapping. The mapping is incomplete for all
  19328. // glyphs, but common for some set of the standard fonts.
  19329. var GlyphMapForStandardFonts = {
  19330. '2': 10, '3': 32, '4': 33, '5': 34, '6': 35, '7': 36, '8': 37, '9': 38,
  19331. '10': 39, '11': 40, '12': 41, '13': 42, '14': 43, '15': 44, '16': 45,
  19332. '17': 46, '18': 47, '19': 48, '20': 49, '21': 50, '22': 51, '23': 52,
  19333. '24': 53, '25': 54, '26': 55, '27': 56, '28': 57, '29': 58, '30': 894,
  19334. '31': 60, '32': 61, '33': 62, '34': 63, '35': 64, '36': 65, '37': 66,
  19335. '38': 67, '39': 68, '40': 69, '41': 70, '42': 71, '43': 72, '44': 73,
  19336. '45': 74, '46': 75, '47': 76, '48': 77, '49': 78, '50': 79, '51': 80,
  19337. '52': 81, '53': 82, '54': 83, '55': 84, '56': 85, '57': 86, '58': 87,
  19338. '59': 88, '60': 89, '61': 90, '62': 91, '63': 92, '64': 93, '65': 94,
  19339. '66': 95, '67': 96, '68': 97, '69': 98, '70': 99, '71': 100, '72': 101,
  19340. '73': 102, '74': 103, '75': 104, '76': 105, '77': 106, '78': 107, '79': 108,
  19341. '80': 109, '81': 110, '82': 111, '83': 112, '84': 113, '85': 114, '86': 115,
  19342. '87': 116, '88': 117, '89': 118, '90': 119, '91': 120, '92': 121, '93': 122,
  19343. '94': 123, '95': 124, '96': 125, '97': 126, '98': 196, '99': 197, '100': 199,
  19344. '101': 201, '102': 209, '103': 214, '104': 220, '105': 225, '106': 224,
  19345. '107': 226, '108': 228, '109': 227, '110': 229, '111': 231, '112': 233,
  19346. '113': 232, '114': 234, '115': 235, '116': 237, '117': 236, '118': 238,
  19347. '119': 239, '120': 241, '121': 243, '122': 242, '123': 244, '124': 246,
  19348. '125': 245, '126': 250, '127': 249, '128': 251, '129': 252, '130': 8224,
  19349. '131': 176, '132': 162, '133': 163, '134': 167, '135': 8226, '136': 182,
  19350. '137': 223, '138': 174, '139': 169, '140': 8482, '141': 180, '142': 168,
  19351. '143': 8800, '144': 198, '145': 216, '146': 8734, '147': 177, '148': 8804,
  19352. '149': 8805, '150': 165, '151': 181, '152': 8706, '153': 8721, '154': 8719,
  19353. '156': 8747, '157': 170, '158': 186, '159': 8486, '160': 230, '161': 248,
  19354. '162': 191, '163': 161, '164': 172, '165': 8730, '166': 402, '167': 8776,
  19355. '168': 8710, '169': 171, '170': 187, '171': 8230, '210': 218, '223': 711,
  19356. '224': 321, '225': 322, '227': 353, '229': 382, '234': 253, '252': 263,
  19357. '253': 268, '254': 269, '258': 258, '260': 260, '261': 261, '265': 280,
  19358. '266': 281, '268': 283, '269': 313, '275': 323, '276': 324, '278': 328,
  19359. '284': 345, '285': 346, '286': 347, '292': 367, '295': 377, '296': 378,
  19360. '298': 380, '305': 963,
  19361. '306': 964, '307': 966, '308': 8215, '309': 8252, '310': 8319, '311': 8359,
  19362. '312': 8592, '313': 8593, '337': 9552, '493': 1039, '494': 1040, '705': 1524,
  19363. '706': 8362, '710': 64288, '711': 64298, '759': 1617, '761': 1776,
  19364. '763': 1778, '775': 1652, '777': 1764, '778': 1780, '779': 1781, '780': 1782,
  19365. '782': 771, '783': 64726, '786': 8363, '788': 8532, '790': 768, '791': 769,
  19366. '792': 768, '795': 803, '797': 64336, '798': 64337, '799': 64342,
  19367. '800': 64343, '801': 64344, '802': 64345, '803': 64362, '804': 64363,
  19368. '805': 64364, '2424': 7821, '2425': 7822, '2426': 7823, '2427': 7824,
  19369. '2428': 7825, '2429': 7826, '2430': 7827, '2433': 7682, '2678': 8045,
  19370. '2679': 8046, '2830': 1552, '2838': 686, '2840': 751, '2842': 753,
  19371. '2843': 754, '2844': 755, '2846': 757, '2856': 767, '2857': 848, '2858': 849,
  19372. '2862': 853, '2863': 854, '2864': 855, '2865': 861, '2866': 862, '2906': 7460,
  19373. '2908': 7462, '2909': 7463, '2910': 7464, '2912': 7466, '2913': 7467,
  19374. '2914': 7468, '2916': 7470, '2917': 7471, '2918': 7472, '2920': 7474,
  19375. '2921': 7475, '2922': 7476, '2924': 7478, '2925': 7479, '2926': 7480,
  19376. '2928': 7482, '2929': 7483, '2930': 7484, '2932': 7486, '2933': 7487,
  19377. '2934': 7488, '2936': 7490, '2937': 7491, '2938': 7492, '2940': 7494,
  19378. '2941': 7495, '2942': 7496, '2944': 7498, '2946': 7500, '2948': 7502,
  19379. '2950': 7504, '2951': 7505, '2952': 7506, '2954': 7508, '2955': 7509,
  19380. '2956': 7510, '2958': 7512, '2959': 7513, '2960': 7514, '2962': 7516,
  19381. '2963': 7517, '2964': 7518, '2966': 7520, '2967': 7521, '2968': 7522,
  19382. '2970': 7524, '2971': 7525, '2972': 7526, '2974': 7528, '2975': 7529,
  19383. '2976': 7530, '2978': 1537, '2979': 1538, '2980': 1539, '2982': 1549,
  19384. '2983': 1551, '2984': 1552, '2986': 1554, '2987': 1555, '2988': 1556,
  19385. '2990': 1623, '2991': 1624, '2995': 1775, '2999': 1791, '3002': 64290,
  19386. '3003': 64291, '3004': 64292, '3006': 64294, '3007': 64295, '3008': 64296,
  19387. '3011': 1900, '3014': 8223, '3015': 8244, '3017': 7532, '3018': 7533,
  19388. '3019': 7534, '3075': 7590, '3076': 7591, '3079': 7594, '3080': 7595,
  19389. '3083': 7598, '3084': 7599, '3087': 7602, '3088': 7603, '3091': 7606,
  19390. '3092': 7607, '3095': 7610, '3096': 7611, '3099': 7614, '3100': 7615,
  19391. '3103': 7618, '3104': 7619, '3107': 8337, '3108': 8338, '3116': 1884,
  19392. '3119': 1885, '3120': 1885, '3123': 1886, '3124': 1886, '3127': 1887,
  19393. '3128': 1887, '3131': 1888, '3132': 1888, '3135': 1889, '3136': 1889,
  19394. '3139': 1890, '3140': 1890, '3143': 1891, '3144': 1891, '3147': 1892,
  19395. '3148': 1892, '3153': 580, '3154': 581, '3157': 584, '3158': 585, '3161': 588,
  19396. '3162': 589, '3165': 891, '3166': 892, '3169': 1274, '3170': 1275,
  19397. '3173': 1278, '3174': 1279, '3181': 7622, '3182': 7623, '3282': 11799,
  19398. '3316': 578, '3379': 42785, '3393': 1159, '3416': 8377
  19399. };
  19400. // The glyph map for ArialBlack differs slightly from the glyph map used for
  19401. // other well-known standard fonts. Hence we use this (incomplete) CID to GID
  19402. // mapping to adjust the glyph map for non-embedded ArialBlack fonts.
  19403. var SupplementalGlyphMapForArialBlack = {
  19404. '227': 322, '264': 261, '291': 346,
  19405. };
  19406. // Some characters, e.g. copyrightserif, are mapped to the private use area and
  19407. // might not be displayed using standard fonts. Mapping/hacking well-known chars
  19408. // to the similar equivalents in the normal characters range.
  19409. var SpecialPUASymbols = {
  19410. '63721': 0x00A9, // copyrightsans (0xF8E9) => copyright
  19411. '63193': 0x00A9, // copyrightserif (0xF6D9) => copyright
  19412. '63720': 0x00AE, // registersans (0xF8E8) => registered
  19413. '63194': 0x00AE, // registerserif (0xF6DA) => registered
  19414. '63722': 0x2122, // trademarksans (0xF8EA) => trademark
  19415. '63195': 0x2122, // trademarkserif (0xF6DB) => trademark
  19416. '63729': 0x23A7, // bracelefttp (0xF8F1)
  19417. '63730': 0x23A8, // braceleftmid (0xF8F2)
  19418. '63731': 0x23A9, // braceleftbt (0xF8F3)
  19419. '63740': 0x23AB, // bracerighttp (0xF8FC)
  19420. '63741': 0x23AC, // bracerightmid (0xF8FD)
  19421. '63742': 0x23AD, // bracerightbt (0xF8FE)
  19422. '63726': 0x23A1, // bracketlefttp (0xF8EE)
  19423. '63727': 0x23A2, // bracketleftex (0xF8EF)
  19424. '63728': 0x23A3, // bracketleftbt (0xF8F0)
  19425. '63737': 0x23A4, // bracketrighttp (0xF8F9)
  19426. '63738': 0x23A5, // bracketrightex (0xF8FA)
  19427. '63739': 0x23A6, // bracketrightbt (0xF8FB)
  19428. '63723': 0x239B, // parenlefttp (0xF8EB)
  19429. '63724': 0x239C, // parenleftex (0xF8EC)
  19430. '63725': 0x239D, // parenleftbt (0xF8ED)
  19431. '63734': 0x239E, // parenrighttp (0xF8F6)
  19432. '63735': 0x239F, // parenrightex (0xF8F7)
  19433. '63736': 0x23A0, // parenrightbt (0xF8F8)
  19434. };
  19435. function mapSpecialUnicodeValues(code) {
  19436. if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials unicode block.
  19437. return 0;
  19438. } else if (code >= 0xF600 && code <= 0xF8FF) {
  19439. return (SpecialPUASymbols[code] || code);
  19440. }
  19441. return code;
  19442. }
  19443. var UnicodeRanges = [
  19444. { 'begin': 0x0000, 'end': 0x007F }, // Basic Latin
  19445. { 'begin': 0x0080, 'end': 0x00FF }, // Latin-1 Supplement
  19446. { 'begin': 0x0100, 'end': 0x017F }, // Latin Extended-A
  19447. { 'begin': 0x0180, 'end': 0x024F }, // Latin Extended-B
  19448. { 'begin': 0x0250, 'end': 0x02AF }, // IPA Extensions
  19449. { 'begin': 0x02B0, 'end': 0x02FF }, // Spacing Modifier Letters
  19450. { 'begin': 0x0300, 'end': 0x036F }, // Combining Diacritical Marks
  19451. { 'begin': 0x0370, 'end': 0x03FF }, // Greek and Coptic
  19452. { 'begin': 0x2C80, 'end': 0x2CFF }, // Coptic
  19453. { 'begin': 0x0400, 'end': 0x04FF }, // Cyrillic
  19454. { 'begin': 0x0530, 'end': 0x058F }, // Armenian
  19455. { 'begin': 0x0590, 'end': 0x05FF }, // Hebrew
  19456. { 'begin': 0xA500, 'end': 0xA63F }, // Vai
  19457. { 'begin': 0x0600, 'end': 0x06FF }, // Arabic
  19458. { 'begin': 0x07C0, 'end': 0x07FF }, // NKo
  19459. { 'begin': 0x0900, 'end': 0x097F }, // Devanagari
  19460. { 'begin': 0x0980, 'end': 0x09FF }, // Bengali
  19461. { 'begin': 0x0A00, 'end': 0x0A7F }, // Gurmukhi
  19462. { 'begin': 0x0A80, 'end': 0x0AFF }, // Gujarati
  19463. { 'begin': 0x0B00, 'end': 0x0B7F }, // Oriya
  19464. { 'begin': 0x0B80, 'end': 0x0BFF }, // Tamil
  19465. { 'begin': 0x0C00, 'end': 0x0C7F }, // Telugu
  19466. { 'begin': 0x0C80, 'end': 0x0CFF }, // Kannada
  19467. { 'begin': 0x0D00, 'end': 0x0D7F }, // Malayalam
  19468. { 'begin': 0x0E00, 'end': 0x0E7F }, // Thai
  19469. { 'begin': 0x0E80, 'end': 0x0EFF }, // Lao
  19470. { 'begin': 0x10A0, 'end': 0x10FF }, // Georgian
  19471. { 'begin': 0x1B00, 'end': 0x1B7F }, // Balinese
  19472. { 'begin': 0x1100, 'end': 0x11FF }, // Hangul Jamo
  19473. { 'begin': 0x1E00, 'end': 0x1EFF }, // Latin Extended Additional
  19474. { 'begin': 0x1F00, 'end': 0x1FFF }, // Greek Extended
  19475. { 'begin': 0x2000, 'end': 0x206F }, // General Punctuation
  19476. { 'begin': 0x2070, 'end': 0x209F }, // Superscripts And Subscripts
  19477. { 'begin': 0x20A0, 'end': 0x20CF }, // Currency Symbol
  19478. { 'begin': 0x20D0, 'end': 0x20FF }, // Combining Diacritical Marks For Symbols
  19479. { 'begin': 0x2100, 'end': 0x214F }, // Letterlike Symbols
  19480. { 'begin': 0x2150, 'end': 0x218F }, // Number Forms
  19481. { 'begin': 0x2190, 'end': 0x21FF }, // Arrows
  19482. { 'begin': 0x2200, 'end': 0x22FF }, // Mathematical Operators
  19483. { 'begin': 0x2300, 'end': 0x23FF }, // Miscellaneous Technical
  19484. { 'begin': 0x2400, 'end': 0x243F }, // Control Pictures
  19485. { 'begin': 0x2440, 'end': 0x245F }, // Optical Character Recognition
  19486. { 'begin': 0x2460, 'end': 0x24FF }, // Enclosed Alphanumerics
  19487. { 'begin': 0x2500, 'end': 0x257F }, // Box Drawing
  19488. { 'begin': 0x2580, 'end': 0x259F }, // Block Elements
  19489. { 'begin': 0x25A0, 'end': 0x25FF }, // Geometric Shapes
  19490. { 'begin': 0x2600, 'end': 0x26FF }, // Miscellaneous Symbols
  19491. { 'begin': 0x2700, 'end': 0x27BF }, // Dingbats
  19492. { 'begin': 0x3000, 'end': 0x303F }, // CJK Symbols And Punctuation
  19493. { 'begin': 0x3040, 'end': 0x309F }, // Hiragana
  19494. { 'begin': 0x30A0, 'end': 0x30FF }, // Katakana
  19495. { 'begin': 0x3100, 'end': 0x312F }, // Bopomofo
  19496. { 'begin': 0x3130, 'end': 0x318F }, // Hangul Compatibility Jamo
  19497. { 'begin': 0xA840, 'end': 0xA87F }, // Phags-pa
  19498. { 'begin': 0x3200, 'end': 0x32FF }, // Enclosed CJK Letters And Months
  19499. { 'begin': 0x3300, 'end': 0x33FF }, // CJK Compatibility
  19500. { 'begin': 0xAC00, 'end': 0xD7AF }, // Hangul Syllables
  19501. { 'begin': 0xD800, 'end': 0xDFFF }, // Non-Plane 0 *
  19502. { 'begin': 0x10900, 'end': 0x1091F }, // Phoenicia
  19503. { 'begin': 0x4E00, 'end': 0x9FFF }, // CJK Unified Ideographs
  19504. { 'begin': 0xE000, 'end': 0xF8FF }, // Private Use Area (plane 0)
  19505. { 'begin': 0x31C0, 'end': 0x31EF }, // CJK Strokes
  19506. { 'begin': 0xFB00, 'end': 0xFB4F }, // Alphabetic Presentation Forms
  19507. { 'begin': 0xFB50, 'end': 0xFDFF }, // Arabic Presentation Forms-A
  19508. { 'begin': 0xFE20, 'end': 0xFE2F }, // Combining Half Marks
  19509. { 'begin': 0xFE10, 'end': 0xFE1F }, // Vertical Forms
  19510. { 'begin': 0xFE50, 'end': 0xFE6F }, // Small Form Variants
  19511. { 'begin': 0xFE70, 'end': 0xFEFF }, // Arabic Presentation Forms-B
  19512. { 'begin': 0xFF00, 'end': 0xFFEF }, // Halfwidth And Fullwidth Forms
  19513. { 'begin': 0xFFF0, 'end': 0xFFFF }, // Specials
  19514. { 'begin': 0x0F00, 'end': 0x0FFF }, // Tibetan
  19515. { 'begin': 0x0700, 'end': 0x074F }, // Syriac
  19516. { 'begin': 0x0780, 'end': 0x07BF }, // Thaana
  19517. { 'begin': 0x0D80, 'end': 0x0DFF }, // Sinhala
  19518. { 'begin': 0x1000, 'end': 0x109F }, // Myanmar
  19519. { 'begin': 0x1200, 'end': 0x137F }, // Ethiopic
  19520. { 'begin': 0x13A0, 'end': 0x13FF }, // Cherokee
  19521. { 'begin': 0x1400, 'end': 0x167F }, // Unified Canadian Aboriginal Syllabics
  19522. { 'begin': 0x1680, 'end': 0x169F }, // Ogham
  19523. { 'begin': 0x16A0, 'end': 0x16FF }, // Runic
  19524. { 'begin': 0x1780, 'end': 0x17FF }, // Khmer
  19525. { 'begin': 0x1800, 'end': 0x18AF }, // Mongolian
  19526. { 'begin': 0x2800, 'end': 0x28FF }, // Braille Patterns
  19527. { 'begin': 0xA000, 'end': 0xA48F }, // Yi Syllables
  19528. { 'begin': 0x1700, 'end': 0x171F }, // Tagalog
  19529. { 'begin': 0x10300, 'end': 0x1032F }, // Old Italic
  19530. { 'begin': 0x10330, 'end': 0x1034F }, // Gothic
  19531. { 'begin': 0x10400, 'end': 0x1044F }, // Deseret
  19532. { 'begin': 0x1D000, 'end': 0x1D0FF }, // Byzantine Musical Symbols
  19533. { 'begin': 0x1D400, 'end': 0x1D7FF }, // Mathematical Alphanumeric Symbols
  19534. { 'begin': 0xFF000, 'end': 0xFFFFD }, // Private Use (plane 15)
  19535. { 'begin': 0xFE00, 'end': 0xFE0F }, // Variation Selectors
  19536. { 'begin': 0xE0000, 'end': 0xE007F }, // Tags
  19537. { 'begin': 0x1900, 'end': 0x194F }, // Limbu
  19538. { 'begin': 0x1950, 'end': 0x197F }, // Tai Le
  19539. { 'begin': 0x1980, 'end': 0x19DF }, // New Tai Lue
  19540. { 'begin': 0x1A00, 'end': 0x1A1F }, // Buginese
  19541. { 'begin': 0x2C00, 'end': 0x2C5F }, // Glagolitic
  19542. { 'begin': 0x2D30, 'end': 0x2D7F }, // Tifinagh
  19543. { 'begin': 0x4DC0, 'end': 0x4DFF }, // Yijing Hexagram Symbols
  19544. { 'begin': 0xA800, 'end': 0xA82F }, // Syloti Nagri
  19545. { 'begin': 0x10000, 'end': 0x1007F }, // Linear B Syllabary
  19546. { 'begin': 0x10140, 'end': 0x1018F }, // Ancient Greek Numbers
  19547. { 'begin': 0x10380, 'end': 0x1039F }, // Ugaritic
  19548. { 'begin': 0x103A0, 'end': 0x103DF }, // Old Persian
  19549. { 'begin': 0x10450, 'end': 0x1047F }, // Shavian
  19550. { 'begin': 0x10480, 'end': 0x104AF }, // Osmanya
  19551. { 'begin': 0x10800, 'end': 0x1083F }, // Cypriot Syllabary
  19552. { 'begin': 0x10A00, 'end': 0x10A5F }, // Kharoshthi
  19553. { 'begin': 0x1D300, 'end': 0x1D35F }, // Tai Xuan Jing Symbols
  19554. { 'begin': 0x12000, 'end': 0x123FF }, // Cuneiform
  19555. { 'begin': 0x1D360, 'end': 0x1D37F }, // Counting Rod Numerals
  19556. { 'begin': 0x1B80, 'end': 0x1BBF }, // Sundanese
  19557. { 'begin': 0x1C00, 'end': 0x1C4F }, // Lepcha
  19558. { 'begin': 0x1C50, 'end': 0x1C7F }, // Ol Chiki
  19559. { 'begin': 0xA880, 'end': 0xA8DF }, // Saurashtra
  19560. { 'begin': 0xA900, 'end': 0xA92F }, // Kayah Li
  19561. { 'begin': 0xA930, 'end': 0xA95F }, // Rejang
  19562. { 'begin': 0xAA00, 'end': 0xAA5F }, // Cham
  19563. { 'begin': 0x10190, 'end': 0x101CF }, // Ancient Symbols
  19564. { 'begin': 0x101D0, 'end': 0x101FF }, // Phaistos Disc
  19565. { 'begin': 0x102A0, 'end': 0x102DF }, // Carian
  19566. { 'begin': 0x1F030, 'end': 0x1F09F } // Domino Tiles
  19567. ];
  19568. var MacStandardGlyphOrdering = [
  19569. '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl',
  19570. 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft',
  19571. 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash',
  19572. 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
  19573. 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at',
  19574. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  19575. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft',
  19576. 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b',
  19577. 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
  19578. 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright',
  19579. 'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde',
  19580. 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis',
  19581. 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  19582. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve',
  19583. 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex',
  19584. 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet',
  19585. 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute',
  19586. 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal',
  19587. 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi',
  19588. 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash',
  19589. 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin',
  19590. 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis',
  19591. 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash',
  19592. 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright',
  19593. 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency',
  19594. 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered',
  19595. 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex',
  19596. 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex',
  19597. 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute',
  19598. 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron',
  19599. 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron',
  19600. 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar',
  19601. 'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply',
  19602. 'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter',
  19603. 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla',
  19604. 'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
  19605. function getUnicodeRangeFor(value) {
  19606. for (var i = 0, ii = UnicodeRanges.length; i < ii; i++) {
  19607. var range = UnicodeRanges[i];
  19608. if (value >= range.begin && value < range.end) {
  19609. return i;
  19610. }
  19611. }
  19612. return -1;
  19613. }
  19614. function isRTLRangeFor(value) {
  19615. var range = UnicodeRanges[13];
  19616. if (value >= range.begin && value < range.end) {
  19617. return true;
  19618. }
  19619. range = UnicodeRanges[11];
  19620. if (value >= range.begin && value < range.end) {
  19621. return true;
  19622. }
  19623. return false;
  19624. }
  19625. // The normalization table is obtained by filtering the Unicode characters
  19626. // database with <compat> entries.
  19627. var NormalizedUnicodes = {
  19628. '\u00A8': '\u0020\u0308',
  19629. '\u00AF': '\u0020\u0304',
  19630. '\u00B4': '\u0020\u0301',
  19631. '\u00B5': '\u03BC',
  19632. '\u00B8': '\u0020\u0327',
  19633. '\u0132': '\u0049\u004A',
  19634. '\u0133': '\u0069\u006A',
  19635. '\u013F': '\u004C\u00B7',
  19636. '\u0140': '\u006C\u00B7',
  19637. '\u0149': '\u02BC\u006E',
  19638. '\u017F': '\u0073',
  19639. '\u01C4': '\u0044\u017D',
  19640. '\u01C5': '\u0044\u017E',
  19641. '\u01C6': '\u0064\u017E',
  19642. '\u01C7': '\u004C\u004A',
  19643. '\u01C8': '\u004C\u006A',
  19644. '\u01C9': '\u006C\u006A',
  19645. '\u01CA': '\u004E\u004A',
  19646. '\u01CB': '\u004E\u006A',
  19647. '\u01CC': '\u006E\u006A',
  19648. '\u01F1': '\u0044\u005A',
  19649. '\u01F2': '\u0044\u007A',
  19650. '\u01F3': '\u0064\u007A',
  19651. '\u02D8': '\u0020\u0306',
  19652. '\u02D9': '\u0020\u0307',
  19653. '\u02DA': '\u0020\u030A',
  19654. '\u02DB': '\u0020\u0328',
  19655. '\u02DC': '\u0020\u0303',
  19656. '\u02DD': '\u0020\u030B',
  19657. '\u037A': '\u0020\u0345',
  19658. '\u0384': '\u0020\u0301',
  19659. '\u03D0': '\u03B2',
  19660. '\u03D1': '\u03B8',
  19661. '\u03D2': '\u03A5',
  19662. '\u03D5': '\u03C6',
  19663. '\u03D6': '\u03C0',
  19664. '\u03F0': '\u03BA',
  19665. '\u03F1': '\u03C1',
  19666. '\u03F2': '\u03C2',
  19667. '\u03F4': '\u0398',
  19668. '\u03F5': '\u03B5',
  19669. '\u03F9': '\u03A3',
  19670. '\u0587': '\u0565\u0582',
  19671. '\u0675': '\u0627\u0674',
  19672. '\u0676': '\u0648\u0674',
  19673. '\u0677': '\u06C7\u0674',
  19674. '\u0678': '\u064A\u0674',
  19675. '\u0E33': '\u0E4D\u0E32',
  19676. '\u0EB3': '\u0ECD\u0EB2',
  19677. '\u0EDC': '\u0EAB\u0E99',
  19678. '\u0EDD': '\u0EAB\u0EA1',
  19679. '\u0F77': '\u0FB2\u0F81',
  19680. '\u0F79': '\u0FB3\u0F81',
  19681. '\u1E9A': '\u0061\u02BE',
  19682. '\u1FBD': '\u0020\u0313',
  19683. '\u1FBF': '\u0020\u0313',
  19684. '\u1FC0': '\u0020\u0342',
  19685. '\u1FFE': '\u0020\u0314',
  19686. '\u2002': '\u0020',
  19687. '\u2003': '\u0020',
  19688. '\u2004': '\u0020',
  19689. '\u2005': '\u0020',
  19690. '\u2006': '\u0020',
  19691. '\u2008': '\u0020',
  19692. '\u2009': '\u0020',
  19693. '\u200A': '\u0020',
  19694. '\u2017': '\u0020\u0333',
  19695. '\u2024': '\u002E',
  19696. '\u2025': '\u002E\u002E',
  19697. '\u2026': '\u002E\u002E\u002E',
  19698. '\u2033': '\u2032\u2032',
  19699. '\u2034': '\u2032\u2032\u2032',
  19700. '\u2036': '\u2035\u2035',
  19701. '\u2037': '\u2035\u2035\u2035',
  19702. '\u203C': '\u0021\u0021',
  19703. '\u203E': '\u0020\u0305',
  19704. '\u2047': '\u003F\u003F',
  19705. '\u2048': '\u003F\u0021',
  19706. '\u2049': '\u0021\u003F',
  19707. '\u2057': '\u2032\u2032\u2032\u2032',
  19708. '\u205F': '\u0020',
  19709. '\u20A8': '\u0052\u0073',
  19710. '\u2100': '\u0061\u002F\u0063',
  19711. '\u2101': '\u0061\u002F\u0073',
  19712. '\u2103': '\u00B0\u0043',
  19713. '\u2105': '\u0063\u002F\u006F',
  19714. '\u2106': '\u0063\u002F\u0075',
  19715. '\u2107': '\u0190',
  19716. '\u2109': '\u00B0\u0046',
  19717. '\u2116': '\u004E\u006F',
  19718. '\u2121': '\u0054\u0045\u004C',
  19719. '\u2135': '\u05D0',
  19720. '\u2136': '\u05D1',
  19721. '\u2137': '\u05D2',
  19722. '\u2138': '\u05D3',
  19723. '\u213B': '\u0046\u0041\u0058',
  19724. '\u2160': '\u0049',
  19725. '\u2161': '\u0049\u0049',
  19726. '\u2162': '\u0049\u0049\u0049',
  19727. '\u2163': '\u0049\u0056',
  19728. '\u2164': '\u0056',
  19729. '\u2165': '\u0056\u0049',
  19730. '\u2166': '\u0056\u0049\u0049',
  19731. '\u2167': '\u0056\u0049\u0049\u0049',
  19732. '\u2168': '\u0049\u0058',
  19733. '\u2169': '\u0058',
  19734. '\u216A': '\u0058\u0049',
  19735. '\u216B': '\u0058\u0049\u0049',
  19736. '\u216C': '\u004C',
  19737. '\u216D': '\u0043',
  19738. '\u216E': '\u0044',
  19739. '\u216F': '\u004D',
  19740. '\u2170': '\u0069',
  19741. '\u2171': '\u0069\u0069',
  19742. '\u2172': '\u0069\u0069\u0069',
  19743. '\u2173': '\u0069\u0076',
  19744. '\u2174': '\u0076',
  19745. '\u2175': '\u0076\u0069',
  19746. '\u2176': '\u0076\u0069\u0069',
  19747. '\u2177': '\u0076\u0069\u0069\u0069',
  19748. '\u2178': '\u0069\u0078',
  19749. '\u2179': '\u0078',
  19750. '\u217A': '\u0078\u0069',
  19751. '\u217B': '\u0078\u0069\u0069',
  19752. '\u217C': '\u006C',
  19753. '\u217D': '\u0063',
  19754. '\u217E': '\u0064',
  19755. '\u217F': '\u006D',
  19756. '\u222C': '\u222B\u222B',
  19757. '\u222D': '\u222B\u222B\u222B',
  19758. '\u222F': '\u222E\u222E',
  19759. '\u2230': '\u222E\u222E\u222E',
  19760. '\u2474': '\u0028\u0031\u0029',
  19761. '\u2475': '\u0028\u0032\u0029',
  19762. '\u2476': '\u0028\u0033\u0029',
  19763. '\u2477': '\u0028\u0034\u0029',
  19764. '\u2478': '\u0028\u0035\u0029',
  19765. '\u2479': '\u0028\u0036\u0029',
  19766. '\u247A': '\u0028\u0037\u0029',
  19767. '\u247B': '\u0028\u0038\u0029',
  19768. '\u247C': '\u0028\u0039\u0029',
  19769. '\u247D': '\u0028\u0031\u0030\u0029',
  19770. '\u247E': '\u0028\u0031\u0031\u0029',
  19771. '\u247F': '\u0028\u0031\u0032\u0029',
  19772. '\u2480': '\u0028\u0031\u0033\u0029',
  19773. '\u2481': '\u0028\u0031\u0034\u0029',
  19774. '\u2482': '\u0028\u0031\u0035\u0029',
  19775. '\u2483': '\u0028\u0031\u0036\u0029',
  19776. '\u2484': '\u0028\u0031\u0037\u0029',
  19777. '\u2485': '\u0028\u0031\u0038\u0029',
  19778. '\u2486': '\u0028\u0031\u0039\u0029',
  19779. '\u2487': '\u0028\u0032\u0030\u0029',
  19780. '\u2488': '\u0031\u002E',
  19781. '\u2489': '\u0032\u002E',
  19782. '\u248A': '\u0033\u002E',
  19783. '\u248B': '\u0034\u002E',
  19784. '\u248C': '\u0035\u002E',
  19785. '\u248D': '\u0036\u002E',
  19786. '\u248E': '\u0037\u002E',
  19787. '\u248F': '\u0038\u002E',
  19788. '\u2490': '\u0039\u002E',
  19789. '\u2491': '\u0031\u0030\u002E',
  19790. '\u2492': '\u0031\u0031\u002E',
  19791. '\u2493': '\u0031\u0032\u002E',
  19792. '\u2494': '\u0031\u0033\u002E',
  19793. '\u2495': '\u0031\u0034\u002E',
  19794. '\u2496': '\u0031\u0035\u002E',
  19795. '\u2497': '\u0031\u0036\u002E',
  19796. '\u2498': '\u0031\u0037\u002E',
  19797. '\u2499': '\u0031\u0038\u002E',
  19798. '\u249A': '\u0031\u0039\u002E',
  19799. '\u249B': '\u0032\u0030\u002E',
  19800. '\u249C': '\u0028\u0061\u0029',
  19801. '\u249D': '\u0028\u0062\u0029',
  19802. '\u249E': '\u0028\u0063\u0029',
  19803. '\u249F': '\u0028\u0064\u0029',
  19804. '\u24A0': '\u0028\u0065\u0029',
  19805. '\u24A1': '\u0028\u0066\u0029',
  19806. '\u24A2': '\u0028\u0067\u0029',
  19807. '\u24A3': '\u0028\u0068\u0029',
  19808. '\u24A4': '\u0028\u0069\u0029',
  19809. '\u24A5': '\u0028\u006A\u0029',
  19810. '\u24A6': '\u0028\u006B\u0029',
  19811. '\u24A7': '\u0028\u006C\u0029',
  19812. '\u24A8': '\u0028\u006D\u0029',
  19813. '\u24A9': '\u0028\u006E\u0029',
  19814. '\u24AA': '\u0028\u006F\u0029',
  19815. '\u24AB': '\u0028\u0070\u0029',
  19816. '\u24AC': '\u0028\u0071\u0029',
  19817. '\u24AD': '\u0028\u0072\u0029',
  19818. '\u24AE': '\u0028\u0073\u0029',
  19819. '\u24AF': '\u0028\u0074\u0029',
  19820. '\u24B0': '\u0028\u0075\u0029',
  19821. '\u24B1': '\u0028\u0076\u0029',
  19822. '\u24B2': '\u0028\u0077\u0029',
  19823. '\u24B3': '\u0028\u0078\u0029',
  19824. '\u24B4': '\u0028\u0079\u0029',
  19825. '\u24B5': '\u0028\u007A\u0029',
  19826. '\u2A0C': '\u222B\u222B\u222B\u222B',
  19827. '\u2A74': '\u003A\u003A\u003D',
  19828. '\u2A75': '\u003D\u003D',
  19829. '\u2A76': '\u003D\u003D\u003D',
  19830. '\u2E9F': '\u6BCD',
  19831. '\u2EF3': '\u9F9F',
  19832. '\u2F00': '\u4E00',
  19833. '\u2F01': '\u4E28',
  19834. '\u2F02': '\u4E36',
  19835. '\u2F03': '\u4E3F',
  19836. '\u2F04': '\u4E59',
  19837. '\u2F05': '\u4E85',
  19838. '\u2F06': '\u4E8C',
  19839. '\u2F07': '\u4EA0',
  19840. '\u2F08': '\u4EBA',
  19841. '\u2F09': '\u513F',
  19842. '\u2F0A': '\u5165',
  19843. '\u2F0B': '\u516B',
  19844. '\u2F0C': '\u5182',
  19845. '\u2F0D': '\u5196',
  19846. '\u2F0E': '\u51AB',
  19847. '\u2F0F': '\u51E0',
  19848. '\u2F10': '\u51F5',
  19849. '\u2F11': '\u5200',
  19850. '\u2F12': '\u529B',
  19851. '\u2F13': '\u52F9',
  19852. '\u2F14': '\u5315',
  19853. '\u2F15': '\u531A',
  19854. '\u2F16': '\u5338',
  19855. '\u2F17': '\u5341',
  19856. '\u2F18': '\u535C',
  19857. '\u2F19': '\u5369',
  19858. '\u2F1A': '\u5382',
  19859. '\u2F1B': '\u53B6',
  19860. '\u2F1C': '\u53C8',
  19861. '\u2F1D': '\u53E3',
  19862. '\u2F1E': '\u56D7',
  19863. '\u2F1F': '\u571F',
  19864. '\u2F20': '\u58EB',
  19865. '\u2F21': '\u5902',
  19866. '\u2F22': '\u590A',
  19867. '\u2F23': '\u5915',
  19868. '\u2F24': '\u5927',
  19869. '\u2F25': '\u5973',
  19870. '\u2F26': '\u5B50',
  19871. '\u2F27': '\u5B80',
  19872. '\u2F28': '\u5BF8',
  19873. '\u2F29': '\u5C0F',
  19874. '\u2F2A': '\u5C22',
  19875. '\u2F2B': '\u5C38',
  19876. '\u2F2C': '\u5C6E',
  19877. '\u2F2D': '\u5C71',
  19878. '\u2F2E': '\u5DDB',
  19879. '\u2F2F': '\u5DE5',
  19880. '\u2F30': '\u5DF1',
  19881. '\u2F31': '\u5DFE',
  19882. '\u2F32': '\u5E72',
  19883. '\u2F33': '\u5E7A',
  19884. '\u2F34': '\u5E7F',
  19885. '\u2F35': '\u5EF4',
  19886. '\u2F36': '\u5EFE',
  19887. '\u2F37': '\u5F0B',
  19888. '\u2F38': '\u5F13',
  19889. '\u2F39': '\u5F50',
  19890. '\u2F3A': '\u5F61',
  19891. '\u2F3B': '\u5F73',
  19892. '\u2F3C': '\u5FC3',
  19893. '\u2F3D': '\u6208',
  19894. '\u2F3E': '\u6236',
  19895. '\u2F3F': '\u624B',
  19896. '\u2F40': '\u652F',
  19897. '\u2F41': '\u6534',
  19898. '\u2F42': '\u6587',
  19899. '\u2F43': '\u6597',
  19900. '\u2F44': '\u65A4',
  19901. '\u2F45': '\u65B9',
  19902. '\u2F46': '\u65E0',
  19903. '\u2F47': '\u65E5',
  19904. '\u2F48': '\u66F0',
  19905. '\u2F49': '\u6708',
  19906. '\u2F4A': '\u6728',
  19907. '\u2F4B': '\u6B20',
  19908. '\u2F4C': '\u6B62',
  19909. '\u2F4D': '\u6B79',
  19910. '\u2F4E': '\u6BB3',
  19911. '\u2F4F': '\u6BCB',
  19912. '\u2F50': '\u6BD4',
  19913. '\u2F51': '\u6BDB',
  19914. '\u2F52': '\u6C0F',
  19915. '\u2F53': '\u6C14',
  19916. '\u2F54': '\u6C34',
  19917. '\u2F55': '\u706B',
  19918. '\u2F56': '\u722A',
  19919. '\u2F57': '\u7236',
  19920. '\u2F58': '\u723B',
  19921. '\u2F59': '\u723F',
  19922. '\u2F5A': '\u7247',
  19923. '\u2F5B': '\u7259',
  19924. '\u2F5C': '\u725B',
  19925. '\u2F5D': '\u72AC',
  19926. '\u2F5E': '\u7384',
  19927. '\u2F5F': '\u7389',
  19928. '\u2F60': '\u74DC',
  19929. '\u2F61': '\u74E6',
  19930. '\u2F62': '\u7518',
  19931. '\u2F63': '\u751F',
  19932. '\u2F64': '\u7528',
  19933. '\u2F65': '\u7530',
  19934. '\u2F66': '\u758B',
  19935. '\u2F67': '\u7592',
  19936. '\u2F68': '\u7676',
  19937. '\u2F69': '\u767D',
  19938. '\u2F6A': '\u76AE',
  19939. '\u2F6B': '\u76BF',
  19940. '\u2F6C': '\u76EE',
  19941. '\u2F6D': '\u77DB',
  19942. '\u2F6E': '\u77E2',
  19943. '\u2F6F': '\u77F3',
  19944. '\u2F70': '\u793A',
  19945. '\u2F71': '\u79B8',
  19946. '\u2F72': '\u79BE',
  19947. '\u2F73': '\u7A74',
  19948. '\u2F74': '\u7ACB',
  19949. '\u2F75': '\u7AF9',
  19950. '\u2F76': '\u7C73',
  19951. '\u2F77': '\u7CF8',
  19952. '\u2F78': '\u7F36',
  19953. '\u2F79': '\u7F51',
  19954. '\u2F7A': '\u7F8A',
  19955. '\u2F7B': '\u7FBD',
  19956. '\u2F7C': '\u8001',
  19957. '\u2F7D': '\u800C',
  19958. '\u2F7E': '\u8012',
  19959. '\u2F7F': '\u8033',
  19960. '\u2F80': '\u807F',
  19961. '\u2F81': '\u8089',
  19962. '\u2F82': '\u81E3',
  19963. '\u2F83': '\u81EA',
  19964. '\u2F84': '\u81F3',
  19965. '\u2F85': '\u81FC',
  19966. '\u2F86': '\u820C',
  19967. '\u2F87': '\u821B',
  19968. '\u2F88': '\u821F',
  19969. '\u2F89': '\u826E',
  19970. '\u2F8A': '\u8272',
  19971. '\u2F8B': '\u8278',
  19972. '\u2F8C': '\u864D',
  19973. '\u2F8D': '\u866B',
  19974. '\u2F8E': '\u8840',
  19975. '\u2F8F': '\u884C',
  19976. '\u2F90': '\u8863',
  19977. '\u2F91': '\u897E',
  19978. '\u2F92': '\u898B',
  19979. '\u2F93': '\u89D2',
  19980. '\u2F94': '\u8A00',
  19981. '\u2F95': '\u8C37',
  19982. '\u2F96': '\u8C46',
  19983. '\u2F97': '\u8C55',
  19984. '\u2F98': '\u8C78',
  19985. '\u2F99': '\u8C9D',
  19986. '\u2F9A': '\u8D64',
  19987. '\u2F9B': '\u8D70',
  19988. '\u2F9C': '\u8DB3',
  19989. '\u2F9D': '\u8EAB',
  19990. '\u2F9E': '\u8ECA',
  19991. '\u2F9F': '\u8F9B',
  19992. '\u2FA0': '\u8FB0',
  19993. '\u2FA1': '\u8FB5',
  19994. '\u2FA2': '\u9091',
  19995. '\u2FA3': '\u9149',
  19996. '\u2FA4': '\u91C6',
  19997. '\u2FA5': '\u91CC',
  19998. '\u2FA6': '\u91D1',
  19999. '\u2FA7': '\u9577',
  20000. '\u2FA8': '\u9580',
  20001. '\u2FA9': '\u961C',
  20002. '\u2FAA': '\u96B6',
  20003. '\u2FAB': '\u96B9',
  20004. '\u2FAC': '\u96E8',
  20005. '\u2FAD': '\u9751',
  20006. '\u2FAE': '\u975E',
  20007. '\u2FAF': '\u9762',
  20008. '\u2FB0': '\u9769',
  20009. '\u2FB1': '\u97CB',
  20010. '\u2FB2': '\u97ED',
  20011. '\u2FB3': '\u97F3',
  20012. '\u2FB4': '\u9801',
  20013. '\u2FB5': '\u98A8',
  20014. '\u2FB6': '\u98DB',
  20015. '\u2FB7': '\u98DF',
  20016. '\u2FB8': '\u9996',
  20017. '\u2FB9': '\u9999',
  20018. '\u2FBA': '\u99AC',
  20019. '\u2FBB': '\u9AA8',
  20020. '\u2FBC': '\u9AD8',
  20021. '\u2FBD': '\u9ADF',
  20022. '\u2FBE': '\u9B25',
  20023. '\u2FBF': '\u9B2F',
  20024. '\u2FC0': '\u9B32',
  20025. '\u2FC1': '\u9B3C',
  20026. '\u2FC2': '\u9B5A',
  20027. '\u2FC3': '\u9CE5',
  20028. '\u2FC4': '\u9E75',
  20029. '\u2FC5': '\u9E7F',
  20030. '\u2FC6': '\u9EA5',
  20031. '\u2FC7': '\u9EBB',
  20032. '\u2FC8': '\u9EC3',
  20033. '\u2FC9': '\u9ECD',
  20034. '\u2FCA': '\u9ED1',
  20035. '\u2FCB': '\u9EF9',
  20036. '\u2FCC': '\u9EFD',
  20037. '\u2FCD': '\u9F0E',
  20038. '\u2FCE': '\u9F13',
  20039. '\u2FCF': '\u9F20',
  20040. '\u2FD0': '\u9F3B',
  20041. '\u2FD1': '\u9F4A',
  20042. '\u2FD2': '\u9F52',
  20043. '\u2FD3': '\u9F8D',
  20044. '\u2FD4': '\u9F9C',
  20045. '\u2FD5': '\u9FA0',
  20046. '\u3036': '\u3012',
  20047. '\u3038': '\u5341',
  20048. '\u3039': '\u5344',
  20049. '\u303A': '\u5345',
  20050. '\u309B': '\u0020\u3099',
  20051. '\u309C': '\u0020\u309A',
  20052. '\u3131': '\u1100',
  20053. '\u3132': '\u1101',
  20054. '\u3133': '\u11AA',
  20055. '\u3134': '\u1102',
  20056. '\u3135': '\u11AC',
  20057. '\u3136': '\u11AD',
  20058. '\u3137': '\u1103',
  20059. '\u3138': '\u1104',
  20060. '\u3139': '\u1105',
  20061. '\u313A': '\u11B0',
  20062. '\u313B': '\u11B1',
  20063. '\u313C': '\u11B2',
  20064. '\u313D': '\u11B3',
  20065. '\u313E': '\u11B4',
  20066. '\u313F': '\u11B5',
  20067. '\u3140': '\u111A',
  20068. '\u3141': '\u1106',
  20069. '\u3142': '\u1107',
  20070. '\u3143': '\u1108',
  20071. '\u3144': '\u1121',
  20072. '\u3145': '\u1109',
  20073. '\u3146': '\u110A',
  20074. '\u3147': '\u110B',
  20075. '\u3148': '\u110C',
  20076. '\u3149': '\u110D',
  20077. '\u314A': '\u110E',
  20078. '\u314B': '\u110F',
  20079. '\u314C': '\u1110',
  20080. '\u314D': '\u1111',
  20081. '\u314E': '\u1112',
  20082. '\u314F': '\u1161',
  20083. '\u3150': '\u1162',
  20084. '\u3151': '\u1163',
  20085. '\u3152': '\u1164',
  20086. '\u3153': '\u1165',
  20087. '\u3154': '\u1166',
  20088. '\u3155': '\u1167',
  20089. '\u3156': '\u1168',
  20090. '\u3157': '\u1169',
  20091. '\u3158': '\u116A',
  20092. '\u3159': '\u116B',
  20093. '\u315A': '\u116C',
  20094. '\u315B': '\u116D',
  20095. '\u315C': '\u116E',
  20096. '\u315D': '\u116F',
  20097. '\u315E': '\u1170',
  20098. '\u315F': '\u1171',
  20099. '\u3160': '\u1172',
  20100. '\u3161': '\u1173',
  20101. '\u3162': '\u1174',
  20102. '\u3163': '\u1175',
  20103. '\u3164': '\u1160',
  20104. '\u3165': '\u1114',
  20105. '\u3166': '\u1115',
  20106. '\u3167': '\u11C7',
  20107. '\u3168': '\u11C8',
  20108. '\u3169': '\u11CC',
  20109. '\u316A': '\u11CE',
  20110. '\u316B': '\u11D3',
  20111. '\u316C': '\u11D7',
  20112. '\u316D': '\u11D9',
  20113. '\u316E': '\u111C',
  20114. '\u316F': '\u11DD',
  20115. '\u3170': '\u11DF',
  20116. '\u3171': '\u111D',
  20117. '\u3172': '\u111E',
  20118. '\u3173': '\u1120',
  20119. '\u3174': '\u1122',
  20120. '\u3175': '\u1123',
  20121. '\u3176': '\u1127',
  20122. '\u3177': '\u1129',
  20123. '\u3178': '\u112B',
  20124. '\u3179': '\u112C',
  20125. '\u317A': '\u112D',
  20126. '\u317B': '\u112E',
  20127. '\u317C': '\u112F',
  20128. '\u317D': '\u1132',
  20129. '\u317E': '\u1136',
  20130. '\u317F': '\u1140',
  20131. '\u3180': '\u1147',
  20132. '\u3181': '\u114C',
  20133. '\u3182': '\u11F1',
  20134. '\u3183': '\u11F2',
  20135. '\u3184': '\u1157',
  20136. '\u3185': '\u1158',
  20137. '\u3186': '\u1159',
  20138. '\u3187': '\u1184',
  20139. '\u3188': '\u1185',
  20140. '\u3189': '\u1188',
  20141. '\u318A': '\u1191',
  20142. '\u318B': '\u1192',
  20143. '\u318C': '\u1194',
  20144. '\u318D': '\u119E',
  20145. '\u318E': '\u11A1',
  20146. '\u3200': '\u0028\u1100\u0029',
  20147. '\u3201': '\u0028\u1102\u0029',
  20148. '\u3202': '\u0028\u1103\u0029',
  20149. '\u3203': '\u0028\u1105\u0029',
  20150. '\u3204': '\u0028\u1106\u0029',
  20151. '\u3205': '\u0028\u1107\u0029',
  20152. '\u3206': '\u0028\u1109\u0029',
  20153. '\u3207': '\u0028\u110B\u0029',
  20154. '\u3208': '\u0028\u110C\u0029',
  20155. '\u3209': '\u0028\u110E\u0029',
  20156. '\u320A': '\u0028\u110F\u0029',
  20157. '\u320B': '\u0028\u1110\u0029',
  20158. '\u320C': '\u0028\u1111\u0029',
  20159. '\u320D': '\u0028\u1112\u0029',
  20160. '\u320E': '\u0028\u1100\u1161\u0029',
  20161. '\u320F': '\u0028\u1102\u1161\u0029',
  20162. '\u3210': '\u0028\u1103\u1161\u0029',
  20163. '\u3211': '\u0028\u1105\u1161\u0029',
  20164. '\u3212': '\u0028\u1106\u1161\u0029',
  20165. '\u3213': '\u0028\u1107\u1161\u0029',
  20166. '\u3214': '\u0028\u1109\u1161\u0029',
  20167. '\u3215': '\u0028\u110B\u1161\u0029',
  20168. '\u3216': '\u0028\u110C\u1161\u0029',
  20169. '\u3217': '\u0028\u110E\u1161\u0029',
  20170. '\u3218': '\u0028\u110F\u1161\u0029',
  20171. '\u3219': '\u0028\u1110\u1161\u0029',
  20172. '\u321A': '\u0028\u1111\u1161\u0029',
  20173. '\u321B': '\u0028\u1112\u1161\u0029',
  20174. '\u321C': '\u0028\u110C\u116E\u0029',
  20175. '\u321D': '\u0028\u110B\u1169\u110C\u1165\u11AB\u0029',
  20176. '\u321E': '\u0028\u110B\u1169\u1112\u116E\u0029',
  20177. '\u3220': '\u0028\u4E00\u0029',
  20178. '\u3221': '\u0028\u4E8C\u0029',
  20179. '\u3222': '\u0028\u4E09\u0029',
  20180. '\u3223': '\u0028\u56DB\u0029',
  20181. '\u3224': '\u0028\u4E94\u0029',
  20182. '\u3225': '\u0028\u516D\u0029',
  20183. '\u3226': '\u0028\u4E03\u0029',
  20184. '\u3227': '\u0028\u516B\u0029',
  20185. '\u3228': '\u0028\u4E5D\u0029',
  20186. '\u3229': '\u0028\u5341\u0029',
  20187. '\u322A': '\u0028\u6708\u0029',
  20188. '\u322B': '\u0028\u706B\u0029',
  20189. '\u322C': '\u0028\u6C34\u0029',
  20190. '\u322D': '\u0028\u6728\u0029',
  20191. '\u322E': '\u0028\u91D1\u0029',
  20192. '\u322F': '\u0028\u571F\u0029',
  20193. '\u3230': '\u0028\u65E5\u0029',
  20194. '\u3231': '\u0028\u682A\u0029',
  20195. '\u3232': '\u0028\u6709\u0029',
  20196. '\u3233': '\u0028\u793E\u0029',
  20197. '\u3234': '\u0028\u540D\u0029',
  20198. '\u3235': '\u0028\u7279\u0029',
  20199. '\u3236': '\u0028\u8CA1\u0029',
  20200. '\u3237': '\u0028\u795D\u0029',
  20201. '\u3238': '\u0028\u52B4\u0029',
  20202. '\u3239': '\u0028\u4EE3\u0029',
  20203. '\u323A': '\u0028\u547C\u0029',
  20204. '\u323B': '\u0028\u5B66\u0029',
  20205. '\u323C': '\u0028\u76E3\u0029',
  20206. '\u323D': '\u0028\u4F01\u0029',
  20207. '\u323E': '\u0028\u8CC7\u0029',
  20208. '\u323F': '\u0028\u5354\u0029',
  20209. '\u3240': '\u0028\u796D\u0029',
  20210. '\u3241': '\u0028\u4F11\u0029',
  20211. '\u3242': '\u0028\u81EA\u0029',
  20212. '\u3243': '\u0028\u81F3\u0029',
  20213. '\u32C0': '\u0031\u6708',
  20214. '\u32C1': '\u0032\u6708',
  20215. '\u32C2': '\u0033\u6708',
  20216. '\u32C3': '\u0034\u6708',
  20217. '\u32C4': '\u0035\u6708',
  20218. '\u32C5': '\u0036\u6708',
  20219. '\u32C6': '\u0037\u6708',
  20220. '\u32C7': '\u0038\u6708',
  20221. '\u32C8': '\u0039\u6708',
  20222. '\u32C9': '\u0031\u0030\u6708',
  20223. '\u32CA': '\u0031\u0031\u6708',
  20224. '\u32CB': '\u0031\u0032\u6708',
  20225. '\u3358': '\u0030\u70B9',
  20226. '\u3359': '\u0031\u70B9',
  20227. '\u335A': '\u0032\u70B9',
  20228. '\u335B': '\u0033\u70B9',
  20229. '\u335C': '\u0034\u70B9',
  20230. '\u335D': '\u0035\u70B9',
  20231. '\u335E': '\u0036\u70B9',
  20232. '\u335F': '\u0037\u70B9',
  20233. '\u3360': '\u0038\u70B9',
  20234. '\u3361': '\u0039\u70B9',
  20235. '\u3362': '\u0031\u0030\u70B9',
  20236. '\u3363': '\u0031\u0031\u70B9',
  20237. '\u3364': '\u0031\u0032\u70B9',
  20238. '\u3365': '\u0031\u0033\u70B9',
  20239. '\u3366': '\u0031\u0034\u70B9',
  20240. '\u3367': '\u0031\u0035\u70B9',
  20241. '\u3368': '\u0031\u0036\u70B9',
  20242. '\u3369': '\u0031\u0037\u70B9',
  20243. '\u336A': '\u0031\u0038\u70B9',
  20244. '\u336B': '\u0031\u0039\u70B9',
  20245. '\u336C': '\u0032\u0030\u70B9',
  20246. '\u336D': '\u0032\u0031\u70B9',
  20247. '\u336E': '\u0032\u0032\u70B9',
  20248. '\u336F': '\u0032\u0033\u70B9',
  20249. '\u3370': '\u0032\u0034\u70B9',
  20250. '\u33E0': '\u0031\u65E5',
  20251. '\u33E1': '\u0032\u65E5',
  20252. '\u33E2': '\u0033\u65E5',
  20253. '\u33E3': '\u0034\u65E5',
  20254. '\u33E4': '\u0035\u65E5',
  20255. '\u33E5': '\u0036\u65E5',
  20256. '\u33E6': '\u0037\u65E5',
  20257. '\u33E7': '\u0038\u65E5',
  20258. '\u33E8': '\u0039\u65E5',
  20259. '\u33E9': '\u0031\u0030\u65E5',
  20260. '\u33EA': '\u0031\u0031\u65E5',
  20261. '\u33EB': '\u0031\u0032\u65E5',
  20262. '\u33EC': '\u0031\u0033\u65E5',
  20263. '\u33ED': '\u0031\u0034\u65E5',
  20264. '\u33EE': '\u0031\u0035\u65E5',
  20265. '\u33EF': '\u0031\u0036\u65E5',
  20266. '\u33F0': '\u0031\u0037\u65E5',
  20267. '\u33F1': '\u0031\u0038\u65E5',
  20268. '\u33F2': '\u0031\u0039\u65E5',
  20269. '\u33F3': '\u0032\u0030\u65E5',
  20270. '\u33F4': '\u0032\u0031\u65E5',
  20271. '\u33F5': '\u0032\u0032\u65E5',
  20272. '\u33F6': '\u0032\u0033\u65E5',
  20273. '\u33F7': '\u0032\u0034\u65E5',
  20274. '\u33F8': '\u0032\u0035\u65E5',
  20275. '\u33F9': '\u0032\u0036\u65E5',
  20276. '\u33FA': '\u0032\u0037\u65E5',
  20277. '\u33FB': '\u0032\u0038\u65E5',
  20278. '\u33FC': '\u0032\u0039\u65E5',
  20279. '\u33FD': '\u0033\u0030\u65E5',
  20280. '\u33FE': '\u0033\u0031\u65E5',
  20281. '\uFB00': '\u0066\u0066',
  20282. '\uFB01': '\u0066\u0069',
  20283. '\uFB02': '\u0066\u006C',
  20284. '\uFB03': '\u0066\u0066\u0069',
  20285. '\uFB04': '\u0066\u0066\u006C',
  20286. '\uFB05': '\u017F\u0074',
  20287. '\uFB06': '\u0073\u0074',
  20288. '\uFB13': '\u0574\u0576',
  20289. '\uFB14': '\u0574\u0565',
  20290. '\uFB15': '\u0574\u056B',
  20291. '\uFB16': '\u057E\u0576',
  20292. '\uFB17': '\u0574\u056D',
  20293. '\uFB4F': '\u05D0\u05DC',
  20294. '\uFB50': '\u0671',
  20295. '\uFB51': '\u0671',
  20296. '\uFB52': '\u067B',
  20297. '\uFB53': '\u067B',
  20298. '\uFB54': '\u067B',
  20299. '\uFB55': '\u067B',
  20300. '\uFB56': '\u067E',
  20301. '\uFB57': '\u067E',
  20302. '\uFB58': '\u067E',
  20303. '\uFB59': '\u067E',
  20304. '\uFB5A': '\u0680',
  20305. '\uFB5B': '\u0680',
  20306. '\uFB5C': '\u0680',
  20307. '\uFB5D': '\u0680',
  20308. '\uFB5E': '\u067A',
  20309. '\uFB5F': '\u067A',
  20310. '\uFB60': '\u067A',
  20311. '\uFB61': '\u067A',
  20312. '\uFB62': '\u067F',
  20313. '\uFB63': '\u067F',
  20314. '\uFB64': '\u067F',
  20315. '\uFB65': '\u067F',
  20316. '\uFB66': '\u0679',
  20317. '\uFB67': '\u0679',
  20318. '\uFB68': '\u0679',
  20319. '\uFB69': '\u0679',
  20320. '\uFB6A': '\u06A4',
  20321. '\uFB6B': '\u06A4',
  20322. '\uFB6C': '\u06A4',
  20323. '\uFB6D': '\u06A4',
  20324. '\uFB6E': '\u06A6',
  20325. '\uFB6F': '\u06A6',
  20326. '\uFB70': '\u06A6',
  20327. '\uFB71': '\u06A6',
  20328. '\uFB72': '\u0684',
  20329. '\uFB73': '\u0684',
  20330. '\uFB74': '\u0684',
  20331. '\uFB75': '\u0684',
  20332. '\uFB76': '\u0683',
  20333. '\uFB77': '\u0683',
  20334. '\uFB78': '\u0683',
  20335. '\uFB79': '\u0683',
  20336. '\uFB7A': '\u0686',
  20337. '\uFB7B': '\u0686',
  20338. '\uFB7C': '\u0686',
  20339. '\uFB7D': '\u0686',
  20340. '\uFB7E': '\u0687',
  20341. '\uFB7F': '\u0687',
  20342. '\uFB80': '\u0687',
  20343. '\uFB81': '\u0687',
  20344. '\uFB82': '\u068D',
  20345. '\uFB83': '\u068D',
  20346. '\uFB84': '\u068C',
  20347. '\uFB85': '\u068C',
  20348. '\uFB86': '\u068E',
  20349. '\uFB87': '\u068E',
  20350. '\uFB88': '\u0688',
  20351. '\uFB89': '\u0688',
  20352. '\uFB8A': '\u0698',
  20353. '\uFB8B': '\u0698',
  20354. '\uFB8C': '\u0691',
  20355. '\uFB8D': '\u0691',
  20356. '\uFB8E': '\u06A9',
  20357. '\uFB8F': '\u06A9',
  20358. '\uFB90': '\u06A9',
  20359. '\uFB91': '\u06A9',
  20360. '\uFB92': '\u06AF',
  20361. '\uFB93': '\u06AF',
  20362. '\uFB94': '\u06AF',
  20363. '\uFB95': '\u06AF',
  20364. '\uFB96': '\u06B3',
  20365. '\uFB97': '\u06B3',
  20366. '\uFB98': '\u06B3',
  20367. '\uFB99': '\u06B3',
  20368. '\uFB9A': '\u06B1',
  20369. '\uFB9B': '\u06B1',
  20370. '\uFB9C': '\u06B1',
  20371. '\uFB9D': '\u06B1',
  20372. '\uFB9E': '\u06BA',
  20373. '\uFB9F': '\u06BA',
  20374. '\uFBA0': '\u06BB',
  20375. '\uFBA1': '\u06BB',
  20376. '\uFBA2': '\u06BB',
  20377. '\uFBA3': '\u06BB',
  20378. '\uFBA4': '\u06C0',
  20379. '\uFBA5': '\u06C0',
  20380. '\uFBA6': '\u06C1',
  20381. '\uFBA7': '\u06C1',
  20382. '\uFBA8': '\u06C1',
  20383. '\uFBA9': '\u06C1',
  20384. '\uFBAA': '\u06BE',
  20385. '\uFBAB': '\u06BE',
  20386. '\uFBAC': '\u06BE',
  20387. '\uFBAD': '\u06BE',
  20388. '\uFBAE': '\u06D2',
  20389. '\uFBAF': '\u06D2',
  20390. '\uFBB0': '\u06D3',
  20391. '\uFBB1': '\u06D3',
  20392. '\uFBD3': '\u06AD',
  20393. '\uFBD4': '\u06AD',
  20394. '\uFBD5': '\u06AD',
  20395. '\uFBD6': '\u06AD',
  20396. '\uFBD7': '\u06C7',
  20397. '\uFBD8': '\u06C7',
  20398. '\uFBD9': '\u06C6',
  20399. '\uFBDA': '\u06C6',
  20400. '\uFBDB': '\u06C8',
  20401. '\uFBDC': '\u06C8',
  20402. '\uFBDD': '\u0677',
  20403. '\uFBDE': '\u06CB',
  20404. '\uFBDF': '\u06CB',
  20405. '\uFBE0': '\u06C5',
  20406. '\uFBE1': '\u06C5',
  20407. '\uFBE2': '\u06C9',
  20408. '\uFBE3': '\u06C9',
  20409. '\uFBE4': '\u06D0',
  20410. '\uFBE5': '\u06D0',
  20411. '\uFBE6': '\u06D0',
  20412. '\uFBE7': '\u06D0',
  20413. '\uFBE8': '\u0649',
  20414. '\uFBE9': '\u0649',
  20415. '\uFBEA': '\u0626\u0627',
  20416. '\uFBEB': '\u0626\u0627',
  20417. '\uFBEC': '\u0626\u06D5',
  20418. '\uFBED': '\u0626\u06D5',
  20419. '\uFBEE': '\u0626\u0648',
  20420. '\uFBEF': '\u0626\u0648',
  20421. '\uFBF0': '\u0626\u06C7',
  20422. '\uFBF1': '\u0626\u06C7',
  20423. '\uFBF2': '\u0626\u06C6',
  20424. '\uFBF3': '\u0626\u06C6',
  20425. '\uFBF4': '\u0626\u06C8',
  20426. '\uFBF5': '\u0626\u06C8',
  20427. '\uFBF6': '\u0626\u06D0',
  20428. '\uFBF7': '\u0626\u06D0',
  20429. '\uFBF8': '\u0626\u06D0',
  20430. '\uFBF9': '\u0626\u0649',
  20431. '\uFBFA': '\u0626\u0649',
  20432. '\uFBFB': '\u0626\u0649',
  20433. '\uFBFC': '\u06CC',
  20434. '\uFBFD': '\u06CC',
  20435. '\uFBFE': '\u06CC',
  20436. '\uFBFF': '\u06CC',
  20437. '\uFC00': '\u0626\u062C',
  20438. '\uFC01': '\u0626\u062D',
  20439. '\uFC02': '\u0626\u0645',
  20440. '\uFC03': '\u0626\u0649',
  20441. '\uFC04': '\u0626\u064A',
  20442. '\uFC05': '\u0628\u062C',
  20443. '\uFC06': '\u0628\u062D',
  20444. '\uFC07': '\u0628\u062E',
  20445. '\uFC08': '\u0628\u0645',
  20446. '\uFC09': '\u0628\u0649',
  20447. '\uFC0A': '\u0628\u064A',
  20448. '\uFC0B': '\u062A\u062C',
  20449. '\uFC0C': '\u062A\u062D',
  20450. '\uFC0D': '\u062A\u062E',
  20451. '\uFC0E': '\u062A\u0645',
  20452. '\uFC0F': '\u062A\u0649',
  20453. '\uFC10': '\u062A\u064A',
  20454. '\uFC11': '\u062B\u062C',
  20455. '\uFC12': '\u062B\u0645',
  20456. '\uFC13': '\u062B\u0649',
  20457. '\uFC14': '\u062B\u064A',
  20458. '\uFC15': '\u062C\u062D',
  20459. '\uFC16': '\u062C\u0645',
  20460. '\uFC17': '\u062D\u062C',
  20461. '\uFC18': '\u062D\u0645',
  20462. '\uFC19': '\u062E\u062C',
  20463. '\uFC1A': '\u062E\u062D',
  20464. '\uFC1B': '\u062E\u0645',
  20465. '\uFC1C': '\u0633\u062C',
  20466. '\uFC1D': '\u0633\u062D',
  20467. '\uFC1E': '\u0633\u062E',
  20468. '\uFC1F': '\u0633\u0645',
  20469. '\uFC20': '\u0635\u062D',
  20470. '\uFC21': '\u0635\u0645',
  20471. '\uFC22': '\u0636\u062C',
  20472. '\uFC23': '\u0636\u062D',
  20473. '\uFC24': '\u0636\u062E',
  20474. '\uFC25': '\u0636\u0645',
  20475. '\uFC26': '\u0637\u062D',
  20476. '\uFC27': '\u0637\u0645',
  20477. '\uFC28': '\u0638\u0645',
  20478. '\uFC29': '\u0639\u062C',
  20479. '\uFC2A': '\u0639\u0645',
  20480. '\uFC2B': '\u063A\u062C',
  20481. '\uFC2C': '\u063A\u0645',
  20482. '\uFC2D': '\u0641\u062C',
  20483. '\uFC2E': '\u0641\u062D',
  20484. '\uFC2F': '\u0641\u062E',
  20485. '\uFC30': '\u0641\u0645',
  20486. '\uFC31': '\u0641\u0649',
  20487. '\uFC32': '\u0641\u064A',
  20488. '\uFC33': '\u0642\u062D',
  20489. '\uFC34': '\u0642\u0645',
  20490. '\uFC35': '\u0642\u0649',
  20491. '\uFC36': '\u0642\u064A',
  20492. '\uFC37': '\u0643\u0627',
  20493. '\uFC38': '\u0643\u062C',
  20494. '\uFC39': '\u0643\u062D',
  20495. '\uFC3A': '\u0643\u062E',
  20496. '\uFC3B': '\u0643\u0644',
  20497. '\uFC3C': '\u0643\u0645',
  20498. '\uFC3D': '\u0643\u0649',
  20499. '\uFC3E': '\u0643\u064A',
  20500. '\uFC3F': '\u0644\u062C',
  20501. '\uFC40': '\u0644\u062D',
  20502. '\uFC41': '\u0644\u062E',
  20503. '\uFC42': '\u0644\u0645',
  20504. '\uFC43': '\u0644\u0649',
  20505. '\uFC44': '\u0644\u064A',
  20506. '\uFC45': '\u0645\u062C',
  20507. '\uFC46': '\u0645\u062D',
  20508. '\uFC47': '\u0645\u062E',
  20509. '\uFC48': '\u0645\u0645',
  20510. '\uFC49': '\u0645\u0649',
  20511. '\uFC4A': '\u0645\u064A',
  20512. '\uFC4B': '\u0646\u062C',
  20513. '\uFC4C': '\u0646\u062D',
  20514. '\uFC4D': '\u0646\u062E',
  20515. '\uFC4E': '\u0646\u0645',
  20516. '\uFC4F': '\u0646\u0649',
  20517. '\uFC50': '\u0646\u064A',
  20518. '\uFC51': '\u0647\u062C',
  20519. '\uFC52': '\u0647\u0645',
  20520. '\uFC53': '\u0647\u0649',
  20521. '\uFC54': '\u0647\u064A',
  20522. '\uFC55': '\u064A\u062C',
  20523. '\uFC56': '\u064A\u062D',
  20524. '\uFC57': '\u064A\u062E',
  20525. '\uFC58': '\u064A\u0645',
  20526. '\uFC59': '\u064A\u0649',
  20527. '\uFC5A': '\u064A\u064A',
  20528. '\uFC5B': '\u0630\u0670',
  20529. '\uFC5C': '\u0631\u0670',
  20530. '\uFC5D': '\u0649\u0670',
  20531. '\uFC5E': '\u0020\u064C\u0651',
  20532. '\uFC5F': '\u0020\u064D\u0651',
  20533. '\uFC60': '\u0020\u064E\u0651',
  20534. '\uFC61': '\u0020\u064F\u0651',
  20535. '\uFC62': '\u0020\u0650\u0651',
  20536. '\uFC63': '\u0020\u0651\u0670',
  20537. '\uFC64': '\u0626\u0631',
  20538. '\uFC65': '\u0626\u0632',
  20539. '\uFC66': '\u0626\u0645',
  20540. '\uFC67': '\u0626\u0646',
  20541. '\uFC68': '\u0626\u0649',
  20542. '\uFC69': '\u0626\u064A',
  20543. '\uFC6A': '\u0628\u0631',
  20544. '\uFC6B': '\u0628\u0632',
  20545. '\uFC6C': '\u0628\u0645',
  20546. '\uFC6D': '\u0628\u0646',
  20547. '\uFC6E': '\u0628\u0649',
  20548. '\uFC6F': '\u0628\u064A',
  20549. '\uFC70': '\u062A\u0631',
  20550. '\uFC71': '\u062A\u0632',
  20551. '\uFC72': '\u062A\u0645',
  20552. '\uFC73': '\u062A\u0646',
  20553. '\uFC74': '\u062A\u0649',
  20554. '\uFC75': '\u062A\u064A',
  20555. '\uFC76': '\u062B\u0631',
  20556. '\uFC77': '\u062B\u0632',
  20557. '\uFC78': '\u062B\u0645',
  20558. '\uFC79': '\u062B\u0646',
  20559. '\uFC7A': '\u062B\u0649',
  20560. '\uFC7B': '\u062B\u064A',
  20561. '\uFC7C': '\u0641\u0649',
  20562. '\uFC7D': '\u0641\u064A',
  20563. '\uFC7E': '\u0642\u0649',
  20564. '\uFC7F': '\u0642\u064A',
  20565. '\uFC80': '\u0643\u0627',
  20566. '\uFC81': '\u0643\u0644',
  20567. '\uFC82': '\u0643\u0645',
  20568. '\uFC83': '\u0643\u0649',
  20569. '\uFC84': '\u0643\u064A',
  20570. '\uFC85': '\u0644\u0645',
  20571. '\uFC86': '\u0644\u0649',
  20572. '\uFC87': '\u0644\u064A',
  20573. '\uFC88': '\u0645\u0627',
  20574. '\uFC89': '\u0645\u0645',
  20575. '\uFC8A': '\u0646\u0631',
  20576. '\uFC8B': '\u0646\u0632',
  20577. '\uFC8C': '\u0646\u0645',
  20578. '\uFC8D': '\u0646\u0646',
  20579. '\uFC8E': '\u0646\u0649',
  20580. '\uFC8F': '\u0646\u064A',
  20581. '\uFC90': '\u0649\u0670',
  20582. '\uFC91': '\u064A\u0631',
  20583. '\uFC92': '\u064A\u0632',
  20584. '\uFC93': '\u064A\u0645',
  20585. '\uFC94': '\u064A\u0646',
  20586. '\uFC95': '\u064A\u0649',
  20587. '\uFC96': '\u064A\u064A',
  20588. '\uFC97': '\u0626\u062C',
  20589. '\uFC98': '\u0626\u062D',
  20590. '\uFC99': '\u0626\u062E',
  20591. '\uFC9A': '\u0626\u0645',
  20592. '\uFC9B': '\u0626\u0647',
  20593. '\uFC9C': '\u0628\u062C',
  20594. '\uFC9D': '\u0628\u062D',
  20595. '\uFC9E': '\u0628\u062E',
  20596. '\uFC9F': '\u0628\u0645',
  20597. '\uFCA0': '\u0628\u0647',
  20598. '\uFCA1': '\u062A\u062C',
  20599. '\uFCA2': '\u062A\u062D',
  20600. '\uFCA3': '\u062A\u062E',
  20601. '\uFCA4': '\u062A\u0645',
  20602. '\uFCA5': '\u062A\u0647',
  20603. '\uFCA6': '\u062B\u0645',
  20604. '\uFCA7': '\u062C\u062D',
  20605. '\uFCA8': '\u062C\u0645',
  20606. '\uFCA9': '\u062D\u062C',
  20607. '\uFCAA': '\u062D\u0645',
  20608. '\uFCAB': '\u062E\u062C',
  20609. '\uFCAC': '\u062E\u0645',
  20610. '\uFCAD': '\u0633\u062C',
  20611. '\uFCAE': '\u0633\u062D',
  20612. '\uFCAF': '\u0633\u062E',
  20613. '\uFCB0': '\u0633\u0645',
  20614. '\uFCB1': '\u0635\u062D',
  20615. '\uFCB2': '\u0635\u062E',
  20616. '\uFCB3': '\u0635\u0645',
  20617. '\uFCB4': '\u0636\u062C',
  20618. '\uFCB5': '\u0636\u062D',
  20619. '\uFCB6': '\u0636\u062E',
  20620. '\uFCB7': '\u0636\u0645',
  20621. '\uFCB8': '\u0637\u062D',
  20622. '\uFCB9': '\u0638\u0645',
  20623. '\uFCBA': '\u0639\u062C',
  20624. '\uFCBB': '\u0639\u0645',
  20625. '\uFCBC': '\u063A\u062C',
  20626. '\uFCBD': '\u063A\u0645',
  20627. '\uFCBE': '\u0641\u062C',
  20628. '\uFCBF': '\u0641\u062D',
  20629. '\uFCC0': '\u0641\u062E',
  20630. '\uFCC1': '\u0641\u0645',
  20631. '\uFCC2': '\u0642\u062D',
  20632. '\uFCC3': '\u0642\u0645',
  20633. '\uFCC4': '\u0643\u062C',
  20634. '\uFCC5': '\u0643\u062D',
  20635. '\uFCC6': '\u0643\u062E',
  20636. '\uFCC7': '\u0643\u0644',
  20637. '\uFCC8': '\u0643\u0645',
  20638. '\uFCC9': '\u0644\u062C',
  20639. '\uFCCA': '\u0644\u062D',
  20640. '\uFCCB': '\u0644\u062E',
  20641. '\uFCCC': '\u0644\u0645',
  20642. '\uFCCD': '\u0644\u0647',
  20643. '\uFCCE': '\u0645\u062C',
  20644. '\uFCCF': '\u0645\u062D',
  20645. '\uFCD0': '\u0645\u062E',
  20646. '\uFCD1': '\u0645\u0645',
  20647. '\uFCD2': '\u0646\u062C',
  20648. '\uFCD3': '\u0646\u062D',
  20649. '\uFCD4': '\u0646\u062E',
  20650. '\uFCD5': '\u0646\u0645',
  20651. '\uFCD6': '\u0646\u0647',
  20652. '\uFCD7': '\u0647\u062C',
  20653. '\uFCD8': '\u0647\u0645',
  20654. '\uFCD9': '\u0647\u0670',
  20655. '\uFCDA': '\u064A\u062C',
  20656. '\uFCDB': '\u064A\u062D',
  20657. '\uFCDC': '\u064A\u062E',
  20658. '\uFCDD': '\u064A\u0645',
  20659. '\uFCDE': '\u064A\u0647',
  20660. '\uFCDF': '\u0626\u0645',
  20661. '\uFCE0': '\u0626\u0647',
  20662. '\uFCE1': '\u0628\u0645',
  20663. '\uFCE2': '\u0628\u0647',
  20664. '\uFCE3': '\u062A\u0645',
  20665. '\uFCE4': '\u062A\u0647',
  20666. '\uFCE5': '\u062B\u0645',
  20667. '\uFCE6': '\u062B\u0647',
  20668. '\uFCE7': '\u0633\u0645',
  20669. '\uFCE8': '\u0633\u0647',
  20670. '\uFCE9': '\u0634\u0645',
  20671. '\uFCEA': '\u0634\u0647',
  20672. '\uFCEB': '\u0643\u0644',
  20673. '\uFCEC': '\u0643\u0645',
  20674. '\uFCED': '\u0644\u0645',
  20675. '\uFCEE': '\u0646\u0645',
  20676. '\uFCEF': '\u0646\u0647',
  20677. '\uFCF0': '\u064A\u0645',
  20678. '\uFCF1': '\u064A\u0647',
  20679. '\uFCF2': '\u0640\u064E\u0651',
  20680. '\uFCF3': '\u0640\u064F\u0651',
  20681. '\uFCF4': '\u0640\u0650\u0651',
  20682. '\uFCF5': '\u0637\u0649',
  20683. '\uFCF6': '\u0637\u064A',
  20684. '\uFCF7': '\u0639\u0649',
  20685. '\uFCF8': '\u0639\u064A',
  20686. '\uFCF9': '\u063A\u0649',
  20687. '\uFCFA': '\u063A\u064A',
  20688. '\uFCFB': '\u0633\u0649',
  20689. '\uFCFC': '\u0633\u064A',
  20690. '\uFCFD': '\u0634\u0649',
  20691. '\uFCFE': '\u0634\u064A',
  20692. '\uFCFF': '\u062D\u0649',
  20693. '\uFD00': '\u062D\u064A',
  20694. '\uFD01': '\u062C\u0649',
  20695. '\uFD02': '\u062C\u064A',
  20696. '\uFD03': '\u062E\u0649',
  20697. '\uFD04': '\u062E\u064A',
  20698. '\uFD05': '\u0635\u0649',
  20699. '\uFD06': '\u0635\u064A',
  20700. '\uFD07': '\u0636\u0649',
  20701. '\uFD08': '\u0636\u064A',
  20702. '\uFD09': '\u0634\u062C',
  20703. '\uFD0A': '\u0634\u062D',
  20704. '\uFD0B': '\u0634\u062E',
  20705. '\uFD0C': '\u0634\u0645',
  20706. '\uFD0D': '\u0634\u0631',
  20707. '\uFD0E': '\u0633\u0631',
  20708. '\uFD0F': '\u0635\u0631',
  20709. '\uFD10': '\u0636\u0631',
  20710. '\uFD11': '\u0637\u0649',
  20711. '\uFD12': '\u0637\u064A',
  20712. '\uFD13': '\u0639\u0649',
  20713. '\uFD14': '\u0639\u064A',
  20714. '\uFD15': '\u063A\u0649',
  20715. '\uFD16': '\u063A\u064A',
  20716. '\uFD17': '\u0633\u0649',
  20717. '\uFD18': '\u0633\u064A',
  20718. '\uFD19': '\u0634\u0649',
  20719. '\uFD1A': '\u0634\u064A',
  20720. '\uFD1B': '\u062D\u0649',
  20721. '\uFD1C': '\u062D\u064A',
  20722. '\uFD1D': '\u062C\u0649',
  20723. '\uFD1E': '\u062C\u064A',
  20724. '\uFD1F': '\u062E\u0649',
  20725. '\uFD20': '\u062E\u064A',
  20726. '\uFD21': '\u0635\u0649',
  20727. '\uFD22': '\u0635\u064A',
  20728. '\uFD23': '\u0636\u0649',
  20729. '\uFD24': '\u0636\u064A',
  20730. '\uFD25': '\u0634\u062C',
  20731. '\uFD26': '\u0634\u062D',
  20732. '\uFD27': '\u0634\u062E',
  20733. '\uFD28': '\u0634\u0645',
  20734. '\uFD29': '\u0634\u0631',
  20735. '\uFD2A': '\u0633\u0631',
  20736. '\uFD2B': '\u0635\u0631',
  20737. '\uFD2C': '\u0636\u0631',
  20738. '\uFD2D': '\u0634\u062C',
  20739. '\uFD2E': '\u0634\u062D',
  20740. '\uFD2F': '\u0634\u062E',
  20741. '\uFD30': '\u0634\u0645',
  20742. '\uFD31': '\u0633\u0647',
  20743. '\uFD32': '\u0634\u0647',
  20744. '\uFD33': '\u0637\u0645',
  20745. '\uFD34': '\u0633\u062C',
  20746. '\uFD35': '\u0633\u062D',
  20747. '\uFD36': '\u0633\u062E',
  20748. '\uFD37': '\u0634\u062C',
  20749. '\uFD38': '\u0634\u062D',
  20750. '\uFD39': '\u0634\u062E',
  20751. '\uFD3A': '\u0637\u0645',
  20752. '\uFD3B': '\u0638\u0645',
  20753. '\uFD3C': '\u0627\u064B',
  20754. '\uFD3D': '\u0627\u064B',
  20755. '\uFD50': '\u062A\u062C\u0645',
  20756. '\uFD51': '\u062A\u062D\u062C',
  20757. '\uFD52': '\u062A\u062D\u062C',
  20758. '\uFD53': '\u062A\u062D\u0645',
  20759. '\uFD54': '\u062A\u062E\u0645',
  20760. '\uFD55': '\u062A\u0645\u062C',
  20761. '\uFD56': '\u062A\u0645\u062D',
  20762. '\uFD57': '\u062A\u0645\u062E',
  20763. '\uFD58': '\u062C\u0645\u062D',
  20764. '\uFD59': '\u062C\u0645\u062D',
  20765. '\uFD5A': '\u062D\u0645\u064A',
  20766. '\uFD5B': '\u062D\u0645\u0649',
  20767. '\uFD5C': '\u0633\u062D\u062C',
  20768. '\uFD5D': '\u0633\u062C\u062D',
  20769. '\uFD5E': '\u0633\u062C\u0649',
  20770. '\uFD5F': '\u0633\u0645\u062D',
  20771. '\uFD60': '\u0633\u0645\u062D',
  20772. '\uFD61': '\u0633\u0645\u062C',
  20773. '\uFD62': '\u0633\u0645\u0645',
  20774. '\uFD63': '\u0633\u0645\u0645',
  20775. '\uFD64': '\u0635\u062D\u062D',
  20776. '\uFD65': '\u0635\u062D\u062D',
  20777. '\uFD66': '\u0635\u0645\u0645',
  20778. '\uFD67': '\u0634\u062D\u0645',
  20779. '\uFD68': '\u0634\u062D\u0645',
  20780. '\uFD69': '\u0634\u062C\u064A',
  20781. '\uFD6A': '\u0634\u0645\u062E',
  20782. '\uFD6B': '\u0634\u0645\u062E',
  20783. '\uFD6C': '\u0634\u0645\u0645',
  20784. '\uFD6D': '\u0634\u0645\u0645',
  20785. '\uFD6E': '\u0636\u062D\u0649',
  20786. '\uFD6F': '\u0636\u062E\u0645',
  20787. '\uFD70': '\u0636\u062E\u0645',
  20788. '\uFD71': '\u0637\u0645\u062D',
  20789. '\uFD72': '\u0637\u0645\u062D',
  20790. '\uFD73': '\u0637\u0645\u0645',
  20791. '\uFD74': '\u0637\u0645\u064A',
  20792. '\uFD75': '\u0639\u062C\u0645',
  20793. '\uFD76': '\u0639\u0645\u0645',
  20794. '\uFD77': '\u0639\u0645\u0645',
  20795. '\uFD78': '\u0639\u0645\u0649',
  20796. '\uFD79': '\u063A\u0645\u0645',
  20797. '\uFD7A': '\u063A\u0645\u064A',
  20798. '\uFD7B': '\u063A\u0645\u0649',
  20799. '\uFD7C': '\u0641\u062E\u0645',
  20800. '\uFD7D': '\u0641\u062E\u0645',
  20801. '\uFD7E': '\u0642\u0645\u062D',
  20802. '\uFD7F': '\u0642\u0645\u0645',
  20803. '\uFD80': '\u0644\u062D\u0645',
  20804. '\uFD81': '\u0644\u062D\u064A',
  20805. '\uFD82': '\u0644\u062D\u0649',
  20806. '\uFD83': '\u0644\u062C\u062C',
  20807. '\uFD84': '\u0644\u062C\u062C',
  20808. '\uFD85': '\u0644\u062E\u0645',
  20809. '\uFD86': '\u0644\u062E\u0645',
  20810. '\uFD87': '\u0644\u0645\u062D',
  20811. '\uFD88': '\u0644\u0645\u062D',
  20812. '\uFD89': '\u0645\u062D\u062C',
  20813. '\uFD8A': '\u0645\u062D\u0645',
  20814. '\uFD8B': '\u0645\u062D\u064A',
  20815. '\uFD8C': '\u0645\u062C\u062D',
  20816. '\uFD8D': '\u0645\u062C\u0645',
  20817. '\uFD8E': '\u0645\u062E\u062C',
  20818. '\uFD8F': '\u0645\u062E\u0645',
  20819. '\uFD92': '\u0645\u062C\u062E',
  20820. '\uFD93': '\u0647\u0645\u062C',
  20821. '\uFD94': '\u0647\u0645\u0645',
  20822. '\uFD95': '\u0646\u062D\u0645',
  20823. '\uFD96': '\u0646\u062D\u0649',
  20824. '\uFD97': '\u0646\u062C\u0645',
  20825. '\uFD98': '\u0646\u062C\u0645',
  20826. '\uFD99': '\u0646\u062C\u0649',
  20827. '\uFD9A': '\u0646\u0645\u064A',
  20828. '\uFD9B': '\u0646\u0645\u0649',
  20829. '\uFD9C': '\u064A\u0645\u0645',
  20830. '\uFD9D': '\u064A\u0645\u0645',
  20831. '\uFD9E': '\u0628\u062E\u064A',
  20832. '\uFD9F': '\u062A\u062C\u064A',
  20833. '\uFDA0': '\u062A\u062C\u0649',
  20834. '\uFDA1': '\u062A\u062E\u064A',
  20835. '\uFDA2': '\u062A\u062E\u0649',
  20836. '\uFDA3': '\u062A\u0645\u064A',
  20837. '\uFDA4': '\u062A\u0645\u0649',
  20838. '\uFDA5': '\u062C\u0645\u064A',
  20839. '\uFDA6': '\u062C\u062D\u0649',
  20840. '\uFDA7': '\u062C\u0645\u0649',
  20841. '\uFDA8': '\u0633\u062E\u0649',
  20842. '\uFDA9': '\u0635\u062D\u064A',
  20843. '\uFDAA': '\u0634\u062D\u064A',
  20844. '\uFDAB': '\u0636\u062D\u064A',
  20845. '\uFDAC': '\u0644\u062C\u064A',
  20846. '\uFDAD': '\u0644\u0645\u064A',
  20847. '\uFDAE': '\u064A\u062D\u064A',
  20848. '\uFDAF': '\u064A\u062C\u064A',
  20849. '\uFDB0': '\u064A\u0645\u064A',
  20850. '\uFDB1': '\u0645\u0645\u064A',
  20851. '\uFDB2': '\u0642\u0645\u064A',
  20852. '\uFDB3': '\u0646\u062D\u064A',
  20853. '\uFDB4': '\u0642\u0645\u062D',
  20854. '\uFDB5': '\u0644\u062D\u0645',
  20855. '\uFDB6': '\u0639\u0645\u064A',
  20856. '\uFDB7': '\u0643\u0645\u064A',
  20857. '\uFDB8': '\u0646\u062C\u062D',
  20858. '\uFDB9': '\u0645\u062E\u064A',
  20859. '\uFDBA': '\u0644\u062C\u0645',
  20860. '\uFDBB': '\u0643\u0645\u0645',
  20861. '\uFDBC': '\u0644\u062C\u0645',
  20862. '\uFDBD': '\u0646\u062C\u062D',
  20863. '\uFDBE': '\u062C\u062D\u064A',
  20864. '\uFDBF': '\u062D\u062C\u064A',
  20865. '\uFDC0': '\u0645\u062C\u064A',
  20866. '\uFDC1': '\u0641\u0645\u064A',
  20867. '\uFDC2': '\u0628\u062D\u064A',
  20868. '\uFDC3': '\u0643\u0645\u0645',
  20869. '\uFDC4': '\u0639\u062C\u0645',
  20870. '\uFDC5': '\u0635\u0645\u0645',
  20871. '\uFDC6': '\u0633\u062E\u064A',
  20872. '\uFDC7': '\u0646\u062C\u064A',
  20873. '\uFE49': '\u203E',
  20874. '\uFE4A': '\u203E',
  20875. '\uFE4B': '\u203E',
  20876. '\uFE4C': '\u203E',
  20877. '\uFE4D': '\u005F',
  20878. '\uFE4E': '\u005F',
  20879. '\uFE4F': '\u005F',
  20880. '\uFE80': '\u0621',
  20881. '\uFE81': '\u0622',
  20882. '\uFE82': '\u0622',
  20883. '\uFE83': '\u0623',
  20884. '\uFE84': '\u0623',
  20885. '\uFE85': '\u0624',
  20886. '\uFE86': '\u0624',
  20887. '\uFE87': '\u0625',
  20888. '\uFE88': '\u0625',
  20889. '\uFE89': '\u0626',
  20890. '\uFE8A': '\u0626',
  20891. '\uFE8B': '\u0626',
  20892. '\uFE8C': '\u0626',
  20893. '\uFE8D': '\u0627',
  20894. '\uFE8E': '\u0627',
  20895. '\uFE8F': '\u0628',
  20896. '\uFE90': '\u0628',
  20897. '\uFE91': '\u0628',
  20898. '\uFE92': '\u0628',
  20899. '\uFE93': '\u0629',
  20900. '\uFE94': '\u0629',
  20901. '\uFE95': '\u062A',
  20902. '\uFE96': '\u062A',
  20903. '\uFE97': '\u062A',
  20904. '\uFE98': '\u062A',
  20905. '\uFE99': '\u062B',
  20906. '\uFE9A': '\u062B',
  20907. '\uFE9B': '\u062B',
  20908. '\uFE9C': '\u062B',
  20909. '\uFE9D': '\u062C',
  20910. '\uFE9E': '\u062C',
  20911. '\uFE9F': '\u062C',
  20912. '\uFEA0': '\u062C',
  20913. '\uFEA1': '\u062D',
  20914. '\uFEA2': '\u062D',
  20915. '\uFEA3': '\u062D',
  20916. '\uFEA4': '\u062D',
  20917. '\uFEA5': '\u062E',
  20918. '\uFEA6': '\u062E',
  20919. '\uFEA7': '\u062E',
  20920. '\uFEA8': '\u062E',
  20921. '\uFEA9': '\u062F',
  20922. '\uFEAA': '\u062F',
  20923. '\uFEAB': '\u0630',
  20924. '\uFEAC': '\u0630',
  20925. '\uFEAD': '\u0631',
  20926. '\uFEAE': '\u0631',
  20927. '\uFEAF': '\u0632',
  20928. '\uFEB0': '\u0632',
  20929. '\uFEB1': '\u0633',
  20930. '\uFEB2': '\u0633',
  20931. '\uFEB3': '\u0633',
  20932. '\uFEB4': '\u0633',
  20933. '\uFEB5': '\u0634',
  20934. '\uFEB6': '\u0634',
  20935. '\uFEB7': '\u0634',
  20936. '\uFEB8': '\u0634',
  20937. '\uFEB9': '\u0635',
  20938. '\uFEBA': '\u0635',
  20939. '\uFEBB': '\u0635',
  20940. '\uFEBC': '\u0635',
  20941. '\uFEBD': '\u0636',
  20942. '\uFEBE': '\u0636',
  20943. '\uFEBF': '\u0636',
  20944. '\uFEC0': '\u0636',
  20945. '\uFEC1': '\u0637',
  20946. '\uFEC2': '\u0637',
  20947. '\uFEC3': '\u0637',
  20948. '\uFEC4': '\u0637',
  20949. '\uFEC5': '\u0638',
  20950. '\uFEC6': '\u0638',
  20951. '\uFEC7': '\u0638',
  20952. '\uFEC8': '\u0638',
  20953. '\uFEC9': '\u0639',
  20954. '\uFECA': '\u0639',
  20955. '\uFECB': '\u0639',
  20956. '\uFECC': '\u0639',
  20957. '\uFECD': '\u063A',
  20958. '\uFECE': '\u063A',
  20959. '\uFECF': '\u063A',
  20960. '\uFED0': '\u063A',
  20961. '\uFED1': '\u0641',
  20962. '\uFED2': '\u0641',
  20963. '\uFED3': '\u0641',
  20964. '\uFED4': '\u0641',
  20965. '\uFED5': '\u0642',
  20966. '\uFED6': '\u0642',
  20967. '\uFED7': '\u0642',
  20968. '\uFED8': '\u0642',
  20969. '\uFED9': '\u0643',
  20970. '\uFEDA': '\u0643',
  20971. '\uFEDB': '\u0643',
  20972. '\uFEDC': '\u0643',
  20973. '\uFEDD': '\u0644',
  20974. '\uFEDE': '\u0644',
  20975. '\uFEDF': '\u0644',
  20976. '\uFEE0': '\u0644',
  20977. '\uFEE1': '\u0645',
  20978. '\uFEE2': '\u0645',
  20979. '\uFEE3': '\u0645',
  20980. '\uFEE4': '\u0645',
  20981. '\uFEE5': '\u0646',
  20982. '\uFEE6': '\u0646',
  20983. '\uFEE7': '\u0646',
  20984. '\uFEE8': '\u0646',
  20985. '\uFEE9': '\u0647',
  20986. '\uFEEA': '\u0647',
  20987. '\uFEEB': '\u0647',
  20988. '\uFEEC': '\u0647',
  20989. '\uFEED': '\u0648',
  20990. '\uFEEE': '\u0648',
  20991. '\uFEEF': '\u0649',
  20992. '\uFEF0': '\u0649',
  20993. '\uFEF1': '\u064A',
  20994. '\uFEF2': '\u064A',
  20995. '\uFEF3': '\u064A',
  20996. '\uFEF4': '\u064A',
  20997. '\uFEF5': '\u0644\u0622',
  20998. '\uFEF6': '\u0644\u0622',
  20999. '\uFEF7': '\u0644\u0623',
  21000. '\uFEF8': '\u0644\u0623',
  21001. '\uFEF9': '\u0644\u0625',
  21002. '\uFEFA': '\u0644\u0625',
  21003. '\uFEFB': '\u0644\u0627',
  21004. '\uFEFC': '\u0644\u0627'
  21005. };
  21006. function reverseIfRtl(chars) {
  21007. var charsLength = chars.length;
  21008. //reverse an arabic ligature
  21009. if (charsLength <= 1 || !isRTLRangeFor(chars.charCodeAt(0))) {
  21010. return chars;
  21011. }
  21012. var s = '';
  21013. for (var ii = charsLength - 1; ii >= 0; ii--) {
  21014. s += chars[ii];
  21015. }
  21016. return s;
  21017. }
  21018. function adjustWidths(properties) {
  21019. if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
  21020. return;
  21021. }
  21022. // adjusting width to fontMatrix scale
  21023. var scale = 0.001 / properties.fontMatrix[0];
  21024. var glyphsWidths = properties.widths;
  21025. for (var glyph in glyphsWidths) {
  21026. glyphsWidths[glyph] *= scale;
  21027. }
  21028. properties.defaultWidth *= scale;
  21029. }
  21030. function getFontType(type, subtype) {
  21031. switch (type) {
  21032. case 'Type1':
  21033. return subtype === 'Type1C' ? FontType.TYPE1C : FontType.TYPE1;
  21034. case 'CIDFontType0':
  21035. return subtype === 'CIDFontType0C' ? FontType.CIDFONTTYPE0C :
  21036. FontType.CIDFONTTYPE0;
  21037. case 'OpenType':
  21038. return FontType.OPENTYPE;
  21039. case 'TrueType':
  21040. return FontType.TRUETYPE;
  21041. case 'CIDFontType2':
  21042. return FontType.CIDFONTTYPE2;
  21043. case 'MMType1':
  21044. return FontType.MMTYPE1;
  21045. case 'Type0':
  21046. return FontType.TYPE0;
  21047. default:
  21048. return FontType.UNKNOWN;
  21049. }
  21050. }
  21051. var Glyph = (function GlyphClosure() {
  21052. function Glyph(fontChar, unicode, accent, width, vmetric, operatorListId) {
  21053. this.fontChar = fontChar;
  21054. this.unicode = unicode;
  21055. this.accent = accent;
  21056. this.width = width;
  21057. this.vmetric = vmetric;
  21058. this.operatorListId = operatorListId;
  21059. }
  21060. Glyph.prototype.matchesForCache =
  21061. function(fontChar, unicode, accent, width, vmetric, operatorListId) {
  21062. return this.fontChar === fontChar &&
  21063. this.unicode === unicode &&
  21064. this.accent === accent &&
  21065. this.width === width &&
  21066. this.vmetric === vmetric &&
  21067. this.operatorListId === operatorListId;
  21068. };
  21069. return Glyph;
  21070. })();
  21071. var ToUnicodeMap = (function ToUnicodeMapClosure() {
  21072. function ToUnicodeMap(cmap) {
  21073. // The elements of this._map can be integers or strings, depending on how
  21074. // |cmap| was created.
  21075. this._map = cmap;
  21076. }
  21077. ToUnicodeMap.prototype = {
  21078. get length() {
  21079. return this._map.length;
  21080. },
  21081. forEach: function(callback) {
  21082. for (var charCode in this._map) {
  21083. callback(charCode, this._map[charCode].charCodeAt(0));
  21084. }
  21085. },
  21086. has: function(i) {
  21087. return this._map[i] !== undefined;
  21088. },
  21089. get: function(i) {
  21090. return this._map[i];
  21091. },
  21092. charCodeOf: function(v) {
  21093. return this._map.indexOf(v);
  21094. }
  21095. };
  21096. return ToUnicodeMap;
  21097. })();
  21098. var IdentityToUnicodeMap = (function IdentityToUnicodeMapClosure() {
  21099. function IdentityToUnicodeMap(firstChar, lastChar) {
  21100. this.firstChar = firstChar;
  21101. this.lastChar = lastChar;
  21102. }
  21103. IdentityToUnicodeMap.prototype = {
  21104. get length() {
  21105. return (this.lastChar + 1) - this.firstChar;
  21106. },
  21107. forEach: function (callback) {
  21108. for (var i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
  21109. callback(i, i);
  21110. }
  21111. },
  21112. has: function (i) {
  21113. return this.firstChar <= i && i <= this.lastChar;
  21114. },
  21115. get: function (i) {
  21116. if (this.firstChar <= i && i <= this.lastChar) {
  21117. return String.fromCharCode(i);
  21118. }
  21119. return undefined;
  21120. },
  21121. charCodeOf: function (v) {
  21122. error('should not call .charCodeOf');
  21123. }
  21124. };
  21125. return IdentityToUnicodeMap;
  21126. })();
  21127. var OpenTypeFileBuilder = (function OpenTypeFileBuilderClosure() {
  21128. function writeInt16(dest, offset, num) {
  21129. dest[offset] = (num >> 8) & 0xFF;
  21130. dest[offset + 1] = num & 0xFF;
  21131. }
  21132. function writeInt32(dest, offset, num) {
  21133. dest[offset] = (num >> 24) & 0xFF;
  21134. dest[offset + 1] = (num >> 16) & 0xFF;
  21135. dest[offset + 2] = (num >> 8) & 0xFF;
  21136. dest[offset + 3] = num & 0xFF;
  21137. }
  21138. function writeData(dest, offset, data) {
  21139. var i, ii;
  21140. if (data instanceof Uint8Array) {
  21141. dest.set(data, offset);
  21142. } else if (typeof data === 'string') {
  21143. for (i = 0, ii = data.length; i < ii; i++) {
  21144. dest[offset++] = data.charCodeAt(i) & 0xFF;
  21145. }
  21146. } else {
  21147. // treating everything else as array
  21148. for (i = 0, ii = data.length; i < ii; i++) {
  21149. dest[offset++] = data[i] & 0xFF;
  21150. }
  21151. }
  21152. }
  21153. function OpenTypeFileBuilder(sfnt) {
  21154. this.sfnt = sfnt;
  21155. this.tables = Object.create(null);
  21156. }
  21157. OpenTypeFileBuilder.getSearchParams =
  21158. function OpenTypeFileBuilder_getSearchParams(entriesCount, entrySize) {
  21159. var maxPower2 = 1, log2 = 0;
  21160. while ((maxPower2 ^ entriesCount) > maxPower2) {
  21161. maxPower2 <<= 1;
  21162. log2++;
  21163. }
  21164. var searchRange = maxPower2 * entrySize;
  21165. return {
  21166. range: searchRange,
  21167. entry: log2,
  21168. rangeShift: entrySize * entriesCount - searchRange
  21169. };
  21170. };
  21171. var OTF_HEADER_SIZE = 12;
  21172. var OTF_TABLE_ENTRY_SIZE = 16;
  21173. OpenTypeFileBuilder.prototype = {
  21174. toArray: function OpenTypeFileBuilder_toArray() {
  21175. var sfnt = this.sfnt;
  21176. // Tables needs to be written by ascendant alphabetic order
  21177. var tables = this.tables;
  21178. var tablesNames = Object.keys(tables);
  21179. tablesNames.sort();
  21180. var numTables = tablesNames.length;
  21181. var i, j, jj, table, tableName;
  21182. // layout the tables data
  21183. var offset = OTF_HEADER_SIZE + numTables * OTF_TABLE_ENTRY_SIZE;
  21184. var tableOffsets = [offset];
  21185. for (i = 0; i < numTables; i++) {
  21186. table = tables[tablesNames[i]];
  21187. var paddedLength = ((table.length + 3) & ~3) >>> 0;
  21188. offset += paddedLength;
  21189. tableOffsets.push(offset);
  21190. }
  21191. var file = new Uint8Array(offset);
  21192. // write the table data first (mostly for checksum)
  21193. for (i = 0; i < numTables; i++) {
  21194. table = tables[tablesNames[i]];
  21195. writeData(file, tableOffsets[i], table);
  21196. }
  21197. // sfnt version (4 bytes)
  21198. if (sfnt === 'true') {
  21199. // Windows hates the Mac TrueType sfnt version number
  21200. sfnt = string32(0x00010000);
  21201. }
  21202. file[0] = sfnt.charCodeAt(0) & 0xFF;
  21203. file[1] = sfnt.charCodeAt(1) & 0xFF;
  21204. file[2] = sfnt.charCodeAt(2) & 0xFF;
  21205. file[3] = sfnt.charCodeAt(3) & 0xFF;
  21206. // numTables (2 bytes)
  21207. writeInt16(file, 4, numTables);
  21208. var searchParams = OpenTypeFileBuilder.getSearchParams(numTables, 16);
  21209. // searchRange (2 bytes)
  21210. writeInt16(file, 6, searchParams.range);
  21211. // entrySelector (2 bytes)
  21212. writeInt16(file, 8, searchParams.entry);
  21213. // rangeShift (2 bytes)
  21214. writeInt16(file, 10, searchParams.rangeShift);
  21215. offset = OTF_HEADER_SIZE;
  21216. // writing table entries
  21217. for (i = 0; i < numTables; i++) {
  21218. tableName = tablesNames[i];
  21219. file[offset] = tableName.charCodeAt(0) & 0xFF;
  21220. file[offset + 1] = tableName.charCodeAt(1) & 0xFF;
  21221. file[offset + 2] = tableName.charCodeAt(2) & 0xFF;
  21222. file[offset + 3] = tableName.charCodeAt(3) & 0xFF;
  21223. // checksum
  21224. var checksum = 0;
  21225. for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
  21226. var quad = (file[j] << 24) + (file[j + 1] << 16) +
  21227. (file[j + 2] << 8) + file[j + 3];
  21228. checksum = (checksum + quad) | 0;
  21229. }
  21230. writeInt32(file, offset + 4, checksum);
  21231. // offset
  21232. writeInt32(file, offset + 8, tableOffsets[i]);
  21233. // length
  21234. writeInt32(file, offset + 12, tables[tableName].length);
  21235. offset += OTF_TABLE_ENTRY_SIZE;
  21236. }
  21237. return file;
  21238. },
  21239. addTable: function OpenTypeFileBuilder_addTable(tag, data) {
  21240. if (tag in this.tables) {
  21241. throw new Error('Table ' + tag + ' already exists');
  21242. }
  21243. this.tables[tag] = data;
  21244. }
  21245. };
  21246. return OpenTypeFileBuilder;
  21247. })();
  21248. // Problematic Unicode characters in the fonts that needs to be moved to avoid
  21249. // issues when they are painted on the canvas, e.g. complex-script shaping or
  21250. // control/whitespace characters. The ranges are listed in pairs: the first item
  21251. // is a code of the first problematic code, the second one is the next
  21252. // non-problematic code. The ranges must be in sorted order.
  21253. var ProblematicCharRanges = new Int32Array([
  21254. // Control characters.
  21255. 0x0000, 0x0020,
  21256. 0x007F, 0x00A1,
  21257. 0x00AD, 0x00AE,
  21258. // Chars that is used in complex-script shaping.
  21259. 0x0600, 0x0780,
  21260. 0x08A0, 0x10A0,
  21261. 0x1780, 0x1800,
  21262. // General punctuation chars.
  21263. 0x2000, 0x2010,
  21264. 0x2011, 0x2012,
  21265. 0x2028, 0x2030,
  21266. 0x205F, 0x2070,
  21267. 0x25CC, 0x25CD,
  21268. // Chars that is used in complex-script shaping.
  21269. 0xAA60, 0xAA80,
  21270. // Specials Unicode block.
  21271. 0xFFF0, 0x10000
  21272. ]);
  21273. /**
  21274. * 'Font' is the class the outside world should use, it encapsulate all the font
  21275. * decoding logics whatever type it is (assuming the font type is supported).
  21276. *
  21277. * For example to read a Type1 font and to attach it to the document:
  21278. * var type1Font = new Font("MyFontName", binaryFile, propertiesObject);
  21279. * type1Font.bind();
  21280. */
  21281. var Font = (function FontClosure() {
  21282. function Font(name, file, properties) {
  21283. var charCode, glyphName, fontChar;
  21284. this.name = name;
  21285. this.loadedName = properties.loadedName;
  21286. this.isType3Font = properties.isType3Font;
  21287. this.sizes = [];
  21288. this.glyphCache = {};
  21289. var names = name.split('+');
  21290. names = names.length > 1 ? names[1] : names[0];
  21291. names = names.split(/[-,_]/g)[0];
  21292. this.isSerifFont = !!(properties.flags & FontFlags.Serif);
  21293. this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  21294. this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);
  21295. var type = properties.type;
  21296. var subtype = properties.subtype;
  21297. this.type = type;
  21298. this.fallbackName = (this.isMonospace ? 'monospace' :
  21299. (this.isSerifFont ? 'serif' : 'sans-serif'));
  21300. this.differences = properties.differences;
  21301. this.widths = properties.widths;
  21302. this.defaultWidth = properties.defaultWidth;
  21303. this.composite = properties.composite;
  21304. this.wideChars = properties.wideChars;
  21305. this.cMap = properties.cMap;
  21306. this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
  21307. this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
  21308. this.fontMatrix = properties.fontMatrix;
  21309. this.bbox = properties.bbox;
  21310. this.toUnicode = properties.toUnicode = this.buildToUnicode(properties);
  21311. this.toFontChar = [];
  21312. if (properties.type === 'Type3') {
  21313. for (charCode = 0; charCode < 256; charCode++) {
  21314. this.toFontChar[charCode] = (this.differences[charCode] ||
  21315. properties.defaultEncoding[charCode]);
  21316. }
  21317. this.fontType = FontType.TYPE3;
  21318. return;
  21319. }
  21320. this.cidEncoding = properties.cidEncoding;
  21321. this.vertical = properties.vertical;
  21322. if (this.vertical) {
  21323. this.vmetrics = properties.vmetrics;
  21324. this.defaultVMetrics = properties.defaultVMetrics;
  21325. }
  21326. if (!file || file.isEmpty) {
  21327. if (file) {
  21328. // Some bad PDF generators will include empty font files,
  21329. // attempting to recover by assuming that no file exists.
  21330. warn('Font file is empty in "' + name + '" (' + this.loadedName + ')');
  21331. }
  21332. this.missingFile = true;
  21333. // The file data is not specified. Trying to fix the font name
  21334. // to be used with the canvas.font.
  21335. var fontName = name.replace(/[,_]/g, '-');
  21336. var isStandardFont = !!stdFontMap[fontName] ||
  21337. !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]);
  21338. fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
  21339. this.bold = (fontName.search(/bold/gi) !== -1);
  21340. this.italic = ((fontName.search(/oblique/gi) !== -1) ||
  21341. (fontName.search(/italic/gi) !== -1));
  21342. // Use 'name' instead of 'fontName' here because the original
  21343. // name ArialBlack for example will be replaced by Helvetica.
  21344. this.black = (name.search(/Black/g) !== -1);
  21345. // if at least one width is present, remeasure all chars when exists
  21346. this.remeasure = Object.keys(this.widths).length > 0;
  21347. if (isStandardFont && type === 'CIDFontType2' &&
  21348. properties.cidEncoding.indexOf('Identity-') === 0) {
  21349. // Standard fonts might be embedded as CID font without glyph mapping.
  21350. // Building one based on GlyphMapForStandardFonts.
  21351. var map = [];
  21352. for (charCode in GlyphMapForStandardFonts) {
  21353. map[+charCode] = GlyphMapForStandardFonts[charCode];
  21354. }
  21355. if (/ArialBlack/i.test(name)) {
  21356. for (charCode in SupplementalGlyphMapForArialBlack) {
  21357. map[+charCode] = SupplementalGlyphMapForArialBlack[charCode];
  21358. }
  21359. }
  21360. var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
  21361. if (!isIdentityUnicode) {
  21362. this.toUnicode.forEach(function(charCode, unicodeCharCode) {
  21363. map[+charCode] = unicodeCharCode;
  21364. });
  21365. }
  21366. this.toFontChar = map;
  21367. this.toUnicode = new ToUnicodeMap(map);
  21368. } else if (/Symbol/i.test(fontName)) {
  21369. var symbols = Encodings.SymbolSetEncoding;
  21370. for (charCode in symbols) {
  21371. fontChar = GlyphsUnicode[symbols[charCode]];
  21372. if (!fontChar) {
  21373. continue;
  21374. }
  21375. this.toFontChar[charCode] = fontChar;
  21376. }
  21377. for (charCode in properties.differences) {
  21378. fontChar = GlyphsUnicode[properties.differences[charCode]];
  21379. if (!fontChar) {
  21380. continue;
  21381. }
  21382. this.toFontChar[charCode] = fontChar;
  21383. }
  21384. } else if (/Dingbats/i.test(fontName)) {
  21385. if (/Wingdings/i.test(name)) {
  21386. warn('Wingdings font without embedded font file, ' +
  21387. 'falling back to the ZapfDingbats encoding.');
  21388. }
  21389. var dingbats = Encodings.ZapfDingbatsEncoding;
  21390. for (charCode in dingbats) {
  21391. fontChar = DingbatsGlyphsUnicode[dingbats[charCode]];
  21392. if (!fontChar) {
  21393. continue;
  21394. }
  21395. this.toFontChar[charCode] = fontChar;
  21396. }
  21397. for (charCode in properties.differences) {
  21398. fontChar = DingbatsGlyphsUnicode[properties.differences[charCode]];
  21399. if (!fontChar) {
  21400. continue;
  21401. }
  21402. this.toFontChar[charCode] = fontChar;
  21403. }
  21404. } else if (isStandardFont) {
  21405. this.toFontChar = [];
  21406. for (charCode in properties.defaultEncoding) {
  21407. glyphName = (properties.differences[charCode] ||
  21408. properties.defaultEncoding[charCode]);
  21409. this.toFontChar[charCode] = GlyphsUnicode[glyphName];
  21410. }
  21411. } else {
  21412. var unicodeCharCode, notCidFont = (type.indexOf('CIDFontType') === -1);
  21413. this.toUnicode.forEach(function(charCode, unicodeCharCode) {
  21414. if (notCidFont) {
  21415. glyphName = (properties.differences[charCode] ||
  21416. properties.defaultEncoding[charCode]);
  21417. unicodeCharCode = (GlyphsUnicode[glyphName] || unicodeCharCode);
  21418. }
  21419. this.toFontChar[charCode] = unicodeCharCode;
  21420. }.bind(this));
  21421. }
  21422. this.loadedName = fontName.split('-')[0];
  21423. this.loading = false;
  21424. this.fontType = getFontType(type, subtype);
  21425. return;
  21426. }
  21427. // Some fonts might use wrong font types for Type1C or CIDFontType0C
  21428. if (subtype === 'Type1C' && (type !== 'Type1' && type !== 'MMType1')) {
  21429. // Some TrueType fonts by mistake claim Type1C
  21430. if (isTrueTypeFile(file)) {
  21431. subtype = 'TrueType';
  21432. } else {
  21433. type = 'Type1';
  21434. }
  21435. }
  21436. if (subtype === 'CIDFontType0C' && type !== 'CIDFontType0') {
  21437. type = 'CIDFontType0';
  21438. }
  21439. if (subtype === 'OpenType') {
  21440. type = 'OpenType';
  21441. }
  21442. // Some CIDFontType0C fonts by mistake claim CIDFontType0.
  21443. if (type === 'CIDFontType0') {
  21444. subtype = isType1File(file) ? 'CIDFontType0' : 'CIDFontType0C';
  21445. }
  21446. var data;
  21447. switch (type) {
  21448. case 'MMType1':
  21449. info('MMType1 font (' + name + '), falling back to Type1.');
  21450. /* falls through */
  21451. case 'Type1':
  21452. case 'CIDFontType0':
  21453. this.mimetype = 'font/opentype';
  21454. var cff = (subtype === 'Type1C' || subtype === 'CIDFontType0C') ?
  21455. new CFFFont(file, properties) : new Type1Font(name, file, properties);
  21456. adjustWidths(properties);
  21457. // Wrap the CFF data inside an OTF font file
  21458. data = this.convert(name, cff, properties);
  21459. break;
  21460. case 'OpenType':
  21461. case 'TrueType':
  21462. case 'CIDFontType2':
  21463. this.mimetype = 'font/opentype';
  21464. // Repair the TrueType file. It is can be damaged in the point of
  21465. // view of the sanitizer
  21466. data = this.checkAndRepair(name, file, properties);
  21467. if (this.isOpenType) {
  21468. type = 'OpenType';
  21469. }
  21470. break;
  21471. default:
  21472. error('Font ' + type + ' is not supported');
  21473. break;
  21474. }
  21475. this.data = data;
  21476. this.fontType = getFontType(type, subtype);
  21477. // Transfer some properties again that could change during font conversion
  21478. this.fontMatrix = properties.fontMatrix;
  21479. this.widths = properties.widths;
  21480. this.defaultWidth = properties.defaultWidth;
  21481. this.encoding = properties.baseEncoding;
  21482. this.seacMap = properties.seacMap;
  21483. this.loading = true;
  21484. }
  21485. Font.getFontID = (function () {
  21486. var ID = 1;
  21487. return function Font_getFontID() {
  21488. return String(ID++);
  21489. };
  21490. })();
  21491. function int16(b0, b1) {
  21492. return (b0 << 8) + b1;
  21493. }
  21494. function int32(b0, b1, b2, b3) {
  21495. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  21496. }
  21497. function string16(value) {
  21498. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  21499. }
  21500. function safeString16(value) {
  21501. // clamp value to the 16-bit int range
  21502. value = (value > 0x7FFF ? 0x7FFF : (value < -0x8000 ? -0x8000 : value));
  21503. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  21504. }
  21505. function isTrueTypeFile(file) {
  21506. var header = file.peekBytes(4);
  21507. return readUint32(header, 0) === 0x00010000;
  21508. }
  21509. function isType1File(file) {
  21510. var header = file.peekBytes(2);
  21511. // All Type1 font programs must begin with the comment '%!' (0x25 + 0x21).
  21512. if (header[0] === 0x25 && header[1] === 0x21) {
  21513. return true;
  21514. }
  21515. // ... obviously some fonts violate that part of the specification,
  21516. // please refer to the comment in |Type1Font| below.
  21517. if (header[0] === 0x80 && header[1] === 0x01) { // pfb file header.
  21518. return true;
  21519. }
  21520. return false;
  21521. }
  21522. /**
  21523. * Helper function for |adjustMapping|.
  21524. * @return {boolean}
  21525. */
  21526. function isProblematicUnicodeLocation(code) {
  21527. // Using binary search to find a range start.
  21528. var i = 0, j = ProblematicCharRanges.length - 1;
  21529. while (i < j) {
  21530. var c = (i + j + 1) >> 1;
  21531. if (code < ProblematicCharRanges[c]) {
  21532. j = c - 1;
  21533. } else {
  21534. i = c;
  21535. }
  21536. }
  21537. // Even index means code in problematic range.
  21538. return !(i & 1);
  21539. }
  21540. /**
  21541. * Rebuilds the char code to glyph ID map by trying to replace the char codes
  21542. * with their unicode value. It also moves char codes that are in known
  21543. * problematic locations.
  21544. * @return {Object} Two properties:
  21545. * 'toFontChar' - maps original char codes(the value that will be read
  21546. * from commands such as show text) to the char codes that will be used in the
  21547. * font that we build
  21548. * 'charCodeToGlyphId' - maps the new font char codes to glyph ids
  21549. */
  21550. function adjustMapping(charCodeToGlyphId, properties) {
  21551. var toUnicode = properties.toUnicode;
  21552. var isSymbolic = !!(properties.flags & FontFlags.Symbolic);
  21553. var isIdentityUnicode =
  21554. properties.toUnicode instanceof IdentityToUnicodeMap;
  21555. var newMap = Object.create(null);
  21556. var toFontChar = [];
  21557. var usedFontCharCodes = [];
  21558. var nextAvailableFontCharCode = PRIVATE_USE_OFFSET_START;
  21559. for (var originalCharCode in charCodeToGlyphId) {
  21560. originalCharCode |= 0;
  21561. var glyphId = charCodeToGlyphId[originalCharCode];
  21562. var fontCharCode = originalCharCode;
  21563. // First try to map the value to a unicode position if a non identity map
  21564. // was created.
  21565. if (!isIdentityUnicode && toUnicode.has(originalCharCode)) {
  21566. var unicode = toUnicode.get(fontCharCode);
  21567. // TODO: Try to map ligatures to the correct spot.
  21568. if (unicode.length === 1) {
  21569. fontCharCode = unicode.charCodeAt(0);
  21570. }
  21571. }
  21572. // Try to move control characters, special characters and already mapped
  21573. // characters to the private use area since they will not be drawn by
  21574. // canvas if left in their current position. Also, move characters if the
  21575. // font was symbolic and there is only an identity unicode map since the
  21576. // characters probably aren't in the correct position (fixes an issue
  21577. // with firefox and thuluthfont).
  21578. if ((usedFontCharCodes[fontCharCode] !== undefined ||
  21579. isProblematicUnicodeLocation(fontCharCode) ||
  21580. (isSymbolic && isIdentityUnicode)) &&
  21581. nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END) { // Room left.
  21582. // Loop to try and find a free spot in the private use area.
  21583. do {
  21584. fontCharCode = nextAvailableFontCharCode++;
  21585. if (SKIP_PRIVATE_USE_RANGE_F000_TO_F01F && fontCharCode === 0xF000) {
  21586. fontCharCode = 0xF020;
  21587. nextAvailableFontCharCode = fontCharCode + 1;
  21588. }
  21589. } while (usedFontCharCodes[fontCharCode] !== undefined &&
  21590. nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END);
  21591. }
  21592. newMap[fontCharCode] = glyphId;
  21593. toFontChar[originalCharCode] = fontCharCode;
  21594. usedFontCharCodes[fontCharCode] = true;
  21595. }
  21596. return {
  21597. toFontChar: toFontChar,
  21598. charCodeToGlyphId: newMap,
  21599. nextAvailableFontCharCode: nextAvailableFontCharCode
  21600. };
  21601. }
  21602. function getRanges(glyphs) {
  21603. // Array.sort() sorts by characters, not numerically, so convert to an
  21604. // array of characters.
  21605. var codes = [];
  21606. for (var charCode in glyphs) {
  21607. codes.push({ fontCharCode: charCode | 0, glyphId: glyphs[charCode] });
  21608. }
  21609. codes.sort(function fontGetRangesSort(a, b) {
  21610. return a.fontCharCode - b.fontCharCode;
  21611. });
  21612. // Split the sorted codes into ranges.
  21613. var ranges = [];
  21614. var length = codes.length;
  21615. for (var n = 0; n < length; ) {
  21616. var start = codes[n].fontCharCode;
  21617. var codeIndices = [codes[n].glyphId];
  21618. ++n;
  21619. var end = start;
  21620. while (n < length && end + 1 === codes[n].fontCharCode) {
  21621. codeIndices.push(codes[n].glyphId);
  21622. ++end;
  21623. ++n;
  21624. if (end === 0xFFFF) {
  21625. break;
  21626. }
  21627. }
  21628. ranges.push([start, end, codeIndices]);
  21629. }
  21630. return ranges;
  21631. }
  21632. function createCmapTable(glyphs) {
  21633. var ranges = getRanges(glyphs);
  21634. var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1;
  21635. var cmap = '\x00\x00' + // version
  21636. string16(numTables) + // numTables
  21637. '\x00\x03' + // platformID
  21638. '\x00\x01' + // encodingID
  21639. string32(4 + numTables * 8); // start of the table record
  21640. var i, ii, j, jj;
  21641. for (i = ranges.length - 1; i >= 0; --i) {
  21642. if (ranges[i][0] <= 0xFFFF) { break; }
  21643. }
  21644. var bmpLength = i + 1;
  21645. if (ranges[i][0] < 0xFFFF && ranges[i][1] === 0xFFFF) {
  21646. ranges[i][1] = 0xFFFE;
  21647. }
  21648. var trailingRangesCount = ranges[i][1] < 0xFFFF ? 1 : 0;
  21649. var segCount = bmpLength + trailingRangesCount;
  21650. var searchParams = OpenTypeFileBuilder.getSearchParams(segCount, 2);
  21651. // Fill up the 4 parallel arrays describing the segments.
  21652. var startCount = '';
  21653. var endCount = '';
  21654. var idDeltas = '';
  21655. var idRangeOffsets = '';
  21656. var glyphsIds = '';
  21657. var bias = 0;
  21658. var range, start, end, codes;
  21659. for (i = 0, ii = bmpLength; i < ii; i++) {
  21660. range = ranges[i];
  21661. start = range[0];
  21662. end = range[1];
  21663. startCount += string16(start);
  21664. endCount += string16(end);
  21665. codes = range[2];
  21666. var contiguous = true;
  21667. for (j = 1, jj = codes.length; j < jj; ++j) {
  21668. if (codes[j] !== codes[j - 1] + 1) {
  21669. contiguous = false;
  21670. break;
  21671. }
  21672. }
  21673. if (!contiguous) {
  21674. var offset = (segCount - i) * 2 + bias * 2;
  21675. bias += (end - start + 1);
  21676. idDeltas += string16(0);
  21677. idRangeOffsets += string16(offset);
  21678. for (j = 0, jj = codes.length; j < jj; ++j) {
  21679. glyphsIds += string16(codes[j]);
  21680. }
  21681. } else {
  21682. var startCode = codes[0];
  21683. idDeltas += string16((startCode - start) & 0xFFFF);
  21684. idRangeOffsets += string16(0);
  21685. }
  21686. }
  21687. if (trailingRangesCount > 0) {
  21688. endCount += '\xFF\xFF';
  21689. startCount += '\xFF\xFF';
  21690. idDeltas += '\x00\x01';
  21691. idRangeOffsets += '\x00\x00';
  21692. }
  21693. var format314 = '\x00\x00' + // language
  21694. string16(2 * segCount) +
  21695. string16(searchParams.range) +
  21696. string16(searchParams.entry) +
  21697. string16(searchParams.rangeShift) +
  21698. endCount + '\x00\x00' + startCount +
  21699. idDeltas + idRangeOffsets + glyphsIds;
  21700. var format31012 = '';
  21701. var header31012 = '';
  21702. if (numTables > 1) {
  21703. cmap += '\x00\x03' + // platformID
  21704. '\x00\x0A' + // encodingID
  21705. string32(4 + numTables * 8 +
  21706. 4 + format314.length); // start of the table record
  21707. format31012 = '';
  21708. for (i = 0, ii = ranges.length; i < ii; i++) {
  21709. range = ranges[i];
  21710. start = range[0];
  21711. codes = range[2];
  21712. var code = codes[0];
  21713. for (j = 1, jj = codes.length; j < jj; ++j) {
  21714. if (codes[j] !== codes[j - 1] + 1) {
  21715. end = range[0] + j - 1;
  21716. format31012 += string32(start) + // startCharCode
  21717. string32(end) + // endCharCode
  21718. string32(code); // startGlyphID
  21719. start = end + 1;
  21720. code = codes[j];
  21721. }
  21722. }
  21723. format31012 += string32(start) + // startCharCode
  21724. string32(range[1]) + // endCharCode
  21725. string32(code); // startGlyphID
  21726. }
  21727. header31012 = '\x00\x0C' + // format
  21728. '\x00\x00' + // reserved
  21729. string32(format31012.length + 16) + // length
  21730. '\x00\x00\x00\x00' + // language
  21731. string32(format31012.length / 12); // nGroups
  21732. }
  21733. return cmap + '\x00\x04' + // format
  21734. string16(format314.length + 4) + // length
  21735. format314 + header31012 + format31012;
  21736. }
  21737. function validateOS2Table(os2) {
  21738. var stream = new Stream(os2.data);
  21739. var version = stream.getUint16();
  21740. // TODO verify all OS/2 tables fields, but currently we validate only those
  21741. // that give us issues
  21742. stream.getBytes(60); // skipping type, misc sizes, panose, unicode ranges
  21743. var selection = stream.getUint16();
  21744. if (version < 4 && (selection & 0x0300)) {
  21745. return false;
  21746. }
  21747. var firstChar = stream.getUint16();
  21748. var lastChar = stream.getUint16();
  21749. if (firstChar > lastChar) {
  21750. return false;
  21751. }
  21752. stream.getBytes(6); // skipping sTypoAscender/Descender/LineGap
  21753. var usWinAscent = stream.getUint16();
  21754. if (usWinAscent === 0) { // makes font unreadable by windows
  21755. return false;
  21756. }
  21757. // OS/2 appears to be valid, resetting some fields
  21758. os2.data[8] = os2.data[9] = 0; // IE rejects fonts if fsType != 0
  21759. return true;
  21760. }
  21761. function createOS2Table(properties, charstrings, override) {
  21762. override = override || {
  21763. unitsPerEm: 0,
  21764. yMax: 0,
  21765. yMin: 0,
  21766. ascent: 0,
  21767. descent: 0
  21768. };
  21769. var ulUnicodeRange1 = 0;
  21770. var ulUnicodeRange2 = 0;
  21771. var ulUnicodeRange3 = 0;
  21772. var ulUnicodeRange4 = 0;
  21773. var firstCharIndex = null;
  21774. var lastCharIndex = 0;
  21775. if (charstrings) {
  21776. for (var code in charstrings) {
  21777. code |= 0;
  21778. if (firstCharIndex > code || !firstCharIndex) {
  21779. firstCharIndex = code;
  21780. }
  21781. if (lastCharIndex < code) {
  21782. lastCharIndex = code;
  21783. }
  21784. var position = getUnicodeRangeFor(code);
  21785. if (position < 32) {
  21786. ulUnicodeRange1 |= 1 << position;
  21787. } else if (position < 64) {
  21788. ulUnicodeRange2 |= 1 << position - 32;
  21789. } else if (position < 96) {
  21790. ulUnicodeRange3 |= 1 << position - 64;
  21791. } else if (position < 123) {
  21792. ulUnicodeRange4 |= 1 << position - 96;
  21793. } else {
  21794. error('Unicode ranges Bits > 123 are reserved for internal usage');
  21795. }
  21796. }
  21797. } else {
  21798. // TODO
  21799. firstCharIndex = 0;
  21800. lastCharIndex = 255;
  21801. }
  21802. var bbox = properties.bbox || [0, 0, 0, 0];
  21803. var unitsPerEm = (override.unitsPerEm ||
  21804. 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0]);
  21805. // if the font units differ to the PDF glyph space units
  21806. // then scale up the values
  21807. var scale = (properties.ascentScaled ? 1.0 :
  21808. unitsPerEm / PDF_GLYPH_SPACE_UNITS);
  21809. var typoAscent = (override.ascent ||
  21810. Math.round(scale * (properties.ascent || bbox[3])));
  21811. var typoDescent = (override.descent ||
  21812. Math.round(scale * (properties.descent || bbox[1])));
  21813. if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
  21814. typoDescent = -typoDescent; // fixing incorrect descent
  21815. }
  21816. var winAscent = override.yMax || typoAscent;
  21817. var winDescent = -override.yMin || -typoDescent;
  21818. return '\x00\x03' + // version
  21819. '\x02\x24' + // xAvgCharWidth
  21820. '\x01\xF4' + // usWeightClass
  21821. '\x00\x05' + // usWidthClass
  21822. '\x00\x00' + // fstype (0 to let the font loads via font-face on IE)
  21823. '\x02\x8A' + // ySubscriptXSize
  21824. '\x02\xBB' + // ySubscriptYSize
  21825. '\x00\x00' + // ySubscriptXOffset
  21826. '\x00\x8C' + // ySubscriptYOffset
  21827. '\x02\x8A' + // ySuperScriptXSize
  21828. '\x02\xBB' + // ySuperScriptYSize
  21829. '\x00\x00' + // ySuperScriptXOffset
  21830. '\x01\xDF' + // ySuperScriptYOffset
  21831. '\x00\x31' + // yStrikeOutSize
  21832. '\x01\x02' + // yStrikeOutPosition
  21833. '\x00\x00' + // sFamilyClass
  21834. '\x00\x00\x06' +
  21835. String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) +
  21836. '\x00\x00\x00\x00\x00\x00' + // Panose
  21837. string32(ulUnicodeRange1) + // ulUnicodeRange1 (Bits 0-31)
  21838. string32(ulUnicodeRange2) + // ulUnicodeRange2 (Bits 32-63)
  21839. string32(ulUnicodeRange3) + // ulUnicodeRange3 (Bits 64-95)
  21840. string32(ulUnicodeRange4) + // ulUnicodeRange4 (Bits 96-127)
  21841. '\x2A\x32\x31\x2A' + // achVendID
  21842. string16(properties.italicAngle ? 1 : 0) + // fsSelection
  21843. string16(firstCharIndex ||
  21844. properties.firstChar) + // usFirstCharIndex
  21845. string16(lastCharIndex || properties.lastChar) + // usLastCharIndex
  21846. string16(typoAscent) + // sTypoAscender
  21847. string16(typoDescent) + // sTypoDescender
  21848. '\x00\x64' + // sTypoLineGap (7%-10% of the unitsPerEM value)
  21849. string16(winAscent) + // usWinAscent
  21850. string16(winDescent) + // usWinDescent
  21851. '\x00\x00\x00\x00' + // ulCodePageRange1 (Bits 0-31)
  21852. '\x00\x00\x00\x00' + // ulCodePageRange2 (Bits 32-63)
  21853. string16(properties.xHeight) + // sxHeight
  21854. string16(properties.capHeight) + // sCapHeight
  21855. string16(0) + // usDefaultChar
  21856. string16(firstCharIndex || properties.firstChar) + // usBreakChar
  21857. '\x00\x03'; // usMaxContext
  21858. }
  21859. function createPostTable(properties) {
  21860. var angle = Math.floor(properties.italicAngle * (Math.pow(2, 16)));
  21861. return ('\x00\x03\x00\x00' + // Version number
  21862. string32(angle) + // italicAngle
  21863. '\x00\x00' + // underlinePosition
  21864. '\x00\x00' + // underlineThickness
  21865. string32(properties.fixedPitch) + // isFixedPitch
  21866. '\x00\x00\x00\x00' + // minMemType42
  21867. '\x00\x00\x00\x00' + // maxMemType42
  21868. '\x00\x00\x00\x00' + // minMemType1
  21869. '\x00\x00\x00\x00'); // maxMemType1
  21870. }
  21871. function createNameTable(name, proto) {
  21872. if (!proto) {
  21873. proto = [[], []]; // no strings and unicode strings
  21874. }
  21875. var strings = [
  21876. proto[0][0] || 'Original licence', // 0.Copyright
  21877. proto[0][1] || name, // 1.Font family
  21878. proto[0][2] || 'Unknown', // 2.Font subfamily (font weight)
  21879. proto[0][3] || 'uniqueID', // 3.Unique ID
  21880. proto[0][4] || name, // 4.Full font name
  21881. proto[0][5] || 'Version 0.11', // 5.Version
  21882. proto[0][6] || '', // 6.Postscript name
  21883. proto[0][7] || 'Unknown', // 7.Trademark
  21884. proto[0][8] || 'Unknown', // 8.Manufacturer
  21885. proto[0][9] || 'Unknown' // 9.Designer
  21886. ];
  21887. // Mac want 1-byte per character strings while Windows want
  21888. // 2-bytes per character, so duplicate the names table
  21889. var stringsUnicode = [];
  21890. var i, ii, j, jj, str;
  21891. for (i = 0, ii = strings.length; i < ii; i++) {
  21892. str = proto[1][i] || strings[i];
  21893. var strBufUnicode = [];
  21894. for (j = 0, jj = str.length; j < jj; j++) {
  21895. strBufUnicode.push(string16(str.charCodeAt(j)));
  21896. }
  21897. stringsUnicode.push(strBufUnicode.join(''));
  21898. }
  21899. var names = [strings, stringsUnicode];
  21900. var platforms = ['\x00\x01', '\x00\x03'];
  21901. var encodings = ['\x00\x00', '\x00\x01'];
  21902. var languages = ['\x00\x00', '\x04\x09'];
  21903. var namesRecordCount = strings.length * platforms.length;
  21904. var nameTable =
  21905. '\x00\x00' + // format
  21906. string16(namesRecordCount) + // Number of names Record
  21907. string16(namesRecordCount * 12 + 6); // Storage
  21908. // Build the name records field
  21909. var strOffset = 0;
  21910. for (i = 0, ii = platforms.length; i < ii; i++) {
  21911. var strs = names[i];
  21912. for (j = 0, jj = strs.length; j < jj; j++) {
  21913. str = strs[j];
  21914. var nameRecord =
  21915. platforms[i] + // platform ID
  21916. encodings[i] + // encoding ID
  21917. languages[i] + // language ID
  21918. string16(j) + // name ID
  21919. string16(str.length) +
  21920. string16(strOffset);
  21921. nameTable += nameRecord;
  21922. strOffset += str.length;
  21923. }
  21924. }
  21925. nameTable += strings.join('') + stringsUnicode.join('');
  21926. return nameTable;
  21927. }
  21928. Font.prototype = {
  21929. name: null,
  21930. font: null,
  21931. mimetype: null,
  21932. encoding: null,
  21933. get renderer() {
  21934. var renderer = FontRendererFactory.create(this);
  21935. return shadow(this, 'renderer', renderer);
  21936. },
  21937. exportData: function Font_exportData() {
  21938. var data = {};
  21939. for (var i in this) {
  21940. if (this.hasOwnProperty(i)) {
  21941. data[i] = this[i];
  21942. }
  21943. }
  21944. return data;
  21945. },
  21946. checkAndRepair: function Font_checkAndRepair(name, font, properties) {
  21947. function readTableEntry(file) {
  21948. var tag = bytesToString(file.getBytes(4));
  21949. var checksum = file.getInt32();
  21950. var offset = file.getInt32() >>> 0;
  21951. var length = file.getInt32() >>> 0;
  21952. // Read the table associated data
  21953. var previousPosition = file.pos;
  21954. file.pos = file.start ? file.start : 0;
  21955. file.skip(offset);
  21956. var data = file.getBytes(length);
  21957. file.pos = previousPosition;
  21958. if (tag === 'head') {
  21959. // clearing checksum adjustment
  21960. data[8] = data[9] = data[10] = data[11] = 0;
  21961. data[17] |= 0x20; //Set font optimized for cleartype flag
  21962. }
  21963. return {
  21964. tag: tag,
  21965. checksum: checksum,
  21966. length: length,
  21967. offset: offset,
  21968. data: data
  21969. };
  21970. }
  21971. function readOpenTypeHeader(ttf) {
  21972. return {
  21973. version: bytesToString(ttf.getBytes(4)),
  21974. numTables: ttf.getUint16(),
  21975. searchRange: ttf.getUint16(),
  21976. entrySelector: ttf.getUint16(),
  21977. rangeShift: ttf.getUint16()
  21978. };
  21979. }
  21980. /**
  21981. * Read the appropriate subtable from the cmap according to 9.6.6.4 from
  21982. * PDF spec
  21983. */
  21984. function readCmapTable(cmap, font, isSymbolicFont, hasEncoding) {
  21985. var segment;
  21986. var start = (font.start ? font.start : 0) + cmap.offset;
  21987. font.pos = start;
  21988. var version = font.getUint16();
  21989. var numTables = font.getUint16();
  21990. var potentialTable;
  21991. var canBreak = false;
  21992. // There's an order of preference in terms of which cmap subtable to
  21993. // use:
  21994. // - non-symbolic fonts the preference is a 3,1 table then a 1,0 table
  21995. // - symbolic fonts the preference is a 3,0 table then a 1,0 table
  21996. // The following takes advantage of the fact that the tables are sorted
  21997. // to work.
  21998. for (var i = 0; i < numTables; i++) {
  21999. var platformId = font.getUint16();
  22000. var encodingId = font.getUint16();
  22001. var offset = font.getInt32() >>> 0;
  22002. var useTable = false;
  22003. if (platformId === 0 && encodingId === 0) {
  22004. useTable = true;
  22005. // Continue the loop since there still may be a higher priority
  22006. // table.
  22007. } else if (platformId === 1 && encodingId === 0) {
  22008. useTable = true;
  22009. // Continue the loop since there still may be a higher priority
  22010. // table.
  22011. } else if (platformId === 3 && encodingId === 1 &&
  22012. ((!isSymbolicFont && hasEncoding) || !potentialTable)) {
  22013. useTable = true;
  22014. if (!isSymbolicFont) {
  22015. canBreak = true;
  22016. }
  22017. } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
  22018. useTable = true;
  22019. canBreak = true;
  22020. }
  22021. if (useTable) {
  22022. potentialTable = {
  22023. platformId: platformId,
  22024. encodingId: encodingId,
  22025. offset: offset
  22026. };
  22027. }
  22028. if (canBreak) {
  22029. break;
  22030. }
  22031. }
  22032. if (potentialTable) {
  22033. font.pos = start + potentialTable.offset;
  22034. }
  22035. if (!potentialTable || font.peekByte() === -1) {
  22036. warn('Could not find a preferred cmap table.');
  22037. return {
  22038. platformId: -1,
  22039. encodingId: -1,
  22040. mappings: [],
  22041. hasShortCmap: false
  22042. };
  22043. }
  22044. var format = font.getUint16();
  22045. var length = font.getUint16();
  22046. var language = font.getUint16();
  22047. var hasShortCmap = false;
  22048. var mappings = [];
  22049. var j, glyphId;
  22050. // TODO(mack): refactor this cmap subtable reading logic out
  22051. if (format === 0) {
  22052. for (j = 0; j < 256; j++) {
  22053. var index = font.getByte();
  22054. if (!index) {
  22055. continue;
  22056. }
  22057. mappings.push({
  22058. charCode: j,
  22059. glyphId: index
  22060. });
  22061. }
  22062. hasShortCmap = true;
  22063. } else if (format === 4) {
  22064. // re-creating the table in format 4 since the encoding
  22065. // might be changed
  22066. var segCount = (font.getUint16() >> 1);
  22067. font.getBytes(6); // skipping range fields
  22068. var segIndex, segments = [];
  22069. for (segIndex = 0; segIndex < segCount; segIndex++) {
  22070. segments.push({ end: font.getUint16() });
  22071. }
  22072. font.getUint16();
  22073. for (segIndex = 0; segIndex < segCount; segIndex++) {
  22074. segments[segIndex].start = font.getUint16();
  22075. }
  22076. for (segIndex = 0; segIndex < segCount; segIndex++) {
  22077. segments[segIndex].delta = font.getUint16();
  22078. }
  22079. var offsetsCount = 0;
  22080. for (segIndex = 0; segIndex < segCount; segIndex++) {
  22081. segment = segments[segIndex];
  22082. var rangeOffset = font.getUint16();
  22083. if (!rangeOffset) {
  22084. segment.offsetIndex = -1;
  22085. continue;
  22086. }
  22087. var offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
  22088. segment.offsetIndex = offsetIndex;
  22089. offsetsCount = Math.max(offsetsCount, offsetIndex +
  22090. segment.end - segment.start + 1);
  22091. }
  22092. var offsets = [];
  22093. for (j = 0; j < offsetsCount; j++) {
  22094. offsets.push(font.getUint16());
  22095. }
  22096. for (segIndex = 0; segIndex < segCount; segIndex++) {
  22097. segment = segments[segIndex];
  22098. start = segment.start;
  22099. var end = segment.end;
  22100. var delta = segment.delta;
  22101. offsetIndex = segment.offsetIndex;
  22102. for (j = start; j <= end; j++) {
  22103. if (j === 0xFFFF) {
  22104. continue;
  22105. }
  22106. glyphId = (offsetIndex < 0 ?
  22107. j : offsets[offsetIndex + j - start]);
  22108. glyphId = (glyphId + delta) & 0xFFFF;
  22109. if (glyphId === 0) {
  22110. continue;
  22111. }
  22112. mappings.push({
  22113. charCode: j,
  22114. glyphId: glyphId
  22115. });
  22116. }
  22117. }
  22118. } else if (format === 6) {
  22119. // Format 6 is a 2-bytes dense mapping, which means the font data
  22120. // lives glue together even if they are pretty far in the unicode
  22121. // table. (This looks weird, so I can have missed something), this
  22122. // works on Linux but seems to fails on Mac so let's rewrite the
  22123. // cmap table to a 3-1-4 style
  22124. var firstCode = font.getUint16();
  22125. var entryCount = font.getUint16();
  22126. for (j = 0; j < entryCount; j++) {
  22127. glyphId = font.getUint16();
  22128. var charCode = firstCode + j;
  22129. mappings.push({
  22130. charCode: charCode,
  22131. glyphId: glyphId
  22132. });
  22133. }
  22134. } else {
  22135. warn('cmap table has unsupported format: ' + format);
  22136. return {
  22137. platformId: -1,
  22138. encodingId: -1,
  22139. mappings: [],
  22140. hasShortCmap: false
  22141. };
  22142. }
  22143. // removing duplicate entries
  22144. mappings.sort(function (a, b) {
  22145. return a.charCode - b.charCode;
  22146. });
  22147. for (i = 1; i < mappings.length; i++) {
  22148. if (mappings[i - 1].charCode === mappings[i].charCode) {
  22149. mappings.splice(i, 1);
  22150. i--;
  22151. }
  22152. }
  22153. return {
  22154. platformId: potentialTable.platformId,
  22155. encodingId: potentialTable.encodingId,
  22156. mappings: mappings,
  22157. hasShortCmap: hasShortCmap
  22158. };
  22159. }
  22160. function sanitizeMetrics(font, header, metrics, numGlyphs) {
  22161. if (!header) {
  22162. if (metrics) {
  22163. metrics.data = null;
  22164. }
  22165. return;
  22166. }
  22167. font.pos = (font.start ? font.start : 0) + header.offset;
  22168. font.pos += header.length - 2;
  22169. var numOfMetrics = font.getUint16();
  22170. if (numOfMetrics > numGlyphs) {
  22171. info('The numOfMetrics (' + numOfMetrics + ') should not be ' +
  22172. 'greater than the numGlyphs (' + numGlyphs + ')');
  22173. // Reduce numOfMetrics if it is greater than numGlyphs
  22174. numOfMetrics = numGlyphs;
  22175. header.data[34] = (numOfMetrics & 0xff00) >> 8;
  22176. header.data[35] = numOfMetrics & 0x00ff;
  22177. }
  22178. var numOfSidebearings = numGlyphs - numOfMetrics;
  22179. var numMissing = numOfSidebearings -
  22180. ((metrics.length - numOfMetrics * 4) >> 1);
  22181. if (numMissing > 0) {
  22182. // For each missing glyph, we set both the width and lsb to 0 (zero).
  22183. // Since we need to add two properties for each glyph, this explains
  22184. // the use of |numMissing * 2| when initializing the typed array.
  22185. var entries = new Uint8Array(metrics.length + numMissing * 2);
  22186. entries.set(metrics.data);
  22187. metrics.data = entries;
  22188. }
  22189. }
  22190. function sanitizeGlyph(source, sourceStart, sourceEnd, dest, destStart,
  22191. hintsValid) {
  22192. if (sourceEnd - sourceStart <= 12) {
  22193. // glyph with data less than 12 is invalid one
  22194. return 0;
  22195. }
  22196. var glyf = source.subarray(sourceStart, sourceEnd);
  22197. var contoursCount = (glyf[0] << 8) | glyf[1];
  22198. if (contoursCount & 0x8000) {
  22199. // complex glyph, writing as is
  22200. dest.set(glyf, destStart);
  22201. return glyf.length;
  22202. }
  22203. var i, j = 10, flagsCount = 0;
  22204. for (i = 0; i < contoursCount; i++) {
  22205. var endPoint = (glyf[j] << 8) | glyf[j + 1];
  22206. flagsCount = endPoint + 1;
  22207. j += 2;
  22208. }
  22209. // skipping instructions
  22210. var instructionsStart = j;
  22211. var instructionsLength = (glyf[j] << 8) | glyf[j + 1];
  22212. j += 2 + instructionsLength;
  22213. var instructionsEnd = j;
  22214. // validating flags
  22215. var coordinatesLength = 0;
  22216. for (i = 0; i < flagsCount; i++) {
  22217. var flag = glyf[j++];
  22218. if (flag & 0xC0) {
  22219. // reserved flags must be zero, cleaning up
  22220. glyf[j - 1] = flag & 0x3F;
  22221. }
  22222. var xyLength = ((flag & 2) ? 1 : (flag & 16) ? 0 : 2) +
  22223. ((flag & 4) ? 1 : (flag & 32) ? 0 : 2);
  22224. coordinatesLength += xyLength;
  22225. if (flag & 8) {
  22226. var repeat = glyf[j++];
  22227. i += repeat;
  22228. coordinatesLength += repeat * xyLength;
  22229. }
  22230. }
  22231. // glyph without coordinates will be rejected
  22232. if (coordinatesLength === 0) {
  22233. return 0;
  22234. }
  22235. var glyphDataLength = j + coordinatesLength;
  22236. if (glyphDataLength > glyf.length) {
  22237. // not enough data for coordinates
  22238. return 0;
  22239. }
  22240. if (!hintsValid && instructionsLength > 0) {
  22241. dest.set(glyf.subarray(0, instructionsStart), destStart);
  22242. dest.set([0, 0], destStart + instructionsStart);
  22243. dest.set(glyf.subarray(instructionsEnd, glyphDataLength),
  22244. destStart + instructionsStart + 2);
  22245. glyphDataLength -= instructionsLength;
  22246. if (glyf.length - glyphDataLength > 3) {
  22247. glyphDataLength = (glyphDataLength + 3) & ~3;
  22248. }
  22249. return glyphDataLength;
  22250. }
  22251. if (glyf.length - glyphDataLength > 3) {
  22252. // truncating and aligning to 4 bytes the long glyph data
  22253. glyphDataLength = (glyphDataLength + 3) & ~3;
  22254. dest.set(glyf.subarray(0, glyphDataLength), destStart);
  22255. return glyphDataLength;
  22256. }
  22257. // glyph data is fine
  22258. dest.set(glyf, destStart);
  22259. return glyf.length;
  22260. }
  22261. function sanitizeHead(head, numGlyphs, locaLength) {
  22262. var data = head.data;
  22263. // Validate version:
  22264. // Should always be 0x00010000
  22265. var version = int32(data[0], data[1], data[2], data[3]);
  22266. if (version >> 16 !== 1) {
  22267. info('Attempting to fix invalid version in head table: ' + version);
  22268. data[0] = 0;
  22269. data[1] = 1;
  22270. data[2] = 0;
  22271. data[3] = 0;
  22272. }
  22273. var indexToLocFormat = int16(data[50], data[51]);
  22274. if (indexToLocFormat < 0 || indexToLocFormat > 1) {
  22275. info('Attempting to fix invalid indexToLocFormat in head table: ' +
  22276. indexToLocFormat);
  22277. // The value of indexToLocFormat should be 0 if the loca table
  22278. // consists of short offsets, and should be 1 if the loca table
  22279. // consists of long offsets.
  22280. //
  22281. // The number of entries in the loca table should be numGlyphs + 1.
  22282. //
  22283. // Using this information, we can work backwards to deduce if the
  22284. // size of each offset in the loca table, and thus figure out the
  22285. // appropriate value for indexToLocFormat.
  22286. var numGlyphsPlusOne = numGlyphs + 1;
  22287. if (locaLength === numGlyphsPlusOne << 1) {
  22288. // 0x0000 indicates the loca table consists of short offsets
  22289. data[50] = 0;
  22290. data[51] = 0;
  22291. } else if (locaLength === numGlyphsPlusOne << 2) {
  22292. // 0x0001 indicates the loca table consists of long offsets
  22293. data[50] = 0;
  22294. data[51] = 1;
  22295. } else {
  22296. warn('Could not fix indexToLocFormat: ' + indexToLocFormat);
  22297. }
  22298. }
  22299. }
  22300. function sanitizeGlyphLocations(loca, glyf, numGlyphs,
  22301. isGlyphLocationsLong, hintsValid,
  22302. dupFirstEntry) {
  22303. var itemSize, itemDecode, itemEncode;
  22304. if (isGlyphLocationsLong) {
  22305. itemSize = 4;
  22306. itemDecode = function fontItemDecodeLong(data, offset) {
  22307. return (data[offset] << 24) | (data[offset + 1] << 16) |
  22308. (data[offset + 2] << 8) | data[offset + 3];
  22309. };
  22310. itemEncode = function fontItemEncodeLong(data, offset, value) {
  22311. data[offset] = (value >>> 24) & 0xFF;
  22312. data[offset + 1] = (value >> 16) & 0xFF;
  22313. data[offset + 2] = (value >> 8) & 0xFF;
  22314. data[offset + 3] = value & 0xFF;
  22315. };
  22316. } else {
  22317. itemSize = 2;
  22318. itemDecode = function fontItemDecode(data, offset) {
  22319. return (data[offset] << 9) | (data[offset + 1] << 1);
  22320. };
  22321. itemEncode = function fontItemEncode(data, offset, value) {
  22322. data[offset] = (value >> 9) & 0xFF;
  22323. data[offset + 1] = (value >> 1) & 0xFF;
  22324. };
  22325. }
  22326. var locaData = loca.data;
  22327. var locaDataSize = itemSize * (1 + numGlyphs);
  22328. // is loca.data too short or long?
  22329. if (locaData.length !== locaDataSize) {
  22330. locaData = new Uint8Array(locaDataSize);
  22331. locaData.set(loca.data.subarray(0, locaDataSize));
  22332. loca.data = locaData;
  22333. }
  22334. // removing the invalid glyphs
  22335. var oldGlyfData = glyf.data;
  22336. var oldGlyfDataLength = oldGlyfData.length;
  22337. var newGlyfData = new Uint8Array(oldGlyfDataLength);
  22338. var startOffset = itemDecode(locaData, 0);
  22339. var writeOffset = 0;
  22340. var missingGlyphData = {};
  22341. itemEncode(locaData, 0, writeOffset);
  22342. var i, j;
  22343. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  22344. var endOffset = itemDecode(locaData, j);
  22345. if (endOffset > oldGlyfDataLength &&
  22346. ((oldGlyfDataLength + 3) & ~3) === endOffset) {
  22347. // Aspose breaks fonts by aligning the glyphs to the qword, but not
  22348. // the glyf table size, which makes last glyph out of range.
  22349. endOffset = oldGlyfDataLength;
  22350. }
  22351. if (endOffset > oldGlyfDataLength) {
  22352. // glyph end offset points outside glyf data, rejecting the glyph
  22353. itemEncode(locaData, j, writeOffset);
  22354. startOffset = endOffset;
  22355. continue;
  22356. }
  22357. if (startOffset === endOffset) {
  22358. missingGlyphData[i] = true;
  22359. }
  22360. var newLength = sanitizeGlyph(oldGlyfData, startOffset, endOffset,
  22361. newGlyfData, writeOffset, hintsValid);
  22362. writeOffset += newLength;
  22363. itemEncode(locaData, j, writeOffset);
  22364. startOffset = endOffset;
  22365. }
  22366. if (writeOffset === 0) {
  22367. // glyf table cannot be empty -- redoing the glyf and loca tables
  22368. // to have single glyph with one point
  22369. var simpleGlyph = new Uint8Array(
  22370. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);
  22371. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  22372. itemEncode(locaData, j, simpleGlyph.length);
  22373. }
  22374. glyf.data = simpleGlyph;
  22375. return missingGlyphData;
  22376. }
  22377. if (dupFirstEntry) {
  22378. var firstEntryLength = itemDecode(locaData, itemSize);
  22379. if (newGlyfData.length > firstEntryLength + writeOffset) {
  22380. glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);
  22381. } else {
  22382. glyf.data = new Uint8Array(firstEntryLength + writeOffset);
  22383. glyf.data.set(newGlyfData.subarray(0, writeOffset));
  22384. }
  22385. glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);
  22386. itemEncode(loca.data, locaData.length - itemSize,
  22387. writeOffset + firstEntryLength);
  22388. } else {
  22389. glyf.data = newGlyfData.subarray(0, writeOffset);
  22390. }
  22391. return missingGlyphData;
  22392. }
  22393. function readPostScriptTable(post, properties, maxpNumGlyphs) {
  22394. var start = (font.start ? font.start : 0) + post.offset;
  22395. font.pos = start;
  22396. var length = post.length, end = start + length;
  22397. var version = font.getInt32();
  22398. // skip rest to the tables
  22399. font.getBytes(28);
  22400. var glyphNames;
  22401. var valid = true;
  22402. var i;
  22403. switch (version) {
  22404. case 0x00010000:
  22405. glyphNames = MacStandardGlyphOrdering;
  22406. break;
  22407. case 0x00020000:
  22408. var numGlyphs = font.getUint16();
  22409. if (numGlyphs !== maxpNumGlyphs) {
  22410. valid = false;
  22411. break;
  22412. }
  22413. var glyphNameIndexes = [];
  22414. for (i = 0; i < numGlyphs; ++i) {
  22415. var index = font.getUint16();
  22416. if (index >= 32768) {
  22417. valid = false;
  22418. break;
  22419. }
  22420. glyphNameIndexes.push(index);
  22421. }
  22422. if (!valid) {
  22423. break;
  22424. }
  22425. var customNames = [];
  22426. var strBuf = [];
  22427. while (font.pos < end) {
  22428. var stringLength = font.getByte();
  22429. strBuf.length = stringLength;
  22430. for (i = 0; i < stringLength; ++i) {
  22431. strBuf[i] = String.fromCharCode(font.getByte());
  22432. }
  22433. customNames.push(strBuf.join(''));
  22434. }
  22435. glyphNames = [];
  22436. for (i = 0; i < numGlyphs; ++i) {
  22437. var j = glyphNameIndexes[i];
  22438. if (j < 258) {
  22439. glyphNames.push(MacStandardGlyphOrdering[j]);
  22440. continue;
  22441. }
  22442. glyphNames.push(customNames[j - 258]);
  22443. }
  22444. break;
  22445. case 0x00030000:
  22446. break;
  22447. default:
  22448. warn('Unknown/unsupported post table version ' + version);
  22449. valid = false;
  22450. if (properties.defaultEncoding) {
  22451. glyphNames = properties.defaultEncoding;
  22452. }
  22453. break;
  22454. }
  22455. properties.glyphNames = glyphNames;
  22456. return valid;
  22457. }
  22458. function readNameTable(nameTable) {
  22459. var start = (font.start ? font.start : 0) + nameTable.offset;
  22460. font.pos = start;
  22461. var names = [[], []];
  22462. var length = nameTable.length, end = start + length;
  22463. var format = font.getUint16();
  22464. var FORMAT_0_HEADER_LENGTH = 6;
  22465. if (format !== 0 || length < FORMAT_0_HEADER_LENGTH) {
  22466. // unsupported name table format or table "too" small
  22467. return names;
  22468. }
  22469. var numRecords = font.getUint16();
  22470. var stringsStart = font.getUint16();
  22471. var records = [];
  22472. var NAME_RECORD_LENGTH = 12;
  22473. var i, ii;
  22474. for (i = 0; i < numRecords &&
  22475. font.pos + NAME_RECORD_LENGTH <= end; i++) {
  22476. var r = {
  22477. platform: font.getUint16(),
  22478. encoding: font.getUint16(),
  22479. language: font.getUint16(),
  22480. name: font.getUint16(),
  22481. length: font.getUint16(),
  22482. offset: font.getUint16()
  22483. };
  22484. // using only Macintosh and Windows platform/encoding names
  22485. if ((r.platform === 1 && r.encoding === 0 && r.language === 0) ||
  22486. (r.platform === 3 && r.encoding === 1 && r.language === 0x409)) {
  22487. records.push(r);
  22488. }
  22489. }
  22490. for (i = 0, ii = records.length; i < ii; i++) {
  22491. var record = records[i];
  22492. var pos = start + stringsStart + record.offset;
  22493. if (pos + record.length > end) {
  22494. continue; // outside of name table, ignoring
  22495. }
  22496. font.pos = pos;
  22497. var nameIndex = record.name;
  22498. if (record.encoding) {
  22499. // unicode
  22500. var str = '';
  22501. for (var j = 0, jj = record.length; j < jj; j += 2) {
  22502. str += String.fromCharCode(font.getUint16());
  22503. }
  22504. names[1][nameIndex] = str;
  22505. } else {
  22506. names[0][nameIndex] = bytesToString(font.getBytes(record.length));
  22507. }
  22508. }
  22509. return names;
  22510. }
  22511. var TTOpsStackDeltas = [
  22512. 0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, 0, 0, -2, -5,
  22513. -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, -1, -1,
  22514. 1, -1, -999, 0, 1, 0, -1, -2, 0, -1, -2, -1, -1, 0, -1, -1,
  22515. 0, 0, -999, -999, -1, -1, -1, -1, -2, -999, -2, -2, -999, 0, -2, -2,
  22516. 0, 0, -2, 0, -2, 0, 0, 0, -2, -1, -1, 1, 1, 0, 0, -1,
  22517. -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, -999, -1, -1,
  22518. -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22519. -2, -999, -999, -999, -999, -999, -1, -1, -2, -2, 0, 0, 0, 0, -1, -1,
  22520. -999, -2, -2, 0, 0, -1, -2, -2, 0, 0, 0, -1, -1, -1, -2];
  22521. // 0xC0-DF == -1 and 0xE0-FF == -2
  22522. function sanitizeTTProgram(table, ttContext) {
  22523. var data = table.data;
  22524. var i = 0, j, n, b, funcId, pc, lastEndf = 0, lastDeff = 0;
  22525. var stack = [];
  22526. var callstack = [];
  22527. var functionsCalled = [];
  22528. var tooComplexToFollowFunctions =
  22529. ttContext.tooComplexToFollowFunctions;
  22530. var inFDEF = false, ifLevel = 0, inELSE = 0;
  22531. for (var ii = data.length; i < ii;) {
  22532. var op = data[i++];
  22533. // The TrueType instruction set docs can be found at
  22534. // https://developer.apple.com/fonts/TTRefMan/RM05/Chap5.html
  22535. if (op === 0x40) { // NPUSHB - pushes n bytes
  22536. n = data[i++];
  22537. if (inFDEF || inELSE) {
  22538. i += n;
  22539. } else {
  22540. for (j = 0; j < n; j++) {
  22541. stack.push(data[i++]);
  22542. }
  22543. }
  22544. } else if (op === 0x41) { // NPUSHW - pushes n words
  22545. n = data[i++];
  22546. if (inFDEF || inELSE) {
  22547. i += n * 2;
  22548. } else {
  22549. for (j = 0; j < n; j++) {
  22550. b = data[i++];
  22551. stack.push((b << 8) | data[i++]);
  22552. }
  22553. }
  22554. } else if ((op & 0xF8) === 0xB0) { // PUSHB - pushes bytes
  22555. n = op - 0xB0 + 1;
  22556. if (inFDEF || inELSE) {
  22557. i += n;
  22558. } else {
  22559. for (j = 0; j < n; j++) {
  22560. stack.push(data[i++]);
  22561. }
  22562. }
  22563. } else if ((op & 0xF8) === 0xB8) { // PUSHW - pushes words
  22564. n = op - 0xB8 + 1;
  22565. if (inFDEF || inELSE) {
  22566. i += n * 2;
  22567. } else {
  22568. for (j = 0; j < n; j++) {
  22569. b = data[i++];
  22570. stack.push((b << 8) | data[i++]);
  22571. }
  22572. }
  22573. } else if (op === 0x2B && !tooComplexToFollowFunctions) { // CALL
  22574. if (!inFDEF && !inELSE) {
  22575. // collecting inforamtion about which functions are used
  22576. funcId = stack[stack.length - 1];
  22577. ttContext.functionsUsed[funcId] = true;
  22578. if (funcId in ttContext.functionsStackDeltas) {
  22579. stack.length += ttContext.functionsStackDeltas[funcId];
  22580. } else if (funcId in ttContext.functionsDefined &&
  22581. functionsCalled.indexOf(funcId) < 0) {
  22582. callstack.push({data: data, i: i, stackTop: stack.length - 1});
  22583. functionsCalled.push(funcId);
  22584. pc = ttContext.functionsDefined[funcId];
  22585. if (!pc) {
  22586. warn('TT: CALL non-existent function');
  22587. ttContext.hintsValid = false;
  22588. return;
  22589. }
  22590. data = pc.data;
  22591. i = pc.i;
  22592. }
  22593. }
  22594. } else if (op === 0x2C && !tooComplexToFollowFunctions) { // FDEF
  22595. if (inFDEF || inELSE) {
  22596. warn('TT: nested FDEFs not allowed');
  22597. tooComplexToFollowFunctions = true;
  22598. }
  22599. inFDEF = true;
  22600. // collecting inforamtion about which functions are defined
  22601. lastDeff = i;
  22602. funcId = stack.pop();
  22603. ttContext.functionsDefined[funcId] = {data: data, i: i};
  22604. } else if (op === 0x2D) { // ENDF - end of function
  22605. if (inFDEF) {
  22606. inFDEF = false;
  22607. lastEndf = i;
  22608. } else {
  22609. pc = callstack.pop();
  22610. if (!pc) {
  22611. warn('TT: ENDF bad stack');
  22612. ttContext.hintsValid = false;
  22613. return;
  22614. }
  22615. funcId = functionsCalled.pop();
  22616. data = pc.data;
  22617. i = pc.i;
  22618. ttContext.functionsStackDeltas[funcId] =
  22619. stack.length - pc.stackTop;
  22620. }
  22621. } else if (op === 0x89) { // IDEF - instruction definition
  22622. if (inFDEF || inELSE) {
  22623. warn('TT: nested IDEFs not allowed');
  22624. tooComplexToFollowFunctions = true;
  22625. }
  22626. inFDEF = true;
  22627. // recording it as a function to track ENDF
  22628. lastDeff = i;
  22629. } else if (op === 0x58) { // IF
  22630. ++ifLevel;
  22631. } else if (op === 0x1B) { // ELSE
  22632. inELSE = ifLevel;
  22633. } else if (op === 0x59) { // EIF
  22634. if (inELSE === ifLevel) {
  22635. inELSE = 0;
  22636. }
  22637. --ifLevel;
  22638. } else if (op === 0x1C) { // JMPR
  22639. if (!inFDEF && !inELSE) {
  22640. var offset = stack[stack.length - 1];
  22641. // only jumping forward to prevent infinite loop
  22642. if (offset > 0) {
  22643. i += offset - 1;
  22644. }
  22645. }
  22646. }
  22647. // Adjusting stack not extactly, but just enough to get function id
  22648. if (!inFDEF && !inELSE) {
  22649. var stackDelta = op <= 0x8E ? TTOpsStackDeltas[op] :
  22650. op >= 0xC0 && op <= 0xDF ? -1 : op >= 0xE0 ? -2 : 0;
  22651. if (op >= 0x71 && op <= 0x75) {
  22652. n = stack.pop();
  22653. if (n === n) {
  22654. stackDelta = -n * 2;
  22655. }
  22656. }
  22657. while (stackDelta < 0 && stack.length > 0) {
  22658. stack.pop();
  22659. stackDelta++;
  22660. }
  22661. while (stackDelta > 0) {
  22662. stack.push(NaN); // pushing any number into stack
  22663. stackDelta--;
  22664. }
  22665. }
  22666. }
  22667. ttContext.tooComplexToFollowFunctions = tooComplexToFollowFunctions;
  22668. var content = [data];
  22669. if (i > data.length) {
  22670. content.push(new Uint8Array(i - data.length));
  22671. }
  22672. if (lastDeff > lastEndf) {
  22673. warn('TT: complementing a missing function tail');
  22674. // new function definition started, but not finished
  22675. // complete function by [CLEAR, ENDF]
  22676. content.push(new Uint8Array([0x22, 0x2D]));
  22677. }
  22678. foldTTTable(table, content);
  22679. }
  22680. function checkInvalidFunctions(ttContext, maxFunctionDefs) {
  22681. if (ttContext.tooComplexToFollowFunctions) {
  22682. return;
  22683. }
  22684. if (ttContext.functionsDefined.length > maxFunctionDefs) {
  22685. warn('TT: more functions defined than expected');
  22686. ttContext.hintsValid = false;
  22687. return;
  22688. }
  22689. for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
  22690. if (j > maxFunctionDefs) {
  22691. warn('TT: invalid function id: ' + j);
  22692. ttContext.hintsValid = false;
  22693. return;
  22694. }
  22695. if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
  22696. warn('TT: undefined function: ' + j);
  22697. ttContext.hintsValid = false;
  22698. return;
  22699. }
  22700. }
  22701. }
  22702. function foldTTTable(table, content) {
  22703. if (content.length > 1) {
  22704. // concatenating the content items
  22705. var newLength = 0;
  22706. var j, jj;
  22707. for (j = 0, jj = content.length; j < jj; j++) {
  22708. newLength += content[j].length;
  22709. }
  22710. newLength = (newLength + 3) & ~3;
  22711. var result = new Uint8Array(newLength);
  22712. var pos = 0;
  22713. for (j = 0, jj = content.length; j < jj; j++) {
  22714. result.set(content[j], pos);
  22715. pos += content[j].length;
  22716. }
  22717. table.data = result;
  22718. table.length = newLength;
  22719. }
  22720. }
  22721. function sanitizeTTPrograms(fpgm, prep, cvt) {
  22722. var ttContext = {
  22723. functionsDefined: [],
  22724. functionsUsed: [],
  22725. functionsStackDeltas: [],
  22726. tooComplexToFollowFunctions: false,
  22727. hintsValid: true
  22728. };
  22729. if (fpgm) {
  22730. sanitizeTTProgram(fpgm, ttContext);
  22731. }
  22732. if (prep) {
  22733. sanitizeTTProgram(prep, ttContext);
  22734. }
  22735. if (fpgm) {
  22736. checkInvalidFunctions(ttContext, maxFunctionDefs);
  22737. }
  22738. if (cvt && (cvt.length & 1)) {
  22739. var cvtData = new Uint8Array(cvt.length + 1);
  22740. cvtData.set(cvt.data);
  22741. cvt.data = cvtData;
  22742. }
  22743. return ttContext.hintsValid;
  22744. }
  22745. // The following steps modify the original font data, making copy
  22746. font = new Stream(new Uint8Array(font.getBytes()));
  22747. var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp',
  22748. 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF '];
  22749. var header = readOpenTypeHeader(font);
  22750. var numTables = header.numTables;
  22751. var cff, cffFile;
  22752. var tables = { 'OS/2': null, cmap: null, head: null, hhea: null,
  22753. hmtx: null, maxp: null, name: null, post: null };
  22754. var table;
  22755. for (var i = 0; i < numTables; i++) {
  22756. table = readTableEntry(font);
  22757. if (VALID_TABLES.indexOf(table.tag) < 0) {
  22758. continue; // skipping table if it's not a required or optional table
  22759. }
  22760. if (table.length === 0) {
  22761. continue; // skipping empty tables
  22762. }
  22763. tables[table.tag] = table;
  22764. }
  22765. var isTrueType = !tables['CFF '];
  22766. if (!isTrueType) {
  22767. // OpenType font
  22768. if ((header.version === 'OTTO' && properties.type !== 'CIDFontType2') ||
  22769. !tables.head || !tables.hhea || !tables.maxp || !tables.post) {
  22770. // no major tables: throwing everything at CFFFont
  22771. cffFile = new Stream(tables['CFF '].data);
  22772. cff = new CFFFont(cffFile, properties);
  22773. return this.convert(name, cff, properties);
  22774. }
  22775. delete tables.glyf;
  22776. delete tables.loca;
  22777. delete tables.fpgm;
  22778. delete tables.prep;
  22779. delete tables['cvt '];
  22780. this.isOpenType = true;
  22781. } else {
  22782. if (!tables.glyf || !tables.loca) {
  22783. error('Required "glyf" or "loca" tables are not found');
  22784. }
  22785. this.isOpenType = false;
  22786. }
  22787. if (!tables.maxp) {
  22788. error('Required "maxp" table is not found');
  22789. }
  22790. font.pos = (font.start || 0) + tables.maxp.offset;
  22791. var version = font.getInt32();
  22792. var numGlyphs = font.getUint16();
  22793. var maxFunctionDefs = 0;
  22794. if (version >= 0x00010000 && tables.maxp.length >= 22) {
  22795. // maxZones can be invalid
  22796. font.pos += 8;
  22797. var maxZones = font.getUint16();
  22798. if (maxZones > 2) { // reset to 2 if font has invalid maxZones
  22799. tables.maxp.data[14] = 0;
  22800. tables.maxp.data[15] = 2;
  22801. }
  22802. font.pos += 4;
  22803. maxFunctionDefs = font.getUint16();
  22804. }
  22805. var dupFirstEntry = false;
  22806. if (properties.type === 'CIDFontType2' && properties.toUnicode &&
  22807. properties.toUnicode.get(0) > '\u0000') {
  22808. // oracle's defect (see 3427), duplicating first entry
  22809. dupFirstEntry = true;
  22810. numGlyphs++;
  22811. tables.maxp.data[4] = numGlyphs >> 8;
  22812. tables.maxp.data[5] = numGlyphs & 255;
  22813. }
  22814. var hintsValid = sanitizeTTPrograms(tables.fpgm, tables.prep,
  22815. tables['cvt '], maxFunctionDefs);
  22816. if (!hintsValid) {
  22817. delete tables.fpgm;
  22818. delete tables.prep;
  22819. delete tables['cvt '];
  22820. }
  22821. // Ensure the hmtx table contains the advance width and
  22822. // sidebearings information for numGlyphs in the maxp table
  22823. sanitizeMetrics(font, tables.hhea, tables.hmtx, numGlyphs);
  22824. if (!tables.head) {
  22825. error('Required "head" table is not found');
  22826. }
  22827. sanitizeHead(tables.head, numGlyphs, isTrueType ? tables.loca.length : 0);
  22828. var missingGlyphs = {};
  22829. if (isTrueType) {
  22830. var isGlyphLocationsLong = int16(tables.head.data[50],
  22831. tables.head.data[51]);
  22832. missingGlyphs = sanitizeGlyphLocations(tables.loca, tables.glyf,
  22833. numGlyphs, isGlyphLocationsLong,
  22834. hintsValid, dupFirstEntry);
  22835. }
  22836. if (!tables.hhea) {
  22837. error('Required "hhea" table is not found');
  22838. }
  22839. // Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth
  22840. // Sometimes it's 0. That needs to be fixed
  22841. if (tables.hhea.data[10] === 0 && tables.hhea.data[11] === 0) {
  22842. tables.hhea.data[10] = 0xFF;
  22843. tables.hhea.data[11] = 0xFF;
  22844. }
  22845. // The 'post' table has glyphs names.
  22846. if (tables.post) {
  22847. var valid = readPostScriptTable(tables.post, properties, numGlyphs);
  22848. if (!valid) {
  22849. tables.post = null;
  22850. }
  22851. }
  22852. var charCodeToGlyphId = [], charCode;
  22853. var toUnicode = properties.toUnicode, widths = properties.widths;
  22854. var skipToUnicode = (toUnicode instanceof IdentityToUnicodeMap ||
  22855. toUnicode.length === 0x10000);
  22856. // Helper function to try to skip mapping of empty glyphs.
  22857. // Note: In some cases, just relying on the glyph data doesn't work,
  22858. // hence we also use a few heuristics to fix various PDF files.
  22859. function hasGlyph(glyphId, charCode, widthCode) {
  22860. if (!missingGlyphs[glyphId]) {
  22861. return true;
  22862. }
  22863. if (!skipToUnicode && charCode >= 0 && toUnicode.has(charCode)) {
  22864. return true;
  22865. }
  22866. if (widths && widthCode >= 0 && isNum(widths[widthCode])) {
  22867. return true;
  22868. }
  22869. return false;
  22870. }
  22871. if (properties.type === 'CIDFontType2') {
  22872. var cidToGidMap = properties.cidToGidMap || [];
  22873. var isCidToGidMapEmpty = cidToGidMap.length === 0;
  22874. properties.cMap.forEach(function(charCode, cid) {
  22875. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  22876. var glyphId = -1;
  22877. if (isCidToGidMapEmpty) {
  22878. glyphId = charCode;
  22879. } else if (cidToGidMap[cid] !== undefined) {
  22880. glyphId = cidToGidMap[cid];
  22881. }
  22882. if (glyphId >= 0 && glyphId < numGlyphs &&
  22883. hasGlyph(glyphId, charCode, cid)) {
  22884. charCodeToGlyphId[charCode] = glyphId;
  22885. }
  22886. });
  22887. if (dupFirstEntry) {
  22888. charCodeToGlyphId[0] = numGlyphs - 1;
  22889. }
  22890. } else {
  22891. // Most of the following logic in this code branch is based on the
  22892. // 9.6.6.4 of the PDF spec.
  22893. var hasEncoding =
  22894. properties.differences.length > 0 || !!properties.baseEncodingName;
  22895. var cmapTable =
  22896. readCmapTable(tables.cmap, font, this.isSymbolicFont, hasEncoding);
  22897. var cmapPlatformId = cmapTable.platformId;
  22898. var cmapEncodingId = cmapTable.encodingId;
  22899. var cmapMappings = cmapTable.mappings;
  22900. var cmapMappingsLength = cmapMappings.length;
  22901. // The spec seems to imply that if the font is symbolic the encoding
  22902. // should be ignored, this doesn't appear to work for 'preistabelle.pdf'
  22903. // where the the font is symbolic and it has an encoding.
  22904. if (hasEncoding &&
  22905. (cmapPlatformId === 3 && cmapEncodingId === 1 ||
  22906. cmapPlatformId === 1 && cmapEncodingId === 0) ||
  22907. (cmapPlatformId === -1 && cmapEncodingId === -1 && // Temporary hack
  22908. !!Encodings[properties.baseEncodingName])) { // Temporary hack
  22909. // When no preferred cmap table was found and |baseEncodingName| is
  22910. // one of the predefined encodings, we seem to obtain a better
  22911. // |charCodeToGlyphId| map from the code below (fixes bug 1057544).
  22912. // TODO: Note that this is a hack which should be removed as soon as
  22913. // we have proper support for more exotic cmap tables.
  22914. var baseEncoding = [];
  22915. if (properties.baseEncodingName === 'MacRomanEncoding' ||
  22916. properties.baseEncodingName === 'WinAnsiEncoding') {
  22917. baseEncoding = Encodings[properties.baseEncodingName];
  22918. }
  22919. for (charCode = 0; charCode < 256; charCode++) {
  22920. var glyphName;
  22921. if (this.differences && charCode in this.differences) {
  22922. glyphName = this.differences[charCode];
  22923. } else if (charCode in baseEncoding &&
  22924. baseEncoding[charCode] !== '') {
  22925. glyphName = baseEncoding[charCode];
  22926. } else {
  22927. glyphName = Encodings.StandardEncoding[charCode];
  22928. }
  22929. if (!glyphName) {
  22930. continue;
  22931. }
  22932. var unicodeOrCharCode, isUnicode = false;
  22933. if (cmapPlatformId === 3 && cmapEncodingId === 1) {
  22934. unicodeOrCharCode = GlyphsUnicode[glyphName];
  22935. isUnicode = true;
  22936. } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {
  22937. // TODO: the encoding needs to be updated with mac os table.
  22938. unicodeOrCharCode = Encodings.MacRomanEncoding.indexOf(glyphName);
  22939. }
  22940. var found = false;
  22941. for (i = 0; i < cmapMappingsLength; ++i) {
  22942. if (cmapMappings[i].charCode !== unicodeOrCharCode) {
  22943. continue;
  22944. }
  22945. var code = isUnicode ? charCode : unicodeOrCharCode;
  22946. if (hasGlyph(cmapMappings[i].glyphId, code, -1)) {
  22947. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  22948. found = true;
  22949. break;
  22950. }
  22951. }
  22952. if (!found && properties.glyphNames) {
  22953. // Try to map using the post table.
  22954. var glyphId = properties.glyphNames.indexOf(glyphName);
  22955. if (glyphId > 0 && hasGlyph(glyphId, -1, -1)) {
  22956. charCodeToGlyphId[charCode] = glyphId;
  22957. } else {
  22958. charCodeToGlyphId[charCode] = 0; // notdef
  22959. }
  22960. }
  22961. }
  22962. } else if (cmapPlatformId === 0 && cmapEncodingId === 0) {
  22963. // Default Unicode semantics, use the charcodes as is.
  22964. for (i = 0; i < cmapMappingsLength; ++i) {
  22965. charCodeToGlyphId[cmapMappings[i].charCode] =
  22966. cmapMappings[i].glyphId;
  22967. }
  22968. } else {
  22969. // For (3, 0) cmap tables:
  22970. // The charcode key being stored in charCodeToGlyphId is the lower
  22971. // byte of the two-byte charcodes of the cmap table since according to
  22972. // the spec: 'each byte from the string shall be prepended with the
  22973. // high byte of the range [of charcodes in the cmap table], to form
  22974. // a two-byte character, which shall be used to select the
  22975. // associated glyph description from the subtable'.
  22976. //
  22977. // For (1, 0) cmap tables:
  22978. // 'single bytes from the string shall be used to look up the
  22979. // associated glyph descriptions from the subtable'. This means
  22980. // charcodes in the cmap will be single bytes, so no-op since
  22981. // glyph.charCode & 0xFF === glyph.charCode
  22982. for (i = 0; i < cmapMappingsLength; ++i) {
  22983. charCode = cmapMappings[i].charCode & 0xFF;
  22984. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  22985. }
  22986. }
  22987. }
  22988. if (charCodeToGlyphId.length === 0) {
  22989. // defines at least one glyph
  22990. charCodeToGlyphId[0] = 0;
  22991. }
  22992. // Converting glyphs and ids into font's cmap table
  22993. var newMapping = adjustMapping(charCodeToGlyphId, properties);
  22994. this.toFontChar = newMapping.toFontChar;
  22995. tables.cmap = {
  22996. tag: 'cmap',
  22997. data: createCmapTable(newMapping.charCodeToGlyphId)
  22998. };
  22999. if (!tables['OS/2'] || !validateOS2Table(tables['OS/2'])) {
  23000. // extract some more font properties from the OpenType head and
  23001. // hhea tables; yMin and descent value are always negative
  23002. var override = {
  23003. unitsPerEm: int16(tables.head.data[18], tables.head.data[19]),
  23004. yMax: int16(tables.head.data[42], tables.head.data[43]),
  23005. yMin: int16(tables.head.data[38], tables.head.data[39]) - 0x10000,
  23006. ascent: int16(tables.hhea.data[4], tables.hhea.data[5]),
  23007. descent: int16(tables.hhea.data[6], tables.hhea.data[7]) - 0x10000
  23008. };
  23009. tables['OS/2'] = {
  23010. tag: 'OS/2',
  23011. data: createOS2Table(properties, newMapping.charCodeToGlyphId,
  23012. override)
  23013. };
  23014. }
  23015. // Rewrite the 'post' table if needed
  23016. if (!tables.post) {
  23017. tables.post = {
  23018. tag: 'post',
  23019. data: createPostTable(properties)
  23020. };
  23021. }
  23022. if (!isTrueType) {
  23023. try {
  23024. // Trying to repair CFF file
  23025. cffFile = new Stream(tables['CFF '].data);
  23026. var parser = new CFFParser(cffFile, properties);
  23027. cff = parser.parse();
  23028. var compiler = new CFFCompiler(cff);
  23029. tables['CFF '].data = compiler.compile();
  23030. } catch (e) {
  23031. warn('Failed to compile font ' + properties.loadedName);
  23032. }
  23033. }
  23034. // Re-creating 'name' table
  23035. if (!tables.name) {
  23036. tables.name = {
  23037. tag: 'name',
  23038. data: createNameTable(this.name)
  23039. };
  23040. } else {
  23041. // ... using existing 'name' table as prototype
  23042. var namePrototype = readNameTable(tables.name);
  23043. tables.name.data = createNameTable(name, namePrototype);
  23044. }
  23045. var builder = new OpenTypeFileBuilder(header.version);
  23046. for (var tableTag in tables) {
  23047. builder.addTable(tableTag, tables[tableTag].data);
  23048. }
  23049. return builder.toArray();
  23050. },
  23051. convert: function Font_convert(fontName, font, properties) {
  23052. // TODO: Check the charstring widths to determine this.
  23053. properties.fixedPitch = false;
  23054. var mapping = font.getGlyphMapping(properties);
  23055. var newMapping = adjustMapping(mapping, properties);
  23056. this.toFontChar = newMapping.toFontChar;
  23057. var numGlyphs = font.numGlyphs;
  23058. function getCharCodes(charCodeToGlyphId, glyphId) {
  23059. var charCodes = null;
  23060. for (var charCode in charCodeToGlyphId) {
  23061. if (glyphId === charCodeToGlyphId[charCode]) {
  23062. if (!charCodes) {
  23063. charCodes = [];
  23064. }
  23065. charCodes.push(charCode | 0);
  23066. }
  23067. }
  23068. return charCodes;
  23069. }
  23070. function createCharCode(charCodeToGlyphId, glyphId) {
  23071. for (var charCode in charCodeToGlyphId) {
  23072. if (glyphId === charCodeToGlyphId[charCode]) {
  23073. return charCode | 0;
  23074. }
  23075. }
  23076. newMapping.charCodeToGlyphId[newMapping.nextAvailableFontCharCode] =
  23077. glyphId;
  23078. return newMapping.nextAvailableFontCharCode++;
  23079. }
  23080. var seacs = font.seacs;
  23081. if (SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {
  23082. var matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX;
  23083. var charset = font.getCharset();
  23084. var seacMap = Object.create(null);
  23085. for (var glyphId in seacs) {
  23086. glyphId |= 0;
  23087. var seac = seacs[glyphId];
  23088. var baseGlyphName = Encodings.StandardEncoding[seac[2]];
  23089. var accentGlyphName = Encodings.StandardEncoding[seac[3]];
  23090. var baseGlyphId = charset.indexOf(baseGlyphName);
  23091. var accentGlyphId = charset.indexOf(accentGlyphName);
  23092. if (baseGlyphId < 0 || accentGlyphId < 0) {
  23093. continue;
  23094. }
  23095. var accentOffset = {
  23096. x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],
  23097. y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5]
  23098. };
  23099. var charCodes = getCharCodes(mapping, glyphId);
  23100. if (!charCodes) {
  23101. // There's no point in mapping it if the char code was never mapped
  23102. // to begin with.
  23103. continue;
  23104. }
  23105. for (var i = 0, ii = charCodes.length; i < ii; i++) {
  23106. var charCode = charCodes[i];
  23107. // Find a fontCharCode that maps to the base and accent glyphs.
  23108. // If one doesn't exists, create it.
  23109. var charCodeToGlyphId = newMapping.charCodeToGlyphId;
  23110. var baseFontCharCode = createCharCode(charCodeToGlyphId,
  23111. baseGlyphId);
  23112. var accentFontCharCode = createCharCode(charCodeToGlyphId,
  23113. accentGlyphId);
  23114. seacMap[charCode] = {
  23115. baseFontCharCode: baseFontCharCode,
  23116. accentFontCharCode: accentFontCharCode,
  23117. accentOffset: accentOffset
  23118. };
  23119. }
  23120. }
  23121. properties.seacMap = seacMap;
  23122. }
  23123. var unitsPerEm = 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  23124. var builder = new OpenTypeFileBuilder('\x4F\x54\x54\x4F');
  23125. // PostScript Font Program
  23126. builder.addTable('CFF ', font.data);
  23127. // OS/2 and Windows Specific metrics
  23128. builder.addTable('OS/2', createOS2Table(properties,
  23129. newMapping.charCodeToGlyphId));
  23130. // Character to glyphs mapping
  23131. builder.addTable('cmap', createCmapTable(newMapping.charCodeToGlyphId));
  23132. // Font header
  23133. builder.addTable('head',
  23134. '\x00\x01\x00\x00' + // Version number
  23135. '\x00\x00\x10\x00' + // fontRevision
  23136. '\x00\x00\x00\x00' + // checksumAdjustement
  23137. '\x5F\x0F\x3C\xF5' + // magicNumber
  23138. '\x00\x00' + // Flags
  23139. safeString16(unitsPerEm) + // unitsPerEM
  23140. '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date
  23141. '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date
  23142. '\x00\x00' + // xMin
  23143. safeString16(properties.descent) + // yMin
  23144. '\x0F\xFF' + // xMax
  23145. safeString16(properties.ascent) + // yMax
  23146. string16(properties.italicAngle ? 2 : 0) + // macStyle
  23147. '\x00\x11' + // lowestRecPPEM
  23148. '\x00\x00' + // fontDirectionHint
  23149. '\x00\x00' + // indexToLocFormat
  23150. '\x00\x00'); // glyphDataFormat
  23151. // Horizontal header
  23152. builder.addTable('hhea',
  23153. '\x00\x01\x00\x00' + // Version number
  23154. safeString16(properties.ascent) + // Typographic Ascent
  23155. safeString16(properties.descent) + // Typographic Descent
  23156. '\x00\x00' + // Line Gap
  23157. '\xFF\xFF' + // advanceWidthMax
  23158. '\x00\x00' + // minLeftSidebearing
  23159. '\x00\x00' + // minRightSidebearing
  23160. '\x00\x00' + // xMaxExtent
  23161. safeString16(properties.capHeight) + // caretSlopeRise
  23162. safeString16(Math.tan(properties.italicAngle) *
  23163. properties.xHeight) + // caretSlopeRun
  23164. '\x00\x00' + // caretOffset
  23165. '\x00\x00' + // -reserved-
  23166. '\x00\x00' + // -reserved-
  23167. '\x00\x00' + // -reserved-
  23168. '\x00\x00' + // -reserved-
  23169. '\x00\x00' + // metricDataFormat
  23170. string16(numGlyphs)); // Number of HMetrics
  23171. // Horizontal metrics
  23172. builder.addTable('hmtx', (function fontFieldsHmtx() {
  23173. var charstrings = font.charstrings;
  23174. var cffWidths = font.cff ? font.cff.widths : null;
  23175. var hmtx = '\x00\x00\x00\x00'; // Fake .notdef
  23176. for (var i = 1, ii = numGlyphs; i < ii; i++) {
  23177. var width = 0;
  23178. if (charstrings) {
  23179. var charstring = charstrings[i - 1];
  23180. width = 'width' in charstring ? charstring.width : 0;
  23181. } else if (cffWidths) {
  23182. width = Math.ceil(cffWidths[i] || 0);
  23183. }
  23184. hmtx += string16(width) + string16(0);
  23185. }
  23186. return hmtx;
  23187. })());
  23188. // Maximum profile
  23189. builder.addTable('maxp',
  23190. '\x00\x00\x50\x00' + // Version number
  23191. string16(numGlyphs)); // Num of glyphs
  23192. // Naming tables
  23193. builder.addTable('name', createNameTable(fontName));
  23194. // PostScript informations
  23195. builder.addTable('post', createPostTable(properties));
  23196. return builder.toArray();
  23197. },
  23198. /**
  23199. * Builds a char code to unicode map based on section 9.10 of the spec.
  23200. * @param {Object} properties Font properties object.
  23201. * @return {Object} A ToUnicodeMap object.
  23202. */
  23203. buildToUnicode: function Font_buildToUnicode(properties) {
  23204. // Section 9.10.2 Mapping Character Codes to Unicode Values
  23205. if (properties.toUnicode && properties.toUnicode.length !== 0) {
  23206. return properties.toUnicode;
  23207. }
  23208. // According to the spec if the font is a simple font we should only map
  23209. // to unicode if the base encoding is MacRoman, MacExpert, or WinAnsi or
  23210. // the differences array only contains adobe standard or symbol set names,
  23211. // in pratice it seems better to always try to create a toUnicode
  23212. // map based of the default encoding.
  23213. var toUnicode, charcode;
  23214. if (!properties.composite /* is simple font */) {
  23215. toUnicode = [];
  23216. var encoding = properties.defaultEncoding.slice();
  23217. var baseEncodingName = properties.baseEncodingName;
  23218. // Merge in the differences array.
  23219. var differences = properties.differences;
  23220. for (charcode in differences) {
  23221. encoding[charcode] = differences[charcode];
  23222. }
  23223. for (charcode in encoding) {
  23224. // a) Map the character code to a character name.
  23225. var glyphName = encoding[charcode];
  23226. // b) Look up the character name in the Adobe Glyph List (see the
  23227. // Bibliography) to obtain the corresponding Unicode value.
  23228. if (glyphName === '') {
  23229. continue;
  23230. } else if (GlyphsUnicode[glyphName] === undefined) {
  23231. // (undocumented) c) Few heuristics to recognize unknown glyphs
  23232. // NOTE: Adobe Reader does not do this step, but OSX Preview does
  23233. var code = 0;
  23234. switch (glyphName[0]) {
  23235. case 'G': // Gxx glyph
  23236. if (glyphName.length === 3) {
  23237. code = parseInt(glyphName.substr(1), 16);
  23238. }
  23239. break;
  23240. case 'g': // g00xx glyph
  23241. if (glyphName.length === 5) {
  23242. code = parseInt(glyphName.substr(1), 16);
  23243. }
  23244. break;
  23245. case 'C': // Cddd glyph
  23246. case 'c': // cddd glyph
  23247. if (glyphName.length >= 3) {
  23248. code = +glyphName.substr(1);
  23249. }
  23250. break;
  23251. }
  23252. if (code) {
  23253. // If |baseEncodingName| is one the predefined encodings,
  23254. // and |code| equals |charcode|, using the glyph defined in the
  23255. // baseEncoding seems to yield a better |toUnicode| mapping
  23256. // (fixes issue 5070).
  23257. if (baseEncodingName && code === +charcode) {
  23258. var baseEncoding = Encodings[baseEncodingName];
  23259. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  23260. toUnicode[charcode] =
  23261. String.fromCharCode(GlyphsUnicode[glyphName]);
  23262. continue;
  23263. }
  23264. }
  23265. toUnicode[charcode] = String.fromCharCode(code);
  23266. }
  23267. continue;
  23268. }
  23269. toUnicode[charcode] = String.fromCharCode(GlyphsUnicode[glyphName]);
  23270. }
  23271. return new ToUnicodeMap(toUnicode);
  23272. }
  23273. // If the font is a composite font that uses one of the predefined CMaps
  23274. // listed in Table 118 (except Identity–H and Identity–V) or whose
  23275. // descendant CIDFont uses the Adobe-GB1, Adobe-CNS1, Adobe-Japan1, or
  23276. // Adobe-Korea1 character collection:
  23277. if (properties.composite && (
  23278. (properties.cMap.builtInCMap &&
  23279. !(properties.cMap instanceof IdentityCMap)) ||
  23280. (properties.cidSystemInfo.registry === 'Adobe' &&
  23281. (properties.cidSystemInfo.ordering === 'GB1' ||
  23282. properties.cidSystemInfo.ordering === 'CNS1' ||
  23283. properties.cidSystemInfo.ordering === 'Japan1' ||
  23284. properties.cidSystemInfo.ordering === 'Korea1')))) {
  23285. // Then:
  23286. // a) Map the character code to a character identifier (CID) according
  23287. // to the font’s CMap.
  23288. // b) Obtain the registry and ordering of the character collection used
  23289. // by the font’s CMap (for example, Adobe and Japan1) from its
  23290. // CIDSystemInfo dictionary.
  23291. var registry = properties.cidSystemInfo.registry;
  23292. var ordering = properties.cidSystemInfo.ordering;
  23293. // c) Construct a second CMap name by concatenating the registry and
  23294. // ordering obtained in step (b) in the format registry–ordering–UCS2
  23295. // (for example, Adobe–Japan1–UCS2).
  23296. var ucs2CMapName = new Name(registry + '-' + ordering + '-UCS2');
  23297. // d) Obtain the CMap with the name constructed in step (c) (available
  23298. // from the ASN Web site; see the Bibliography).
  23299. var ucs2CMap = CMapFactory.create(ucs2CMapName,
  23300. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  23301. var cMap = properties.cMap;
  23302. toUnicode = [];
  23303. cMap.forEach(function(charcode, cid) {
  23304. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  23305. // e) Map the CID obtained in step (a) according to the CMap obtained
  23306. // in step (d), producing a Unicode value.
  23307. var ucs2 = ucs2CMap.lookup(cid);
  23308. if (ucs2) {
  23309. toUnicode[charcode] =
  23310. String.fromCharCode((ucs2.charCodeAt(0) << 8) +
  23311. ucs2.charCodeAt(1));
  23312. }
  23313. });
  23314. return new ToUnicodeMap(toUnicode);
  23315. }
  23316. // The viewer's choice, just use an identity map.
  23317. return new IdentityToUnicodeMap(properties.firstChar,
  23318. properties.lastChar);
  23319. },
  23320. get spaceWidth() {
  23321. if ('_shadowWidth' in this) {
  23322. return this._shadowWidth;
  23323. }
  23324. // trying to estimate space character width
  23325. var possibleSpaceReplacements = ['space', 'minus', 'one', 'i'];
  23326. var width;
  23327. for (var i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) {
  23328. var glyphName = possibleSpaceReplacements[i];
  23329. // if possible, getting width by glyph name
  23330. if (glyphName in this.widths) {
  23331. width = this.widths[glyphName];
  23332. break;
  23333. }
  23334. var glyphUnicode = GlyphsUnicode[glyphName];
  23335. // finding the charcode via unicodeToCID map
  23336. var charcode = 0;
  23337. if (this.composite) {
  23338. if (this.cMap.contains(glyphUnicode)) {
  23339. charcode = this.cMap.lookup(glyphUnicode);
  23340. }
  23341. }
  23342. // ... via toUnicode map
  23343. if (!charcode && 'toUnicode' in this) {
  23344. charcode = this.toUnicode.charCodeOf(glyphUnicode);
  23345. }
  23346. // setting it to unicode if negative or undefined
  23347. if (charcode <= 0) {
  23348. charcode = glyphUnicode;
  23349. }
  23350. // trying to get width via charcode
  23351. width = this.widths[charcode];
  23352. if (width) {
  23353. break; // the non-zero width found
  23354. }
  23355. }
  23356. width = width || this.defaultWidth;
  23357. // Do not shadow the property here. See discussion:
  23358. // https://github.com/mozilla/pdf.js/pull/2127#discussion_r1662280
  23359. this._shadowWidth = width;
  23360. return width;
  23361. },
  23362. charToGlyph: function Font_charToGlyph(charcode) {
  23363. var fontCharCode, width, operatorListId;
  23364. var widthCode = charcode;
  23365. if (this.cMap && this.cMap.contains(charcode)) {
  23366. widthCode = this.cMap.lookup(charcode);
  23367. }
  23368. width = this.widths[widthCode];
  23369. width = isNum(width) ? width : this.defaultWidth;
  23370. var vmetric = this.vmetrics && this.vmetrics[widthCode];
  23371. var unicode = this.toUnicode.get(charcode) || charcode;
  23372. if (typeof unicode === 'number') {
  23373. unicode = String.fromCharCode(unicode);
  23374. }
  23375. // First try the toFontChar map, if it's not there then try falling
  23376. // back to the char code.
  23377. fontCharCode = this.toFontChar[charcode] || charcode;
  23378. if (this.missingFile) {
  23379. fontCharCode = mapSpecialUnicodeValues(fontCharCode);
  23380. }
  23381. if (this.isType3Font) {
  23382. // Font char code in this case is actually a glyph name.
  23383. operatorListId = fontCharCode;
  23384. }
  23385. var accent = null;
  23386. if (this.seacMap && this.seacMap[charcode]) {
  23387. var seac = this.seacMap[charcode];
  23388. fontCharCode = seac.baseFontCharCode;
  23389. accent = {
  23390. fontChar: String.fromCharCode(seac.accentFontCharCode),
  23391. offset: seac.accentOffset
  23392. };
  23393. }
  23394. var fontChar = String.fromCharCode(fontCharCode);
  23395. var glyph = this.glyphCache[charcode];
  23396. if (!glyph ||
  23397. !glyph.matchesForCache(fontChar, unicode, accent, width, vmetric,
  23398. operatorListId)) {
  23399. glyph = new Glyph(fontChar, unicode, accent, width, vmetric,
  23400. operatorListId);
  23401. this.glyphCache[charcode] = glyph;
  23402. }
  23403. return glyph;
  23404. },
  23405. charsToGlyphs: function Font_charsToGlyphs(chars) {
  23406. var charsCache = this.charsCache;
  23407. var glyphs, glyph, charcode;
  23408. // if we translated this string before, just grab it from the cache
  23409. if (charsCache) {
  23410. glyphs = charsCache[chars];
  23411. if (glyphs) {
  23412. return glyphs;
  23413. }
  23414. }
  23415. // lazily create the translation cache
  23416. if (!charsCache) {
  23417. charsCache = this.charsCache = Object.create(null);
  23418. }
  23419. glyphs = [];
  23420. var charsCacheKey = chars;
  23421. var i = 0, ii;
  23422. if (this.cMap) {
  23423. // composite fonts have multi-byte strings convert the string from
  23424. // single-byte to multi-byte
  23425. var c = {};
  23426. while (i < chars.length) {
  23427. this.cMap.readCharCode(chars, i, c);
  23428. charcode = c.charcode;
  23429. var length = c.length;
  23430. i += length;
  23431. glyph = this.charToGlyph(charcode);
  23432. glyphs.push(glyph);
  23433. // placing null after each word break charcode (ASCII SPACE)
  23434. // Ignore occurences of 0x20 in multiple-byte codes.
  23435. if (length === 1 && chars.charCodeAt(i - 1) === 0x20) {
  23436. glyphs.push(null);
  23437. }
  23438. }
  23439. } else {
  23440. for (i = 0, ii = chars.length; i < ii; ++i) {
  23441. charcode = chars.charCodeAt(i);
  23442. glyph = this.charToGlyph(charcode);
  23443. glyphs.push(glyph);
  23444. if (charcode === 0x20) {
  23445. glyphs.push(null);
  23446. }
  23447. }
  23448. }
  23449. // Enter the translated string into the cache
  23450. return (charsCache[charsCacheKey] = glyphs);
  23451. }
  23452. };
  23453. return Font;
  23454. })();
  23455. var ErrorFont = (function ErrorFontClosure() {
  23456. function ErrorFont(error) {
  23457. this.error = error;
  23458. this.loadedName = 'g_font_error';
  23459. this.loading = false;
  23460. }
  23461. ErrorFont.prototype = {
  23462. charsToGlyphs: function ErrorFont_charsToGlyphs() {
  23463. return [];
  23464. },
  23465. exportData: function ErrorFont_exportData() {
  23466. return {error: this.error};
  23467. }
  23468. };
  23469. return ErrorFont;
  23470. })();
  23471. /**
  23472. * Shared logic for building a char code to glyph id mapping for Type1 and
  23473. * simple CFF fonts. See section 9.6.6.2 of the spec.
  23474. * @param {Object} properties Font properties object.
  23475. * @param {Object} builtInEncoding The encoding contained within the actual font
  23476. * data.
  23477. * @param {Array} Array of glyph names where the index is the glyph ID.
  23478. * @returns {Object} A char code to glyph ID map.
  23479. */
  23480. function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
  23481. var charCodeToGlyphId = Object.create(null);
  23482. var glyphId, charCode, baseEncoding;
  23483. if (properties.baseEncodingName) {
  23484. // If a valid base encoding name was used, the mapping is initialized with
  23485. // that.
  23486. baseEncoding = Encodings[properties.baseEncodingName];
  23487. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  23488. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  23489. if (glyphId >= 0) {
  23490. charCodeToGlyphId[charCode] = glyphId;
  23491. } else {
  23492. charCodeToGlyphId[charCode] = 0; // notdef
  23493. }
  23494. }
  23495. } else if (!!(properties.flags & FontFlags.Symbolic)) {
  23496. // For a symbolic font the encoding should be the fonts built-in
  23497. // encoding.
  23498. for (charCode in builtInEncoding) {
  23499. charCodeToGlyphId[charCode] = builtInEncoding[charCode];
  23500. }
  23501. } else {
  23502. // For non-symbolic fonts that don't have a base encoding the standard
  23503. // encoding should be used.
  23504. baseEncoding = Encodings.StandardEncoding;
  23505. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  23506. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  23507. if (glyphId >= 0) {
  23508. charCodeToGlyphId[charCode] = glyphId;
  23509. } else {
  23510. charCodeToGlyphId[charCode] = 0; // notdef
  23511. }
  23512. }
  23513. }
  23514. // Lastly, merge in the differences.
  23515. var differences = properties.differences;
  23516. if (differences) {
  23517. for (charCode in differences) {
  23518. var glyphName = differences[charCode];
  23519. glyphId = glyphNames.indexOf(glyphName);
  23520. if (glyphId >= 0) {
  23521. charCodeToGlyphId[charCode] = glyphId;
  23522. } else {
  23523. charCodeToGlyphId[charCode] = 0; // notdef
  23524. }
  23525. }
  23526. }
  23527. return charCodeToGlyphId;
  23528. }
  23529. /*
  23530. * CharStrings are encoded following the the CharString Encoding sequence
  23531. * describe in Chapter 6 of the "Adobe Type1 Font Format" specification.
  23532. * The value in a byte indicates a command, a number, or subsequent bytes
  23533. * that are to be interpreted in a special way.
  23534. *
  23535. * CharString Number Encoding:
  23536. * A CharString byte containing the values from 32 through 255 inclusive
  23537. * indicate an integer. These values are decoded in four ranges.
  23538. *
  23539. * 1. A CharString byte containing a value, v, between 32 and 246 inclusive,
  23540. * indicate the integer v - 139. Thus, the integer values from -107 through
  23541. * 107 inclusive may be encoded in single byte.
  23542. *
  23543. * 2. A CharString byte containing a value, v, between 247 and 250 inclusive,
  23544. * indicates an integer involving the next byte, w, according to the formula:
  23545. * [(v - 247) x 256] + w + 108
  23546. *
  23547. * 3. A CharString byte containing a value, v, between 251 and 254 inclusive,
  23548. * indicates an integer involving the next byte, w, according to the formula:
  23549. * -[(v - 251) * 256] - w - 108
  23550. *
  23551. * 4. A CharString containing the value 255 indicates that the next 4 bytes
  23552. * are a two complement signed integer. The first of these bytes contains the
  23553. * highest order bits, the second byte contains the next higher order bits
  23554. * and the fourth byte contain the lowest order bits.
  23555. *
  23556. *
  23557. * CharString Command Encoding:
  23558. * CharStrings commands are encoded in 1 or 2 bytes.
  23559. *
  23560. * Single byte commands are encoded in 1 byte that contains a value between
  23561. * 0 and 31 inclusive.
  23562. * If a command byte contains the value 12, then the value in the next byte
  23563. * indicates a command. This "escape" mechanism allows many extra commands
  23564. * to be encoded and this encoding technique helps to minimize the length of
  23565. * the charStrings.
  23566. */
  23567. var Type1CharString = (function Type1CharStringClosure() {
  23568. var COMMAND_MAP = {
  23569. 'hstem': [1],
  23570. 'vstem': [3],
  23571. 'vmoveto': [4],
  23572. 'rlineto': [5],
  23573. 'hlineto': [6],
  23574. 'vlineto': [7],
  23575. 'rrcurveto': [8],
  23576. 'callsubr': [10],
  23577. 'flex': [12, 35],
  23578. 'drop' : [12, 18],
  23579. 'endchar': [14],
  23580. 'rmoveto': [21],
  23581. 'hmoveto': [22],
  23582. 'vhcurveto': [30],
  23583. 'hvcurveto': [31]
  23584. };
  23585. function Type1CharString() {
  23586. this.width = 0;
  23587. this.lsb = 0;
  23588. this.flexing = false;
  23589. this.output = [];
  23590. this.stack = [];
  23591. }
  23592. Type1CharString.prototype = {
  23593. convert: function Type1CharString_convert(encoded, subrs) {
  23594. var count = encoded.length;
  23595. var error = false;
  23596. var wx, sbx, subrNumber;
  23597. for (var i = 0; i < count; i++) {
  23598. var value = encoded[i];
  23599. if (value < 32) {
  23600. if (value === 12) {
  23601. value = (value << 8) + encoded[++i];
  23602. }
  23603. switch (value) {
  23604. case 1: // hstem
  23605. if (!HINTING_ENABLED) {
  23606. this.stack = [];
  23607. break;
  23608. }
  23609. error = this.executeCommand(2, COMMAND_MAP.hstem);
  23610. break;
  23611. case 3: // vstem
  23612. if (!HINTING_ENABLED) {
  23613. this.stack = [];
  23614. break;
  23615. }
  23616. error = this.executeCommand(2, COMMAND_MAP.vstem);
  23617. break;
  23618. case 4: // vmoveto
  23619. if (this.flexing) {
  23620. if (this.stack.length < 1) {
  23621. error = true;
  23622. break;
  23623. }
  23624. // Add the dx for flex and but also swap the values so they are
  23625. // the right order.
  23626. var dy = this.stack.pop();
  23627. this.stack.push(0, dy);
  23628. break;
  23629. }
  23630. error = this.executeCommand(1, COMMAND_MAP.vmoveto);
  23631. break;
  23632. case 5: // rlineto
  23633. error = this.executeCommand(2, COMMAND_MAP.rlineto);
  23634. break;
  23635. case 6: // hlineto
  23636. error = this.executeCommand(1, COMMAND_MAP.hlineto);
  23637. break;
  23638. case 7: // vlineto
  23639. error = this.executeCommand(1, COMMAND_MAP.vlineto);
  23640. break;
  23641. case 8: // rrcurveto
  23642. error = this.executeCommand(6, COMMAND_MAP.rrcurveto);
  23643. break;
  23644. case 9: // closepath
  23645. // closepath is a Type1 command that does not take argument and is
  23646. // useless in Type2 and it can simply be ignored.
  23647. this.stack = [];
  23648. break;
  23649. case 10: // callsubr
  23650. if (this.stack.length < 1) {
  23651. error = true;
  23652. break;
  23653. }
  23654. subrNumber = this.stack.pop();
  23655. error = this.convert(subrs[subrNumber], subrs);
  23656. break;
  23657. case 11: // return
  23658. return error;
  23659. case 13: // hsbw
  23660. if (this.stack.length < 2) {
  23661. error = true;
  23662. break;
  23663. }
  23664. // To convert to type2 we have to move the width value to the
  23665. // first part of the charstring and then use hmoveto with lsb.
  23666. wx = this.stack.pop();
  23667. sbx = this.stack.pop();
  23668. this.lsb = sbx;
  23669. this.width = wx;
  23670. this.stack.push(wx, sbx);
  23671. error = this.executeCommand(2, COMMAND_MAP.hmoveto);
  23672. break;
  23673. case 14: // endchar
  23674. this.output.push(COMMAND_MAP.endchar[0]);
  23675. break;
  23676. case 21: // rmoveto
  23677. if (this.flexing) {
  23678. break;
  23679. }
  23680. error = this.executeCommand(2, COMMAND_MAP.rmoveto);
  23681. break;
  23682. case 22: // hmoveto
  23683. if (this.flexing) {
  23684. // Add the dy for flex.
  23685. this.stack.push(0);
  23686. break;
  23687. }
  23688. error = this.executeCommand(1, COMMAND_MAP.hmoveto);
  23689. break;
  23690. case 30: // vhcurveto
  23691. error = this.executeCommand(4, COMMAND_MAP.vhcurveto);
  23692. break;
  23693. case 31: // hvcurveto
  23694. error = this.executeCommand(4, COMMAND_MAP.hvcurveto);
  23695. break;
  23696. case (12 << 8) + 0: // dotsection
  23697. // dotsection is a Type1 command to specify some hinting feature
  23698. // for dots that do not take a parameter and it can safely be
  23699. // ignored for Type2.
  23700. this.stack = [];
  23701. break;
  23702. case (12 << 8) + 1: // vstem3
  23703. if (!HINTING_ENABLED) {
  23704. this.stack = [];
  23705. break;
  23706. }
  23707. // [vh]stem3 are Type1 only and Type2 supports [vh]stem with
  23708. // multiple parameters, so instead of returning [vh]stem3 take a
  23709. // shortcut and return [vhstem] instead.
  23710. error = this.executeCommand(2, COMMAND_MAP.vstem);
  23711. break;
  23712. case (12 << 8) + 2: // hstem3
  23713. if (!HINTING_ENABLED) {
  23714. this.stack = [];
  23715. break;
  23716. }
  23717. // See vstem3.
  23718. error = this.executeCommand(2, COMMAND_MAP.hstem);
  23719. break;
  23720. case (12 << 8) + 6: // seac
  23721. // seac is like type 2's special endchar but it doesn't use the
  23722. // first argument asb, so remove it.
  23723. if (SEAC_ANALYSIS_ENABLED) {
  23724. this.seac = this.stack.splice(-4, 4);
  23725. error = this.executeCommand(0, COMMAND_MAP.endchar);
  23726. } else {
  23727. error = this.executeCommand(4, COMMAND_MAP.endchar);
  23728. }
  23729. break;
  23730. case (12 << 8) + 7: // sbw
  23731. if (this.stack.length < 4) {
  23732. error = true;
  23733. break;
  23734. }
  23735. // To convert to type2 we have to move the width value to the
  23736. // first part of the charstring and then use rmoveto with
  23737. // (dx, dy). The height argument will not be used for vmtx and
  23738. // vhea tables reconstruction -- ignoring it.
  23739. var wy = this.stack.pop();
  23740. wx = this.stack.pop();
  23741. var sby = this.stack.pop();
  23742. sbx = this.stack.pop();
  23743. this.lsb = sbx;
  23744. this.width = wx;
  23745. this.stack.push(wx, sbx, sby);
  23746. error = this.executeCommand(3, COMMAND_MAP.rmoveto);
  23747. break;
  23748. case (12 << 8) + 12: // div
  23749. if (this.stack.length < 2) {
  23750. error = true;
  23751. break;
  23752. }
  23753. var num2 = this.stack.pop();
  23754. var num1 = this.stack.pop();
  23755. this.stack.push(num1 / num2);
  23756. break;
  23757. case (12 << 8) + 16: // callothersubr
  23758. if (this.stack.length < 2) {
  23759. error = true;
  23760. break;
  23761. }
  23762. subrNumber = this.stack.pop();
  23763. var numArgs = this.stack.pop();
  23764. if (subrNumber === 0 && numArgs === 3) {
  23765. var flexArgs = this.stack.splice(this.stack.length - 17, 17);
  23766. this.stack.push(
  23767. flexArgs[2] + flexArgs[0], // bcp1x + rpx
  23768. flexArgs[3] + flexArgs[1], // bcp1y + rpy
  23769. flexArgs[4], // bcp2x
  23770. flexArgs[5], // bcp2y
  23771. flexArgs[6], // p2x
  23772. flexArgs[7], // p2y
  23773. flexArgs[8], // bcp3x
  23774. flexArgs[9], // bcp3y
  23775. flexArgs[10], // bcp4x
  23776. flexArgs[11], // bcp4y
  23777. flexArgs[12], // p3x
  23778. flexArgs[13], // p3y
  23779. flexArgs[14] // flexDepth
  23780. // 15 = finalx unused by flex
  23781. // 16 = finaly unused by flex
  23782. );
  23783. error = this.executeCommand(13, COMMAND_MAP.flex, true);
  23784. this.flexing = false;
  23785. this.stack.push(flexArgs[15], flexArgs[16]);
  23786. } else if (subrNumber === 1 && numArgs === 0) {
  23787. this.flexing = true;
  23788. }
  23789. break;
  23790. case (12 << 8) + 17: // pop
  23791. // Ignore this since it is only used with othersubr.
  23792. break;
  23793. case (12 << 8) + 33: // setcurrentpoint
  23794. // Ignore for now.
  23795. this.stack = [];
  23796. break;
  23797. default:
  23798. warn('Unknown type 1 charstring command of "' + value + '"');
  23799. break;
  23800. }
  23801. if (error) {
  23802. break;
  23803. }
  23804. continue;
  23805. } else if (value <= 246) {
  23806. value = value - 139;
  23807. } else if (value <= 250) {
  23808. value = ((value - 247) * 256) + encoded[++i] + 108;
  23809. } else if (value <= 254) {
  23810. value = -((value - 251) * 256) - encoded[++i] - 108;
  23811. } else {
  23812. value = (encoded[++i] & 0xff) << 24 | (encoded[++i] & 0xff) << 16 |
  23813. (encoded[++i] & 0xff) << 8 | (encoded[++i] & 0xff) << 0;
  23814. }
  23815. this.stack.push(value);
  23816. }
  23817. return error;
  23818. },
  23819. executeCommand: function(howManyArgs, command, keepStack) {
  23820. var stackLength = this.stack.length;
  23821. if (howManyArgs > stackLength) {
  23822. return true;
  23823. }
  23824. var start = stackLength - howManyArgs;
  23825. for (var i = start; i < stackLength; i++) {
  23826. var value = this.stack[i];
  23827. if (value === (value | 0)) { // int
  23828. this.output.push(28, (value >> 8) & 0xff, value & 0xff);
  23829. } else { // fixed point
  23830. value = (65536 * value) | 0;
  23831. this.output.push(255,
  23832. (value >> 24) & 0xFF,
  23833. (value >> 16) & 0xFF,
  23834. (value >> 8) & 0xFF,
  23835. value & 0xFF);
  23836. }
  23837. }
  23838. this.output.push.apply(this.output, command);
  23839. if (keepStack) {
  23840. this.stack.splice(start, howManyArgs);
  23841. } else {
  23842. this.stack.length = 0;
  23843. }
  23844. return false;
  23845. }
  23846. };
  23847. return Type1CharString;
  23848. })();
  23849. /*
  23850. * Type1Parser encapsulate the needed code for parsing a Type1 font
  23851. * program. Some of its logic depends on the Type2 charstrings
  23852. * structure.
  23853. * Note: this doesn't really parse the font since that would require evaluation
  23854. * of PostScript, but it is possible in most cases to extract what we need
  23855. * without a full parse.
  23856. */
  23857. var Type1Parser = (function Type1ParserClosure() {
  23858. /*
  23859. * Decrypt a Sequence of Ciphertext Bytes to Produce the Original Sequence
  23860. * of Plaintext Bytes. The function took a key as a parameter which can be
  23861. * for decrypting the eexec block of for decoding charStrings.
  23862. */
  23863. var EEXEC_ENCRYPT_KEY = 55665;
  23864. var CHAR_STRS_ENCRYPT_KEY = 4330;
  23865. function isHexDigit(code) {
  23866. return code >= 48 && code <= 57 || // '0'-'9'
  23867. code >= 65 && code <= 70 || // 'A'-'F'
  23868. code >= 97 && code <= 102; // 'a'-'f'
  23869. }
  23870. function decrypt(data, key, discardNumber) {
  23871. var r = key | 0, c1 = 52845, c2 = 22719;
  23872. var count = data.length;
  23873. var decrypted = new Uint8Array(count);
  23874. for (var i = 0; i < count; i++) {
  23875. var value = data[i];
  23876. decrypted[i] = value ^ (r >> 8);
  23877. r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
  23878. }
  23879. return Array.prototype.slice.call(decrypted, discardNumber);
  23880. }
  23881. function decryptAscii(data, key, discardNumber) {
  23882. var r = key | 0, c1 = 52845, c2 = 22719;
  23883. var count = data.length, maybeLength = count >>> 1;
  23884. var decrypted = new Uint8Array(maybeLength);
  23885. var i, j;
  23886. for (i = 0, j = 0; i < count; i++) {
  23887. var digit1 = data[i];
  23888. if (!isHexDigit(digit1)) {
  23889. continue;
  23890. }
  23891. i++;
  23892. var digit2;
  23893. while (i < count && !isHexDigit(digit2 = data[i])) {
  23894. i++;
  23895. }
  23896. if (i < count) {
  23897. var value = parseInt(String.fromCharCode(digit1, digit2), 16);
  23898. decrypted[j++] = value ^ (r >> 8);
  23899. r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
  23900. }
  23901. }
  23902. return Array.prototype.slice.call(decrypted, discardNumber, j);
  23903. }
  23904. function isSpecial(c) {
  23905. return c === 0x2F || // '/'
  23906. c === 0x5B || c === 0x5D || // '[', ']'
  23907. c === 0x7B || c === 0x7D || // '{', '}'
  23908. c === 0x28 || c === 0x29; // '(', ')'
  23909. }
  23910. function Type1Parser(stream, encrypted) {
  23911. if (encrypted) {
  23912. var data = stream.getBytes();
  23913. var isBinary = !(isHexDigit(data[0]) && isHexDigit(data[1]) &&
  23914. isHexDigit(data[2]) && isHexDigit(data[3]));
  23915. stream = new Stream(isBinary ? decrypt(data, EEXEC_ENCRYPT_KEY, 4) :
  23916. decryptAscii(data, EEXEC_ENCRYPT_KEY, 4));
  23917. }
  23918. this.stream = stream;
  23919. this.nextChar();
  23920. }
  23921. Type1Parser.prototype = {
  23922. readNumberArray: function Type1Parser_readNumberArray() {
  23923. this.getToken(); // read '[' or '{' (arrays can start with either)
  23924. var array = [];
  23925. while (true) {
  23926. var token = this.getToken();
  23927. if (token === null || token === ']' || token === '}') {
  23928. break;
  23929. }
  23930. array.push(parseFloat(token || 0));
  23931. }
  23932. return array;
  23933. },
  23934. readNumber: function Type1Parser_readNumber() {
  23935. var token = this.getToken();
  23936. return parseFloat(token || 0);
  23937. },
  23938. readInt: function Type1Parser_readInt() {
  23939. // Use '| 0' to prevent setting a double into length such as the double
  23940. // does not flow into the loop variable.
  23941. var token = this.getToken();
  23942. return parseInt(token || 0, 10) | 0;
  23943. },
  23944. readBoolean: function Type1Parser_readBoolean() {
  23945. var token = this.getToken();
  23946. // Use 1 and 0 since that's what type2 charstrings use.
  23947. return token === 'true' ? 1 : 0;
  23948. },
  23949. nextChar : function Type1_nextChar() {
  23950. return (this.currentChar = this.stream.getByte());
  23951. },
  23952. getToken: function Type1Parser_getToken() {
  23953. // Eat whitespace and comments.
  23954. var comment = false;
  23955. var ch = this.currentChar;
  23956. while (true) {
  23957. if (ch === -1) {
  23958. return null;
  23959. }
  23960. if (comment) {
  23961. if (ch === 0x0A || ch === 0x0D) {
  23962. comment = false;
  23963. }
  23964. } else if (ch === 0x25) { // '%'
  23965. comment = true;
  23966. } else if (!Lexer.isSpace(ch)) {
  23967. break;
  23968. }
  23969. ch = this.nextChar();
  23970. }
  23971. if (isSpecial(ch)) {
  23972. this.nextChar();
  23973. return String.fromCharCode(ch);
  23974. }
  23975. var token = '';
  23976. do {
  23977. token += String.fromCharCode(ch);
  23978. ch = this.nextChar();
  23979. } while (ch >= 0 && !Lexer.isSpace(ch) && !isSpecial(ch));
  23980. return token;
  23981. },
  23982. /*
  23983. * Returns an object containing a Subrs array and a CharStrings
  23984. * array extracted from and eexec encrypted block of data
  23985. */
  23986. extractFontProgram: function Type1Parser_extractFontProgram() {
  23987. var stream = this.stream;
  23988. var subrs = [], charstrings = [];
  23989. var program = {
  23990. subrs: [],
  23991. charstrings: [],
  23992. properties: {
  23993. 'privateData': {
  23994. 'lenIV': 4
  23995. }
  23996. }
  23997. };
  23998. var token, length, data, lenIV, encoded;
  23999. while ((token = this.getToken()) !== null) {
  24000. if (token !== '/') {
  24001. continue;
  24002. }
  24003. token = this.getToken();
  24004. switch (token) {
  24005. case 'CharStrings':
  24006. // The number immediately following CharStrings must be greater or
  24007. // equal to the number of CharStrings.
  24008. this.getToken();
  24009. this.getToken(); // read in 'dict'
  24010. this.getToken(); // read in 'dup'
  24011. this.getToken(); // read in 'begin'
  24012. while(true) {
  24013. token = this.getToken();
  24014. if (token === null || token === 'end') {
  24015. break;
  24016. }
  24017. if (token !== '/') {
  24018. continue;
  24019. }
  24020. var glyph = this.getToken();
  24021. length = this.readInt();
  24022. this.getToken(); // read in 'RD' or '-|'
  24023. data = stream.makeSubStream(stream.pos, length);
  24024. lenIV = program.properties.privateData['lenIV'];
  24025. encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);
  24026. // Skip past the required space and binary data.
  24027. stream.skip(length);
  24028. this.nextChar();
  24029. token = this.getToken(); // read in 'ND' or '|-'
  24030. if (token === 'noaccess') {
  24031. this.getToken(); // read in 'def'
  24032. }
  24033. charstrings.push({
  24034. glyph: glyph,
  24035. encoded: encoded
  24036. });
  24037. }
  24038. break;
  24039. case 'Subrs':
  24040. var num = this.readInt();
  24041. this.getToken(); // read in 'array'
  24042. while ((token = this.getToken()) === 'dup') {
  24043. var index = this.readInt();
  24044. length = this.readInt();
  24045. this.getToken(); // read in 'RD' or '-|'
  24046. data = stream.makeSubStream(stream.pos, length);
  24047. lenIV = program.properties.privateData['lenIV'];
  24048. encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);
  24049. // Skip past the required space and binary data.
  24050. stream.skip(length);
  24051. this.nextChar();
  24052. token = this.getToken(); // read in 'NP' or '|'
  24053. if (token === 'noaccess') {
  24054. this.getToken(); // read in 'put'
  24055. }
  24056. subrs[index] = encoded;
  24057. }
  24058. break;
  24059. case 'BlueValues':
  24060. case 'OtherBlues':
  24061. case 'FamilyBlues':
  24062. case 'FamilyOtherBlues':
  24063. var blueArray = this.readNumberArray();
  24064. // *Blue* values may contain invalid data: disables reading of
  24065. // those values when hinting is disabled.
  24066. if (blueArray.length > 0 && (blueArray.length % 2) === 0 &&
  24067. HINTING_ENABLED) {
  24068. program.properties.privateData[token] = blueArray;
  24069. }
  24070. break;
  24071. case 'StemSnapH':
  24072. case 'StemSnapV':
  24073. program.properties.privateData[token] = this.readNumberArray();
  24074. break;
  24075. case 'StdHW':
  24076. case 'StdVW':
  24077. program.properties.privateData[token] =
  24078. this.readNumberArray()[0];
  24079. break;
  24080. case 'BlueShift':
  24081. case 'lenIV':
  24082. case 'BlueFuzz':
  24083. case 'BlueScale':
  24084. case 'LanguageGroup':
  24085. case 'ExpansionFactor':
  24086. program.properties.privateData[token] = this.readNumber();
  24087. break;
  24088. case 'ForceBold':
  24089. program.properties.privateData[token] = this.readBoolean();
  24090. break;
  24091. }
  24092. }
  24093. for (var i = 0; i < charstrings.length; i++) {
  24094. glyph = charstrings[i].glyph;
  24095. encoded = charstrings[i].encoded;
  24096. var charString = new Type1CharString();
  24097. var error = charString.convert(encoded, subrs);
  24098. var output = charString.output;
  24099. if (error) {
  24100. // It seems when FreeType encounters an error while evaluating a glyph
  24101. // that it completely ignores the glyph so we'll mimic that behaviour
  24102. // here and put an endchar to make the validator happy.
  24103. output = [14];
  24104. }
  24105. program.charstrings.push({
  24106. glyphName: glyph,
  24107. charstring: output,
  24108. width: charString.width,
  24109. lsb: charString.lsb,
  24110. seac: charString.seac
  24111. });
  24112. }
  24113. return program;
  24114. },
  24115. extractFontHeader: function Type1Parser_extractFontHeader(properties) {
  24116. var token;
  24117. while ((token = this.getToken()) !== null) {
  24118. if (token !== '/') {
  24119. continue;
  24120. }
  24121. token = this.getToken();
  24122. switch (token) {
  24123. case 'FontMatrix':
  24124. var matrix = this.readNumberArray();
  24125. properties.fontMatrix = matrix;
  24126. break;
  24127. case 'Encoding':
  24128. var encodingArg = this.getToken();
  24129. var encoding;
  24130. if (!/^\d+$/.test(encodingArg)) {
  24131. // encoding name is specified
  24132. encoding = Encodings[encodingArg];
  24133. } else {
  24134. encoding = [];
  24135. var size = parseInt(encodingArg, 10) | 0;
  24136. this.getToken(); // read in 'array'
  24137. for (var j = 0; j < size; j++) {
  24138. token = this.getToken();
  24139. // skipping till first dup or def (e.g. ignoring for statement)
  24140. while (token !== 'dup' && token !== 'def') {
  24141. token = this.getToken();
  24142. if (token === null) {
  24143. return; // invalid header
  24144. }
  24145. }
  24146. if (token === 'def') {
  24147. break; // read all array data
  24148. }
  24149. var index = this.readInt();
  24150. this.getToken(); // read in '/'
  24151. var glyph = this.getToken();
  24152. encoding[index] = glyph;
  24153. this.getToken(); // read the in 'put'
  24154. }
  24155. }
  24156. properties.builtInEncoding = encoding;
  24157. break;
  24158. case 'FontBBox':
  24159. var fontBBox = this.readNumberArray();
  24160. // adjusting ascent/descent
  24161. properties.ascent = fontBBox[3];
  24162. properties.descent = fontBBox[1];
  24163. properties.ascentScaled = true;
  24164. break;
  24165. }
  24166. }
  24167. }
  24168. };
  24169. return Type1Parser;
  24170. })();
  24171. /**
  24172. * The CFF class takes a Type1 file and wrap it into a
  24173. * 'Compact Font Format' which itself embed Type2 charstrings.
  24174. */
  24175. var CFFStandardStrings = [
  24176. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  24177. 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
  24178. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
  24179. 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  24180. 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  24181. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  24182. 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum',
  24183. 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  24184. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
  24185. 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
  24186. 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  24187. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  24188. 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
  24189. 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase',
  24190. 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown',
  24191. 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent',
  24192. 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash',
  24193. 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae',
  24194. 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior',
  24195. 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn',
  24196. 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters',
  24197. 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior',
  24198. 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring',
  24199. 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave',
  24200. 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute',
  24201. 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute',
  24202. 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron',
  24203. 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde',
  24204. 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute',
  24205. 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex',
  24206. 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex',
  24207. 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall',
  24208. 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall',
  24209. 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  24210. 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle',
  24211. 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
  24212. 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior',
  24213. 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior',
  24214. 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior',
  24215. 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  24216. 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior',
  24217. 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall',
  24218. 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
  24219. 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
  24220. 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  24221. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
  24222. 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
  24223. 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
  24224. 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior',
  24225. 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth',
  24226. 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
  24227. 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
  24228. 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior',
  24229. 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior',
  24230. 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
  24231. 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
  24232. 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall',
  24233. 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
  24234. 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
  24235. 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall',
  24236. 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall',
  24237. 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
  24238. 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall',
  24239. 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003',
  24240. 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'
  24241. ];
  24242. // Type1Font is also a CIDFontType0.
  24243. var Type1Font = function Type1Font(name, file, properties) {
  24244. // Some bad generators embed pfb file as is, we have to strip 6-byte headers.
  24245. // Also, length1 and length2 might be off by 6 bytes as well.
  24246. // http://www.math.ubc.ca/~cass/piscript/type1.pdf
  24247. var PFB_HEADER_SIZE = 6;
  24248. var headerBlockLength = properties.length1;
  24249. var eexecBlockLength = properties.length2;
  24250. var pfbHeader = file.peekBytes(PFB_HEADER_SIZE);
  24251. var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01;
  24252. if (pfbHeaderPresent) {
  24253. file.skip(PFB_HEADER_SIZE);
  24254. headerBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
  24255. (pfbHeader[3] << 8) | pfbHeader[2];
  24256. }
  24257. // Get the data block containing glyphs and subrs informations
  24258. var headerBlock = new Stream(file.getBytes(headerBlockLength));
  24259. var headerBlockParser = new Type1Parser(headerBlock);
  24260. headerBlockParser.extractFontHeader(properties);
  24261. if (pfbHeaderPresent) {
  24262. pfbHeader = file.getBytes(PFB_HEADER_SIZE);
  24263. eexecBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
  24264. (pfbHeader[3] << 8) | pfbHeader[2];
  24265. }
  24266. // Decrypt the data blocks and retrieve it's content
  24267. var eexecBlock = new Stream(file.getBytes(eexecBlockLength));
  24268. var eexecBlockParser = new Type1Parser(eexecBlock, true);
  24269. var data = eexecBlockParser.extractFontProgram();
  24270. for (var info in data.properties) {
  24271. properties[info] = data.properties[info];
  24272. }
  24273. var charstrings = data.charstrings;
  24274. var type2Charstrings = this.getType2Charstrings(charstrings);
  24275. var subrs = this.getType2Subrs(data.subrs);
  24276. this.charstrings = charstrings;
  24277. this.data = this.wrap(name, type2Charstrings, this.charstrings,
  24278. subrs, properties);
  24279. this.seacs = this.getSeacs(data.charstrings);
  24280. };
  24281. Type1Font.prototype = {
  24282. get numGlyphs() {
  24283. return this.charstrings.length + 1;
  24284. },
  24285. getCharset: function Type1Font_getCharset() {
  24286. var charset = ['.notdef'];
  24287. var charstrings = this.charstrings;
  24288. for (var glyphId = 0; glyphId < charstrings.length; glyphId++) {
  24289. charset.push(charstrings[glyphId].glyphName);
  24290. }
  24291. return charset;
  24292. },
  24293. getGlyphMapping: function Type1Font_getGlyphMapping(properties) {
  24294. var charstrings = this.charstrings;
  24295. var glyphNames = ['.notdef'], glyphId;
  24296. for (glyphId = 0; glyphId < charstrings.length; glyphId++) {
  24297. glyphNames.push(charstrings[glyphId].glyphName);
  24298. }
  24299. var encoding = properties.builtInEncoding;
  24300. if (encoding) {
  24301. var builtInEncoding = {};
  24302. for (var charCode in encoding) {
  24303. glyphId = glyphNames.indexOf(encoding[charCode]);
  24304. if (glyphId >= 0) {
  24305. builtInEncoding[charCode] = glyphId;
  24306. }
  24307. }
  24308. }
  24309. return type1FontGlyphMapping(properties, builtInEncoding, glyphNames);
  24310. },
  24311. getSeacs: function Type1Font_getSeacs(charstrings) {
  24312. var i, ii;
  24313. var seacMap = [];
  24314. for (i = 0, ii = charstrings.length; i < ii; i++) {
  24315. var charstring = charstrings[i];
  24316. if (charstring.seac) {
  24317. // Offset by 1 for .notdef
  24318. seacMap[i + 1] = charstring.seac;
  24319. }
  24320. }
  24321. return seacMap;
  24322. },
  24323. getType2Charstrings: function Type1Font_getType2Charstrings(
  24324. type1Charstrings) {
  24325. var type2Charstrings = [];
  24326. for (var i = 0, ii = type1Charstrings.length; i < ii; i++) {
  24327. type2Charstrings.push(type1Charstrings[i].charstring);
  24328. }
  24329. return type2Charstrings;
  24330. },
  24331. getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) {
  24332. var bias = 0;
  24333. var count = type1Subrs.length;
  24334. if (count < 1133) {
  24335. bias = 107;
  24336. } else if (count < 33769) {
  24337. bias = 1131;
  24338. } else {
  24339. bias = 32768;
  24340. }
  24341. // Add a bunch of empty subrs to deal with the Type2 bias
  24342. var type2Subrs = [];
  24343. var i;
  24344. for (i = 0; i < bias; i++) {
  24345. type2Subrs.push([0x0B]);
  24346. }
  24347. for (i = 0; i < count; i++) {
  24348. type2Subrs.push(type1Subrs[i]);
  24349. }
  24350. return type2Subrs;
  24351. },
  24352. wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) {
  24353. var cff = new CFF();
  24354. cff.header = new CFFHeader(1, 0, 4, 4);
  24355. cff.names = [name];
  24356. var topDict = new CFFTopDict();
  24357. // CFF strings IDs 0...390 are predefined names, so refering
  24358. // to entries in our own String INDEX starts at SID 391.
  24359. topDict.setByName('version', 391);
  24360. topDict.setByName('Notice', 392);
  24361. topDict.setByName('FullName', 393);
  24362. topDict.setByName('FamilyName', 394);
  24363. topDict.setByName('Weight', 395);
  24364. topDict.setByName('Encoding', null); // placeholder
  24365. topDict.setByName('FontMatrix', properties.fontMatrix);
  24366. topDict.setByName('FontBBox', properties.bbox);
  24367. topDict.setByName('charset', null); // placeholder
  24368. topDict.setByName('CharStrings', null); // placeholder
  24369. topDict.setByName('Private', null); // placeholder
  24370. cff.topDict = topDict;
  24371. var strings = new CFFStrings();
  24372. strings.add('Version 0.11'); // Version
  24373. strings.add('See original notice'); // Notice
  24374. strings.add(name); // FullName
  24375. strings.add(name); // FamilyName
  24376. strings.add('Medium'); // Weight
  24377. cff.strings = strings;
  24378. cff.globalSubrIndex = new CFFIndex();
  24379. var count = glyphs.length;
  24380. var charsetArray = [0];
  24381. var i, ii;
  24382. for (i = 0; i < count; i++) {
  24383. var index = CFFStandardStrings.indexOf(charstrings[i].glyphName);
  24384. // TODO: Insert the string and correctly map it. Previously it was
  24385. // thought mapping names that aren't in the standard strings to .notdef
  24386. // was fine, however in issue818 when mapping them all to .notdef the
  24387. // adieresis glyph no longer worked.
  24388. if (index === -1) {
  24389. index = 0;
  24390. }
  24391. charsetArray.push((index >> 8) & 0xff, index & 0xff);
  24392. }
  24393. cff.charset = new CFFCharset(false, 0, [], charsetArray);
  24394. var charStringsIndex = new CFFIndex();
  24395. charStringsIndex.add([0x8B, 0x0E]); // .notdef
  24396. for (i = 0; i < count; i++) {
  24397. charStringsIndex.add(glyphs[i]);
  24398. }
  24399. cff.charStrings = charStringsIndex;
  24400. var privateDict = new CFFPrivateDict();
  24401. privateDict.setByName('Subrs', null); // placeholder
  24402. var fields = [
  24403. 'BlueValues',
  24404. 'OtherBlues',
  24405. 'FamilyBlues',
  24406. 'FamilyOtherBlues',
  24407. 'StemSnapH',
  24408. 'StemSnapV',
  24409. 'BlueShift',
  24410. 'BlueFuzz',
  24411. 'BlueScale',
  24412. 'LanguageGroup',
  24413. 'ExpansionFactor',
  24414. 'ForceBold',
  24415. 'StdHW',
  24416. 'StdVW'
  24417. ];
  24418. for (i = 0, ii = fields.length; i < ii; i++) {
  24419. var field = fields[i];
  24420. if (!properties.privateData.hasOwnProperty(field)) {
  24421. continue;
  24422. }
  24423. var value = properties.privateData[field];
  24424. if (isArray(value)) {
  24425. // All of the private dictionary array data in CFF must be stored as
  24426. // "delta-encoded" numbers.
  24427. for (var j = value.length - 1; j > 0; j--) {
  24428. value[j] -= value[j - 1]; // ... difference from previous value
  24429. }
  24430. }
  24431. privateDict.setByName(field, value);
  24432. }
  24433. cff.topDict.privateDict = privateDict;
  24434. var subrIndex = new CFFIndex();
  24435. for (i = 0, ii = subrs.length; i < ii; i++) {
  24436. subrIndex.add(subrs[i]);
  24437. }
  24438. privateDict.subrsIndex = subrIndex;
  24439. var compiler = new CFFCompiler(cff);
  24440. return compiler.compile();
  24441. }
  24442. };
  24443. var CFFFont = (function CFFFontClosure() {
  24444. function CFFFont(file, properties) {
  24445. this.properties = properties;
  24446. var parser = new CFFParser(file, properties);
  24447. this.cff = parser.parse();
  24448. var compiler = new CFFCompiler(this.cff);
  24449. this.seacs = this.cff.seacs;
  24450. try {
  24451. this.data = compiler.compile();
  24452. } catch (e) {
  24453. warn('Failed to compile font ' + properties.loadedName);
  24454. // There may have just been an issue with the compiler, set the data
  24455. // anyway and hope the font loaded.
  24456. this.data = file;
  24457. }
  24458. }
  24459. CFFFont.prototype = {
  24460. get numGlyphs() {
  24461. return this.cff.charStrings.count;
  24462. },
  24463. getCharset: function CFFFont_getCharset() {
  24464. return this.cff.charset.charset;
  24465. },
  24466. getGlyphMapping: function CFFFont_getGlyphMapping() {
  24467. var cff = this.cff;
  24468. var properties = this.properties;
  24469. var charsets = cff.charset.charset;
  24470. var charCodeToGlyphId;
  24471. var glyphId;
  24472. if (properties.composite) {
  24473. charCodeToGlyphId = Object.create(null);
  24474. if (cff.isCIDFont) {
  24475. // If the font is actually a CID font then we should use the charset
  24476. // to map CIDs to GIDs.
  24477. for (glyphId = 0; glyphId < charsets.length; glyphId++) {
  24478. var cid = charsets[glyphId];
  24479. var charCode = properties.cMap.charCodeOf(cid);
  24480. charCodeToGlyphId[charCode] = glyphId;
  24481. }
  24482. } else {
  24483. // If it is NOT actually a CID font then CIDs should be mapped
  24484. // directly to GIDs.
  24485. for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {
  24486. charCodeToGlyphId[glyphId] = glyphId;
  24487. }
  24488. }
  24489. return charCodeToGlyphId;
  24490. }
  24491. var encoding = cff.encoding ? cff.encoding.encoding : null;
  24492. charCodeToGlyphId = type1FontGlyphMapping(properties, encoding, charsets);
  24493. return charCodeToGlyphId;
  24494. }
  24495. };
  24496. return CFFFont;
  24497. })();
  24498. var CFFParser = (function CFFParserClosure() {
  24499. var CharstringValidationData = [
  24500. null,
  24501. { id: 'hstem', min: 2, stackClearing: true, stem: true },
  24502. null,
  24503. { id: 'vstem', min: 2, stackClearing: true, stem: true },
  24504. { id: 'vmoveto', min: 1, stackClearing: true },
  24505. { id: 'rlineto', min: 2, resetStack: true },
  24506. { id: 'hlineto', min: 1, resetStack: true },
  24507. { id: 'vlineto', min: 1, resetStack: true },
  24508. { id: 'rrcurveto', min: 6, resetStack: true },
  24509. null,
  24510. { id: 'callsubr', min: 1, undefStack: true },
  24511. { id: 'return', min: 0, undefStack: true },
  24512. null, // 12
  24513. null,
  24514. { id: 'endchar', min: 0, stackClearing: true },
  24515. null,
  24516. null,
  24517. null,
  24518. { id: 'hstemhm', min: 2, stackClearing: true, stem: true },
  24519. { id: 'hintmask', min: 0, stackClearing: true },
  24520. { id: 'cntrmask', min: 0, stackClearing: true },
  24521. { id: 'rmoveto', min: 2, stackClearing: true },
  24522. { id: 'hmoveto', min: 1, stackClearing: true },
  24523. { id: 'vstemhm', min: 2, stackClearing: true, stem: true },
  24524. { id: 'rcurveline', min: 8, resetStack: true },
  24525. { id: 'rlinecurve', min: 8, resetStack: true },
  24526. { id: 'vvcurveto', min: 4, resetStack: true },
  24527. { id: 'hhcurveto', min: 4, resetStack: true },
  24528. null, // shortint
  24529. { id: 'callgsubr', min: 1, undefStack: true },
  24530. { id: 'vhcurveto', min: 4, resetStack: true },
  24531. { id: 'hvcurveto', min: 4, resetStack: true }
  24532. ];
  24533. var CharstringValidationData12 = [
  24534. null,
  24535. null,
  24536. null,
  24537. { id: 'and', min: 2, stackDelta: -1 },
  24538. { id: 'or', min: 2, stackDelta: -1 },
  24539. { id: 'not', min: 1, stackDelta: 0 },
  24540. null,
  24541. null,
  24542. null,
  24543. { id: 'abs', min: 1, stackDelta: 0 },
  24544. { id: 'add', min: 2, stackDelta: -1,
  24545. stackFn: function stack_div(stack, index) {
  24546. stack[index - 2] = stack[index - 2] + stack[index - 1];
  24547. }
  24548. },
  24549. { id: 'sub', min: 2, stackDelta: -1,
  24550. stackFn: function stack_div(stack, index) {
  24551. stack[index - 2] = stack[index - 2] - stack[index - 1];
  24552. }
  24553. },
  24554. { id: 'div', min: 2, stackDelta: -1,
  24555. stackFn: function stack_div(stack, index) {
  24556. stack[index - 2] = stack[index - 2] / stack[index - 1];
  24557. }
  24558. },
  24559. null,
  24560. { id: 'neg', min: 1, stackDelta: 0,
  24561. stackFn: function stack_div(stack, index) {
  24562. stack[index - 1] = -stack[index - 1];
  24563. }
  24564. },
  24565. { id: 'eq', min: 2, stackDelta: -1 },
  24566. null,
  24567. null,
  24568. { id: 'drop', min: 1, stackDelta: -1 },
  24569. null,
  24570. { id: 'put', min: 2, stackDelta: -2 },
  24571. { id: 'get', min: 1, stackDelta: 0 },
  24572. { id: 'ifelse', min: 4, stackDelta: -3 },
  24573. { id: 'random', min: 0, stackDelta: 1 },
  24574. { id: 'mul', min: 2, stackDelta: -1,
  24575. stackFn: function stack_div(stack, index) {
  24576. stack[index - 2] = stack[index - 2] * stack[index - 1];
  24577. }
  24578. },
  24579. null,
  24580. { id: 'sqrt', min: 1, stackDelta: 0 },
  24581. { id: 'dup', min: 1, stackDelta: 1 },
  24582. { id: 'exch', min: 2, stackDelta: 0 },
  24583. { id: 'index', min: 2, stackDelta: 0 },
  24584. { id: 'roll', min: 3, stackDelta: -2 },
  24585. null,
  24586. null,
  24587. null,
  24588. { id: 'hflex', min: 7, resetStack: true },
  24589. { id: 'flex', min: 13, resetStack: true },
  24590. { id: 'hflex1', min: 9, resetStack: true },
  24591. { id: 'flex1', min: 11, resetStack: true }
  24592. ];
  24593. function CFFParser(file, properties) {
  24594. this.bytes = file.getBytes();
  24595. this.properties = properties;
  24596. }
  24597. CFFParser.prototype = {
  24598. parse: function CFFParser_parse() {
  24599. var properties = this.properties;
  24600. var cff = new CFF();
  24601. this.cff = cff;
  24602. // The first five sections must be in order, all the others are reached
  24603. // via offsets contained in one of the below.
  24604. var header = this.parseHeader();
  24605. var nameIndex = this.parseIndex(header.endPos);
  24606. var topDictIndex = this.parseIndex(nameIndex.endPos);
  24607. var stringIndex = this.parseIndex(topDictIndex.endPos);
  24608. var globalSubrIndex = this.parseIndex(stringIndex.endPos);
  24609. var topDictParsed = this.parseDict(topDictIndex.obj.get(0));
  24610. var topDict = this.createDict(CFFTopDict, topDictParsed, cff.strings);
  24611. cff.header = header.obj;
  24612. cff.names = this.parseNameIndex(nameIndex.obj);
  24613. cff.strings = this.parseStringIndex(stringIndex.obj);
  24614. cff.topDict = topDict;
  24615. cff.globalSubrIndex = globalSubrIndex.obj;
  24616. this.parsePrivateDict(cff.topDict);
  24617. cff.isCIDFont = topDict.hasName('ROS');
  24618. var charStringOffset = topDict.getByName('CharStrings');
  24619. var charStringsAndSeacs = this.parseCharStrings(charStringOffset);
  24620. cff.charStrings = charStringsAndSeacs.charStrings;
  24621. cff.seacs = charStringsAndSeacs.seacs;
  24622. cff.widths = charStringsAndSeacs.widths;
  24623. var fontMatrix = topDict.getByName('FontMatrix');
  24624. if (fontMatrix) {
  24625. properties.fontMatrix = fontMatrix;
  24626. }
  24627. var fontBBox = topDict.getByName('FontBBox');
  24628. if (fontBBox) {
  24629. // adjusting ascent/descent
  24630. properties.ascent = fontBBox[3];
  24631. properties.descent = fontBBox[1];
  24632. properties.ascentScaled = true;
  24633. }
  24634. var charset, encoding;
  24635. if (cff.isCIDFont) {
  24636. var fdArrayIndex = this.parseIndex(topDict.getByName('FDArray')).obj;
  24637. for (var i = 0, ii = fdArrayIndex.count; i < ii; ++i) {
  24638. var dictRaw = fdArrayIndex.get(i);
  24639. var fontDict = this.createDict(CFFTopDict, this.parseDict(dictRaw),
  24640. cff.strings);
  24641. this.parsePrivateDict(fontDict);
  24642. cff.fdArray.push(fontDict);
  24643. }
  24644. // cid fonts don't have an encoding
  24645. encoding = null;
  24646. charset = this.parseCharsets(topDict.getByName('charset'),
  24647. cff.charStrings.count, cff.strings, true);
  24648. cff.fdSelect = this.parseFDSelect(topDict.getByName('FDSelect'),
  24649. cff.charStrings.count);
  24650. } else {
  24651. charset = this.parseCharsets(topDict.getByName('charset'),
  24652. cff.charStrings.count, cff.strings, false);
  24653. encoding = this.parseEncoding(topDict.getByName('Encoding'),
  24654. properties,
  24655. cff.strings, charset.charset);
  24656. }
  24657. cff.charset = charset;
  24658. cff.encoding = encoding;
  24659. return cff;
  24660. },
  24661. parseHeader: function CFFParser_parseHeader() {
  24662. var bytes = this.bytes;
  24663. var bytesLength = bytes.length;
  24664. var offset = 0;
  24665. // Prevent an infinite loop, by checking that the offset is within the
  24666. // bounds of the bytes array. Necessary in empty, or invalid, font files.
  24667. while (offset < bytesLength && bytes[offset] !== 1) {
  24668. ++offset;
  24669. }
  24670. if (offset >= bytesLength) {
  24671. error('Invalid CFF header');
  24672. } else if (offset !== 0) {
  24673. info('cff data is shifted');
  24674. bytes = bytes.subarray(offset);
  24675. this.bytes = bytes;
  24676. }
  24677. var major = bytes[0];
  24678. var minor = bytes[1];
  24679. var hdrSize = bytes[2];
  24680. var offSize = bytes[3];
  24681. var header = new CFFHeader(major, minor, hdrSize, offSize);
  24682. return { obj: header, endPos: hdrSize };
  24683. },
  24684. parseDict: function CFFParser_parseDict(dict) {
  24685. var pos = 0;
  24686. function parseOperand() {
  24687. var value = dict[pos++];
  24688. if (value === 30) {
  24689. return parseFloatOperand(pos);
  24690. } else if (value === 28) {
  24691. value = dict[pos++];
  24692. value = ((value << 24) | (dict[pos++] << 16)) >> 16;
  24693. return value;
  24694. } else if (value === 29) {
  24695. value = dict[pos++];
  24696. value = (value << 8) | dict[pos++];
  24697. value = (value << 8) | dict[pos++];
  24698. value = (value << 8) | dict[pos++];
  24699. return value;
  24700. } else if (value >= 32 && value <= 246) {
  24701. return value - 139;
  24702. } else if (value >= 247 && value <= 250) {
  24703. return ((value - 247) * 256) + dict[pos++] + 108;
  24704. } else if (value >= 251 && value <= 254) {
  24705. return -((value - 251) * 256) - dict[pos++] - 108;
  24706. } else {
  24707. error('255 is not a valid DICT command');
  24708. }
  24709. return -1;
  24710. }
  24711. function parseFloatOperand() {
  24712. var str = '';
  24713. var eof = 15;
  24714. var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
  24715. '9', '.', 'E', 'E-', null, '-'];
  24716. var length = dict.length;
  24717. while (pos < length) {
  24718. var b = dict[pos++];
  24719. var b1 = b >> 4;
  24720. var b2 = b & 15;
  24721. if (b1 === eof) {
  24722. break;
  24723. }
  24724. str += lookup[b1];
  24725. if (b2 === eof) {
  24726. break;
  24727. }
  24728. str += lookup[b2];
  24729. }
  24730. return parseFloat(str);
  24731. }
  24732. var operands = [];
  24733. var entries = [];
  24734. pos = 0;
  24735. var end = dict.length;
  24736. while (pos < end) {
  24737. var b = dict[pos];
  24738. if (b <= 21) {
  24739. if (b === 12) {
  24740. b = (b << 8) | dict[++pos];
  24741. }
  24742. entries.push([b, operands]);
  24743. operands = [];
  24744. ++pos;
  24745. } else {
  24746. operands.push(parseOperand());
  24747. }
  24748. }
  24749. return entries;
  24750. },
  24751. parseIndex: function CFFParser_parseIndex(pos) {
  24752. var cffIndex = new CFFIndex();
  24753. var bytes = this.bytes;
  24754. var count = (bytes[pos++] << 8) | bytes[pos++];
  24755. var offsets = [];
  24756. var end = pos;
  24757. var i, ii;
  24758. if (count !== 0) {
  24759. var offsetSize = bytes[pos++];
  24760. // add 1 for offset to determine size of last object
  24761. var startPos = pos + ((count + 1) * offsetSize) - 1;
  24762. for (i = 0, ii = count + 1; i < ii; ++i) {
  24763. var offset = 0;
  24764. for (var j = 0; j < offsetSize; ++j) {
  24765. offset <<= 8;
  24766. offset += bytes[pos++];
  24767. }
  24768. offsets.push(startPos + offset);
  24769. }
  24770. end = offsets[count];
  24771. }
  24772. for (i = 0, ii = offsets.length - 1; i < ii; ++i) {
  24773. var offsetStart = offsets[i];
  24774. var offsetEnd = offsets[i + 1];
  24775. cffIndex.add(bytes.subarray(offsetStart, offsetEnd));
  24776. }
  24777. return {obj: cffIndex, endPos: end};
  24778. },
  24779. parseNameIndex: function CFFParser_parseNameIndex(index) {
  24780. var names = [];
  24781. for (var i = 0, ii = index.count; i < ii; ++i) {
  24782. var name = index.get(i);
  24783. // OTS doesn't allow names to be over 127 characters.
  24784. var length = Math.min(name.length, 127);
  24785. var data = [];
  24786. // OTS also only permits certain characters in the name.
  24787. for (var j = 0; j < length; ++j) {
  24788. var c = name[j];
  24789. if (j === 0 && c === 0) {
  24790. data[j] = c;
  24791. continue;
  24792. }
  24793. if ((c < 33 || c > 126) || c === 91 /* [ */ || c === 93 /* ] */ ||
  24794. c === 40 /* ( */ || c === 41 /* ) */ || c === 123 /* { */ ||
  24795. c === 125 /* } */ || c === 60 /* < */ || c === 62 /* > */ ||
  24796. c === 47 /* / */ || c === 37 /* % */ || c === 35 /* # */) {
  24797. data[j] = 95;
  24798. continue;
  24799. }
  24800. data[j] = c;
  24801. }
  24802. names.push(bytesToString(data));
  24803. }
  24804. return names;
  24805. },
  24806. parseStringIndex: function CFFParser_parseStringIndex(index) {
  24807. var strings = new CFFStrings();
  24808. for (var i = 0, ii = index.count; i < ii; ++i) {
  24809. var data = index.get(i);
  24810. strings.add(bytesToString(data));
  24811. }
  24812. return strings;
  24813. },
  24814. createDict: function CFFParser_createDict(Type, dict, strings) {
  24815. var cffDict = new Type(strings);
  24816. for (var i = 0, ii = dict.length; i < ii; ++i) {
  24817. var pair = dict[i];
  24818. var key = pair[0];
  24819. var value = pair[1];
  24820. cffDict.setByKey(key, value);
  24821. }
  24822. return cffDict;
  24823. },
  24824. parseCharStrings: function CFFParser_parseCharStrings(charStringOffset) {
  24825. var charStrings = this.parseIndex(charStringOffset).obj;
  24826. var seacs = [];
  24827. var widths = [];
  24828. var count = charStrings.count;
  24829. for (var i = 0; i < count; i++) {
  24830. var charstring = charStrings.get(i);
  24831. var stackSize = 0;
  24832. var stack = [];
  24833. var undefStack = true;
  24834. var hints = 0;
  24835. var valid = true;
  24836. var data = charstring;
  24837. var length = data.length;
  24838. var firstStackClearing = true;
  24839. for (var j = 0; j < length;) {
  24840. var value = data[j++];
  24841. var validationCommand = null;
  24842. if (value === 12) {
  24843. var q = data[j++];
  24844. if (q === 0) {
  24845. // The CFF specification state that the 'dotsection' command
  24846. // (12, 0) is deprecated and treated as a no-op, but all Type2
  24847. // charstrings processors should support them. Unfortunately
  24848. // the font sanitizer don't. As a workaround the sequence (12, 0)
  24849. // is replaced by a useless (0, hmoveto).
  24850. data[j - 2] = 139;
  24851. data[j - 1] = 22;
  24852. stackSize = 0;
  24853. } else {
  24854. validationCommand = CharstringValidationData12[q];
  24855. }
  24856. } else if (value === 28) { // number (16 bit)
  24857. stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16)) >> 16;
  24858. j += 2;
  24859. stackSize++;
  24860. } else if (value === 14) {
  24861. if (stackSize >= 4) {
  24862. stackSize -= 4;
  24863. if (SEAC_ANALYSIS_ENABLED) {
  24864. seacs[i] = stack.slice(stackSize, stackSize + 4);
  24865. valid = false;
  24866. }
  24867. }
  24868. validationCommand = CharstringValidationData[value];
  24869. } else if (value >= 32 && value <= 246) { // number
  24870. stack[stackSize] = value - 139;
  24871. stackSize++;
  24872. } else if (value >= 247 && value <= 254) { // number (+1 bytes)
  24873. stack[stackSize] = (value < 251 ?
  24874. ((value - 247) << 8) + data[j] + 108 :
  24875. -((value - 251) << 8) - data[j] - 108);
  24876. j++;
  24877. stackSize++;
  24878. } else if (value === 255) { // number (32 bit)
  24879. stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16) |
  24880. (data[j + 2] << 8) | data[j + 3]) / 65536;
  24881. j += 4;
  24882. stackSize++;
  24883. } else if (value === 19 || value === 20) {
  24884. hints += stackSize >> 1;
  24885. j += (hints + 7) >> 3; // skipping right amount of hints flag data
  24886. stackSize %= 2;
  24887. validationCommand = CharstringValidationData[value];
  24888. } else {
  24889. validationCommand = CharstringValidationData[value];
  24890. }
  24891. if (validationCommand) {
  24892. if (validationCommand.stem) {
  24893. hints += stackSize >> 1;
  24894. }
  24895. if ('min' in validationCommand) {
  24896. if (!undefStack && stackSize < validationCommand.min) {
  24897. warn('Not enough parameters for ' + validationCommand.id +
  24898. '; actual: ' + stackSize +
  24899. ', expected: ' + validationCommand.min);
  24900. valid = false;
  24901. break;
  24902. }
  24903. }
  24904. if (firstStackClearing && validationCommand.stackClearing) {
  24905. firstStackClearing = false;
  24906. // the optional character width can be found before the first
  24907. // stack-clearing command arguments
  24908. stackSize -= validationCommand.min;
  24909. if (stackSize >= 2 && validationCommand.stem) {
  24910. // there are even amount of arguments for stem commands
  24911. stackSize %= 2;
  24912. } else if (stackSize > 1) {
  24913. warn('Found too many parameters for stack-clearing command');
  24914. }
  24915. if (stackSize > 0 && stack[stackSize - 1] >= 0) {
  24916. widths[i] = stack[stackSize - 1];
  24917. }
  24918. }
  24919. if ('stackDelta' in validationCommand) {
  24920. if ('stackFn' in validationCommand) {
  24921. validationCommand.stackFn(stack, stackSize);
  24922. }
  24923. stackSize += validationCommand.stackDelta;
  24924. } else if (validationCommand.stackClearing) {
  24925. stackSize = 0;
  24926. } else if (validationCommand.resetStack) {
  24927. stackSize = 0;
  24928. undefStack = false;
  24929. } else if (validationCommand.undefStack) {
  24930. stackSize = 0;
  24931. undefStack = true;
  24932. firstStackClearing = false;
  24933. }
  24934. }
  24935. }
  24936. if (!valid) {
  24937. // resetting invalid charstring to single 'endchar'
  24938. charStrings.set(i, new Uint8Array([14]));
  24939. }
  24940. }
  24941. return { charStrings: charStrings, seacs: seacs, widths: widths };
  24942. },
  24943. emptyPrivateDictionary:
  24944. function CFFParser_emptyPrivateDictionary(parentDict) {
  24945. var privateDict = this.createDict(CFFPrivateDict, [],
  24946. parentDict.strings);
  24947. parentDict.setByKey(18, [0, 0]);
  24948. parentDict.privateDict = privateDict;
  24949. },
  24950. parsePrivateDict: function CFFParser_parsePrivateDict(parentDict) {
  24951. // no private dict, do nothing
  24952. if (!parentDict.hasName('Private')) {
  24953. this.emptyPrivateDictionary(parentDict);
  24954. return;
  24955. }
  24956. var privateOffset = parentDict.getByName('Private');
  24957. // make sure the params are formatted correctly
  24958. if (!isArray(privateOffset) || privateOffset.length !== 2) {
  24959. parentDict.removeByName('Private');
  24960. return;
  24961. }
  24962. var size = privateOffset[0];
  24963. var offset = privateOffset[1];
  24964. // remove empty dicts or ones that refer to invalid location
  24965. if (size === 0 || offset >= this.bytes.length) {
  24966. this.emptyPrivateDictionary(parentDict);
  24967. return;
  24968. }
  24969. var privateDictEnd = offset + size;
  24970. var dictData = this.bytes.subarray(offset, privateDictEnd);
  24971. var dict = this.parseDict(dictData);
  24972. var privateDict = this.createDict(CFFPrivateDict, dict,
  24973. parentDict.strings);
  24974. parentDict.privateDict = privateDict;
  24975. // Parse the Subrs index also since it's relative to the private dict.
  24976. if (!privateDict.getByName('Subrs')) {
  24977. return;
  24978. }
  24979. var subrsOffset = privateDict.getByName('Subrs');
  24980. var relativeOffset = offset + subrsOffset;
  24981. // Validate the offset.
  24982. if (subrsOffset === 0 || relativeOffset >= this.bytes.length) {
  24983. this.emptyPrivateDictionary(parentDict);
  24984. return;
  24985. }
  24986. var subrsIndex = this.parseIndex(relativeOffset);
  24987. privateDict.subrsIndex = subrsIndex.obj;
  24988. },
  24989. parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) {
  24990. if (pos === 0) {
  24991. return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE,
  24992. ISOAdobeCharset);
  24993. } else if (pos === 1) {
  24994. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT,
  24995. ExpertCharset);
  24996. } else if (pos === 2) {
  24997. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET,
  24998. ExpertSubsetCharset);
  24999. }
  25000. var bytes = this.bytes;
  25001. var start = pos;
  25002. var format = bytes[pos++];
  25003. var charset = ['.notdef'];
  25004. var id, count, i;
  25005. // subtract 1 for the .notdef glyph
  25006. length -= 1;
  25007. switch (format) {
  25008. case 0:
  25009. for (i = 0; i < length; i++) {
  25010. id = (bytes[pos++] << 8) | bytes[pos++];
  25011. charset.push(cid ? id : strings.get(id));
  25012. }
  25013. break;
  25014. case 1:
  25015. while (charset.length <= length) {
  25016. id = (bytes[pos++] << 8) | bytes[pos++];
  25017. count = bytes[pos++];
  25018. for (i = 0; i <= count; i++) {
  25019. charset.push(cid ? id++ : strings.get(id++));
  25020. }
  25021. }
  25022. break;
  25023. case 2:
  25024. while (charset.length <= length) {
  25025. id = (bytes[pos++] << 8) | bytes[pos++];
  25026. count = (bytes[pos++] << 8) | bytes[pos++];
  25027. for (i = 0; i <= count; i++) {
  25028. charset.push(cid ? id++ : strings.get(id++));
  25029. }
  25030. }
  25031. break;
  25032. default:
  25033. error('Unknown charset format');
  25034. }
  25035. // Raw won't be needed if we actually compile the charset.
  25036. var end = pos;
  25037. var raw = bytes.subarray(start, end);
  25038. return new CFFCharset(false, format, charset, raw);
  25039. },
  25040. parseEncoding: function CFFParser_parseEncoding(pos,
  25041. properties,
  25042. strings,
  25043. charset) {
  25044. var encoding = {};
  25045. var bytes = this.bytes;
  25046. var predefined = false;
  25047. var hasSupplement = false;
  25048. var format, i, ii;
  25049. var raw = null;
  25050. function readSupplement() {
  25051. var supplementsCount = bytes[pos++];
  25052. for (i = 0; i < supplementsCount; i++) {
  25053. var code = bytes[pos++];
  25054. var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);
  25055. encoding[code] = charset.indexOf(strings.get(sid));
  25056. }
  25057. }
  25058. if (pos === 0 || pos === 1) {
  25059. predefined = true;
  25060. format = pos;
  25061. var baseEncoding = pos ? Encodings.ExpertEncoding :
  25062. Encodings.StandardEncoding;
  25063. for (i = 0, ii = charset.length; i < ii; i++) {
  25064. var index = baseEncoding.indexOf(charset[i]);
  25065. if (index !== -1) {
  25066. encoding[index] = i;
  25067. }
  25068. }
  25069. } else {
  25070. var dataStart = pos;
  25071. format = bytes[pos++];
  25072. switch (format & 0x7f) {
  25073. case 0:
  25074. var glyphsCount = bytes[pos++];
  25075. for (i = 1; i <= glyphsCount; i++) {
  25076. encoding[bytes[pos++]] = i;
  25077. }
  25078. break;
  25079. case 1:
  25080. var rangesCount = bytes[pos++];
  25081. var gid = 1;
  25082. for (i = 0; i < rangesCount; i++) {
  25083. var start = bytes[pos++];
  25084. var left = bytes[pos++];
  25085. for (var j = start; j <= start + left; j++) {
  25086. encoding[j] = gid++;
  25087. }
  25088. }
  25089. break;
  25090. default:
  25091. error('Unknow encoding format: ' + format + ' in CFF');
  25092. break;
  25093. }
  25094. var dataEnd = pos;
  25095. if (format & 0x80) {
  25096. // The font sanitizer does not support CFF encoding with a
  25097. // supplement, since the encoding is not really used to map
  25098. // between gid to glyph, let's overwrite what is declared in
  25099. // the top dictionary to let the sanitizer think the font use
  25100. // StandardEncoding, that's a lie but that's ok.
  25101. bytes[dataStart] &= 0x7f;
  25102. readSupplement();
  25103. hasSupplement = true;
  25104. }
  25105. raw = bytes.subarray(dataStart, dataEnd);
  25106. }
  25107. format = format & 0x7f;
  25108. return new CFFEncoding(predefined, format, encoding, raw);
  25109. },
  25110. parseFDSelect: function CFFParser_parseFDSelect(pos, length) {
  25111. var start = pos;
  25112. var bytes = this.bytes;
  25113. var format = bytes[pos++];
  25114. var fdSelect = [];
  25115. var i;
  25116. switch (format) {
  25117. case 0:
  25118. for (i = 0; i < length; ++i) {
  25119. var id = bytes[pos++];
  25120. fdSelect.push(id);
  25121. }
  25122. break;
  25123. case 3:
  25124. var rangesCount = (bytes[pos++] << 8) | bytes[pos++];
  25125. for (i = 0; i < rangesCount; ++i) {
  25126. var first = (bytes[pos++] << 8) | bytes[pos++];
  25127. var fdIndex = bytes[pos++];
  25128. var next = (bytes[pos] << 8) | bytes[pos + 1];
  25129. for (var j = first; j < next; ++j) {
  25130. fdSelect.push(fdIndex);
  25131. }
  25132. }
  25133. // Advance past the sentinel(next).
  25134. pos += 2;
  25135. break;
  25136. default:
  25137. error('Unknown fdselect format ' + format);
  25138. break;
  25139. }
  25140. var end = pos;
  25141. return new CFFFDSelect(fdSelect, bytes.subarray(start, end));
  25142. }
  25143. };
  25144. return CFFParser;
  25145. })();
  25146. // Compact Font Format
  25147. var CFF = (function CFFClosure() {
  25148. function CFF() {
  25149. this.header = null;
  25150. this.names = [];
  25151. this.topDict = null;
  25152. this.strings = new CFFStrings();
  25153. this.globalSubrIndex = null;
  25154. // The following could really be per font, but since we only have one font
  25155. // store them here.
  25156. this.encoding = null;
  25157. this.charset = null;
  25158. this.charStrings = null;
  25159. this.fdArray = [];
  25160. this.fdSelect = null;
  25161. this.isCIDFont = false;
  25162. }
  25163. return CFF;
  25164. })();
  25165. var CFFHeader = (function CFFHeaderClosure() {
  25166. function CFFHeader(major, minor, hdrSize, offSize) {
  25167. this.major = major;
  25168. this.minor = minor;
  25169. this.hdrSize = hdrSize;
  25170. this.offSize = offSize;
  25171. }
  25172. return CFFHeader;
  25173. })();
  25174. var CFFStrings = (function CFFStringsClosure() {
  25175. function CFFStrings() {
  25176. this.strings = [];
  25177. }
  25178. CFFStrings.prototype = {
  25179. get: function CFFStrings_get(index) {
  25180. if (index >= 0 && index <= 390) {
  25181. return CFFStandardStrings[index];
  25182. }
  25183. if (index - 391 <= this.strings.length) {
  25184. return this.strings[index - 391];
  25185. }
  25186. return CFFStandardStrings[0];
  25187. },
  25188. add: function CFFStrings_add(value) {
  25189. this.strings.push(value);
  25190. },
  25191. get count() {
  25192. return this.strings.length;
  25193. }
  25194. };
  25195. return CFFStrings;
  25196. })();
  25197. var CFFIndex = (function CFFIndexClosure() {
  25198. function CFFIndex() {
  25199. this.objects = [];
  25200. this.length = 0;
  25201. }
  25202. CFFIndex.prototype = {
  25203. add: function CFFIndex_add(data) {
  25204. this.length += data.length;
  25205. this.objects.push(data);
  25206. },
  25207. set: function CFFIndex_set(index, data) {
  25208. this.length += data.length - this.objects[index].length;
  25209. this.objects[index] = data;
  25210. },
  25211. get: function CFFIndex_get(index) {
  25212. return this.objects[index];
  25213. },
  25214. get count() {
  25215. return this.objects.length;
  25216. }
  25217. };
  25218. return CFFIndex;
  25219. })();
  25220. var CFFDict = (function CFFDictClosure() {
  25221. function CFFDict(tables, strings) {
  25222. this.keyToNameMap = tables.keyToNameMap;
  25223. this.nameToKeyMap = tables.nameToKeyMap;
  25224. this.defaults = tables.defaults;
  25225. this.types = tables.types;
  25226. this.opcodes = tables.opcodes;
  25227. this.order = tables.order;
  25228. this.strings = strings;
  25229. this.values = {};
  25230. }
  25231. CFFDict.prototype = {
  25232. // value should always be an array
  25233. setByKey: function CFFDict_setByKey(key, value) {
  25234. if (!(key in this.keyToNameMap)) {
  25235. return false;
  25236. }
  25237. // ignore empty values
  25238. if (value.length === 0) {
  25239. return true;
  25240. }
  25241. var type = this.types[key];
  25242. // remove the array wrapping these types of values
  25243. if (type === 'num' || type === 'sid' || type === 'offset') {
  25244. value = value[0];
  25245. }
  25246. this.values[key] = value;
  25247. return true;
  25248. },
  25249. setByName: function CFFDict_setByName(name, value) {
  25250. if (!(name in this.nameToKeyMap)) {
  25251. error('Invalid dictionary name "' + name + '"');
  25252. }
  25253. this.values[this.nameToKeyMap[name]] = value;
  25254. },
  25255. hasName: function CFFDict_hasName(name) {
  25256. return this.nameToKeyMap[name] in this.values;
  25257. },
  25258. getByName: function CFFDict_getByName(name) {
  25259. if (!(name in this.nameToKeyMap)) {
  25260. error('Invalid dictionary name "' + name + '"');
  25261. }
  25262. var key = this.nameToKeyMap[name];
  25263. if (!(key in this.values)) {
  25264. return this.defaults[key];
  25265. }
  25266. return this.values[key];
  25267. },
  25268. removeByName: function CFFDict_removeByName(name) {
  25269. delete this.values[this.nameToKeyMap[name]];
  25270. }
  25271. };
  25272. CFFDict.createTables = function CFFDict_createTables(layout) {
  25273. var tables = {
  25274. keyToNameMap: {},
  25275. nameToKeyMap: {},
  25276. defaults: {},
  25277. types: {},
  25278. opcodes: {},
  25279. order: []
  25280. };
  25281. for (var i = 0, ii = layout.length; i < ii; ++i) {
  25282. var entry = layout[i];
  25283. var key = isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0];
  25284. tables.keyToNameMap[key] = entry[1];
  25285. tables.nameToKeyMap[entry[1]] = key;
  25286. tables.types[key] = entry[2];
  25287. tables.defaults[key] = entry[3];
  25288. tables.opcodes[key] = isArray(entry[0]) ? entry[0] : [entry[0]];
  25289. tables.order.push(key);
  25290. }
  25291. return tables;
  25292. };
  25293. return CFFDict;
  25294. })();
  25295. var CFFTopDict = (function CFFTopDictClosure() {
  25296. var layout = [
  25297. [[12, 30], 'ROS', ['sid', 'sid', 'num'], null],
  25298. [[12, 20], 'SyntheticBase', 'num', null],
  25299. [0, 'version', 'sid', null],
  25300. [1, 'Notice', 'sid', null],
  25301. [[12, 0], 'Copyright', 'sid', null],
  25302. [2, 'FullName', 'sid', null],
  25303. [3, 'FamilyName', 'sid', null],
  25304. [4, 'Weight', 'sid', null],
  25305. [[12, 1], 'isFixedPitch', 'num', 0],
  25306. [[12, 2], 'ItalicAngle', 'num', 0],
  25307. [[12, 3], 'UnderlinePosition', 'num', -100],
  25308. [[12, 4], 'UnderlineThickness', 'num', 50],
  25309. [[12, 5], 'PaintType', 'num', 0],
  25310. [[12, 6], 'CharstringType', 'num', 2],
  25311. [[12, 7], 'FontMatrix', ['num', 'num', 'num', 'num', 'num', 'num'],
  25312. [0.001, 0, 0, 0.001, 0, 0]],
  25313. [13, 'UniqueID', 'num', null],
  25314. [5, 'FontBBox', ['num', 'num', 'num', 'num'], [0, 0, 0, 0]],
  25315. [[12, 8], 'StrokeWidth', 'num', 0],
  25316. [14, 'XUID', 'array', null],
  25317. [15, 'charset', 'offset', 0],
  25318. [16, 'Encoding', 'offset', 0],
  25319. [17, 'CharStrings', 'offset', 0],
  25320. [18, 'Private', ['offset', 'offset'], null],
  25321. [[12, 21], 'PostScript', 'sid', null],
  25322. [[12, 22], 'BaseFontName', 'sid', null],
  25323. [[12, 23], 'BaseFontBlend', 'delta', null],
  25324. [[12, 31], 'CIDFontVersion', 'num', 0],
  25325. [[12, 32], 'CIDFontRevision', 'num', 0],
  25326. [[12, 33], 'CIDFontType', 'num', 0],
  25327. [[12, 34], 'CIDCount', 'num', 8720],
  25328. [[12, 35], 'UIDBase', 'num', null],
  25329. // XXX: CID Fonts on DirectWrite 6.1 only seem to work if FDSelect comes
  25330. // before FDArray.
  25331. [[12, 37], 'FDSelect', 'offset', null],
  25332. [[12, 36], 'FDArray', 'offset', null],
  25333. [[12, 38], 'FontName', 'sid', null]
  25334. ];
  25335. var tables = null;
  25336. function CFFTopDict(strings) {
  25337. if (tables === null) {
  25338. tables = CFFDict.createTables(layout);
  25339. }
  25340. CFFDict.call(this, tables, strings);
  25341. this.privateDict = null;
  25342. }
  25343. CFFTopDict.prototype = Object.create(CFFDict.prototype);
  25344. return CFFTopDict;
  25345. })();
  25346. var CFFPrivateDict = (function CFFPrivateDictClosure() {
  25347. var layout = [
  25348. [6, 'BlueValues', 'delta', null],
  25349. [7, 'OtherBlues', 'delta', null],
  25350. [8, 'FamilyBlues', 'delta', null],
  25351. [9, 'FamilyOtherBlues', 'delta', null],
  25352. [[12, 9], 'BlueScale', 'num', 0.039625],
  25353. [[12, 10], 'BlueShift', 'num', 7],
  25354. [[12, 11], 'BlueFuzz', 'num', 1],
  25355. [10, 'StdHW', 'num', null],
  25356. [11, 'StdVW', 'num', null],
  25357. [[12, 12], 'StemSnapH', 'delta', null],
  25358. [[12, 13], 'StemSnapV', 'delta', null],
  25359. [[12, 14], 'ForceBold', 'num', 0],
  25360. [[12, 17], 'LanguageGroup', 'num', 0],
  25361. [[12, 18], 'ExpansionFactor', 'num', 0.06],
  25362. [[12, 19], 'initialRandomSeed', 'num', 0],
  25363. [20, 'defaultWidthX', 'num', 0],
  25364. [21, 'nominalWidthX', 'num', 0],
  25365. [19, 'Subrs', 'offset', null]
  25366. ];
  25367. var tables = null;
  25368. function CFFPrivateDict(strings) {
  25369. if (tables === null) {
  25370. tables = CFFDict.createTables(layout);
  25371. }
  25372. CFFDict.call(this, tables, strings);
  25373. this.subrsIndex = null;
  25374. }
  25375. CFFPrivateDict.prototype = Object.create(CFFDict.prototype);
  25376. return CFFPrivateDict;
  25377. })();
  25378. var CFFCharsetPredefinedTypes = {
  25379. ISO_ADOBE: 0,
  25380. EXPERT: 1,
  25381. EXPERT_SUBSET: 2
  25382. };
  25383. var CFFCharset = (function CFFCharsetClosure() {
  25384. function CFFCharset(predefined, format, charset, raw) {
  25385. this.predefined = predefined;
  25386. this.format = format;
  25387. this.charset = charset;
  25388. this.raw = raw;
  25389. }
  25390. return CFFCharset;
  25391. })();
  25392. var CFFEncoding = (function CFFEncodingClosure() {
  25393. function CFFEncoding(predefined, format, encoding, raw) {
  25394. this.predefined = predefined;
  25395. this.format = format;
  25396. this.encoding = encoding;
  25397. this.raw = raw;
  25398. }
  25399. return CFFEncoding;
  25400. })();
  25401. var CFFFDSelect = (function CFFFDSelectClosure() {
  25402. function CFFFDSelect(fdSelect, raw) {
  25403. this.fdSelect = fdSelect;
  25404. this.raw = raw;
  25405. }
  25406. return CFFFDSelect;
  25407. })();
  25408. // Helper class to keep track of where an offset is within the data and helps
  25409. // filling in that offset once it's known.
  25410. var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
  25411. function CFFOffsetTracker() {
  25412. this.offsets = {};
  25413. }
  25414. CFFOffsetTracker.prototype = {
  25415. isTracking: function CFFOffsetTracker_isTracking(key) {
  25416. return key in this.offsets;
  25417. },
  25418. track: function CFFOffsetTracker_track(key, location) {
  25419. if (key in this.offsets) {
  25420. error('Already tracking location of ' + key);
  25421. }
  25422. this.offsets[key] = location;
  25423. },
  25424. offset: function CFFOffsetTracker_offset(value) {
  25425. for (var key in this.offsets) {
  25426. this.offsets[key] += value;
  25427. }
  25428. },
  25429. setEntryLocation: function CFFOffsetTracker_setEntryLocation(key,
  25430. values,
  25431. output) {
  25432. if (!(key in this.offsets)) {
  25433. error('Not tracking location of ' + key);
  25434. }
  25435. var data = output.data;
  25436. var dataOffset = this.offsets[key];
  25437. var size = 5;
  25438. for (var i = 0, ii = values.length; i < ii; ++i) {
  25439. var offset0 = i * size + dataOffset;
  25440. var offset1 = offset0 + 1;
  25441. var offset2 = offset0 + 2;
  25442. var offset3 = offset0 + 3;
  25443. var offset4 = offset0 + 4;
  25444. // It's easy to screw up offsets so perform this sanity check.
  25445. if (data[offset0] !== 0x1d || data[offset1] !== 0 ||
  25446. data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
  25447. error('writing to an offset that is not empty');
  25448. }
  25449. var value = values[i];
  25450. data[offset0] = 0x1d;
  25451. data[offset1] = (value >> 24) & 0xFF;
  25452. data[offset2] = (value >> 16) & 0xFF;
  25453. data[offset3] = (value >> 8) & 0xFF;
  25454. data[offset4] = value & 0xFF;
  25455. }
  25456. }
  25457. };
  25458. return CFFOffsetTracker;
  25459. })();
  25460. // Takes a CFF and converts it to the binary representation.
  25461. var CFFCompiler = (function CFFCompilerClosure() {
  25462. function CFFCompiler(cff) {
  25463. this.cff = cff;
  25464. }
  25465. CFFCompiler.prototype = {
  25466. compile: function CFFCompiler_compile() {
  25467. var cff = this.cff;
  25468. var output = {
  25469. data: [],
  25470. length: 0,
  25471. add: function CFFCompiler_add(data) {
  25472. this.data = this.data.concat(data);
  25473. this.length = this.data.length;
  25474. }
  25475. };
  25476. // Compile the five entries that must be in order.
  25477. var header = this.compileHeader(cff.header);
  25478. output.add(header);
  25479. var nameIndex = this.compileNameIndex(cff.names);
  25480. output.add(nameIndex);
  25481. if (cff.isCIDFont) {
  25482. // The spec is unclear on how font matrices should relate to each other
  25483. // when there is one in the main top dict and the sub top dicts.
  25484. // Windows handles this differently than linux and osx so we have to
  25485. // normalize to work on all.
  25486. // Rules based off of some mailing list discussions:
  25487. // - If main font has a matrix and subfont doesn't, use the main matrix.
  25488. // - If no main font matrix and there is a subfont matrix, use the
  25489. // subfont matrix.
  25490. // - If both have matrices, concat together.
  25491. // - If neither have matrices, use default.
  25492. // To make this work on all platforms we move the top matrix into each
  25493. // sub top dict and concat if necessary.
  25494. if (cff.topDict.hasName('FontMatrix')) {
  25495. var base = cff.topDict.getByName('FontMatrix');
  25496. cff.topDict.removeByName('FontMatrix');
  25497. for (var i = 0, ii = cff.fdArray.length; i < ii; i++) {
  25498. var subDict = cff.fdArray[i];
  25499. var matrix = base.slice(0);
  25500. if (subDict.hasName('FontMatrix')) {
  25501. matrix = Util.transform(matrix, subDict.getByName('FontMatrix'));
  25502. }
  25503. subDict.setByName('FontMatrix', matrix);
  25504. }
  25505. }
  25506. }
  25507. var compiled = this.compileTopDicts([cff.topDict],
  25508. output.length,
  25509. cff.isCIDFont);
  25510. output.add(compiled.output);
  25511. var topDictTracker = compiled.trackers[0];
  25512. var stringIndex = this.compileStringIndex(cff.strings.strings);
  25513. output.add(stringIndex);
  25514. var globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
  25515. output.add(globalSubrIndex);
  25516. // Now start on the other entries that have no specfic order.
  25517. if (cff.encoding && cff.topDict.hasName('Encoding')) {
  25518. if (cff.encoding.predefined) {
  25519. topDictTracker.setEntryLocation('Encoding', [cff.encoding.format],
  25520. output);
  25521. } else {
  25522. var encoding = this.compileEncoding(cff.encoding);
  25523. topDictTracker.setEntryLocation('Encoding', [output.length], output);
  25524. output.add(encoding);
  25525. }
  25526. }
  25527. if (cff.charset && cff.topDict.hasName('charset')) {
  25528. if (cff.charset.predefined) {
  25529. topDictTracker.setEntryLocation('charset', [cff.charset.format],
  25530. output);
  25531. } else {
  25532. var charset = this.compileCharset(cff.charset);
  25533. topDictTracker.setEntryLocation('charset', [output.length], output);
  25534. output.add(charset);
  25535. }
  25536. }
  25537. var charStrings = this.compileCharStrings(cff.charStrings);
  25538. topDictTracker.setEntryLocation('CharStrings', [output.length], output);
  25539. output.add(charStrings);
  25540. if (cff.isCIDFont) {
  25541. // For some reason FDSelect must be in front of FDArray on windows. OSX
  25542. // and linux don't seem to care.
  25543. topDictTracker.setEntryLocation('FDSelect', [output.length], output);
  25544. var fdSelect = this.compileFDSelect(cff.fdSelect.raw);
  25545. output.add(fdSelect);
  25546. // It is unclear if the sub font dictionary can have CID related
  25547. // dictionary keys, but the sanitizer doesn't like them so remove them.
  25548. compiled = this.compileTopDicts(cff.fdArray, output.length, true);
  25549. topDictTracker.setEntryLocation('FDArray', [output.length], output);
  25550. output.add(compiled.output);
  25551. var fontDictTrackers = compiled.trackers;
  25552. this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
  25553. }
  25554. this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
  25555. // If the font data ends with INDEX whose object data is zero-length,
  25556. // the sanitizer will bail out. Add a dummy byte to avoid that.
  25557. output.add([0]);
  25558. return output.data;
  25559. },
  25560. encodeNumber: function CFFCompiler_encodeNumber(value) {
  25561. if (parseFloat(value) === parseInt(value, 10) && !isNaN(value)) { // isInt
  25562. return this.encodeInteger(value);
  25563. } else {
  25564. return this.encodeFloat(value);
  25565. }
  25566. },
  25567. encodeFloat: function CFFCompiler_encodeFloat(num) {
  25568. var value = num.toString();
  25569. // rounding inaccurate doubles
  25570. var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
  25571. if (m) {
  25572. var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
  25573. value = (Math.round(num * epsilon) / epsilon).toString();
  25574. }
  25575. var nibbles = '';
  25576. var i, ii;
  25577. for (i = 0, ii = value.length; i < ii; ++i) {
  25578. var a = value[i];
  25579. if (a === 'e') {
  25580. nibbles += value[++i] === '-' ? 'c' : 'b';
  25581. } else if (a === '.') {
  25582. nibbles += 'a';
  25583. } else if (a === '-') {
  25584. nibbles += 'e';
  25585. } else {
  25586. nibbles += a;
  25587. }
  25588. }
  25589. nibbles += (nibbles.length & 1) ? 'f' : 'ff';
  25590. var out = [30];
  25591. for (i = 0, ii = nibbles.length; i < ii; i += 2) {
  25592. out.push(parseInt(nibbles.substr(i, 2), 16));
  25593. }
  25594. return out;
  25595. },
  25596. encodeInteger: function CFFCompiler_encodeInteger(value) {
  25597. var code;
  25598. if (value >= -107 && value <= 107) {
  25599. code = [value + 139];
  25600. } else if (value >= 108 && value <= 1131) {
  25601. value = [value - 108];
  25602. code = [(value >> 8) + 247, value & 0xFF];
  25603. } else if (value >= -1131 && value <= -108) {
  25604. value = -value - 108;
  25605. code = [(value >> 8) + 251, value & 0xFF];
  25606. } else if (value >= -32768 && value <= 32767) {
  25607. code = [0x1c, (value >> 8) & 0xFF, value & 0xFF];
  25608. } else {
  25609. code = [0x1d,
  25610. (value >> 24) & 0xFF,
  25611. (value >> 16) & 0xFF,
  25612. (value >> 8) & 0xFF,
  25613. value & 0xFF];
  25614. }
  25615. return code;
  25616. },
  25617. compileHeader: function CFFCompiler_compileHeader(header) {
  25618. return [
  25619. header.major,
  25620. header.minor,
  25621. header.hdrSize,
  25622. header.offSize
  25623. ];
  25624. },
  25625. compileNameIndex: function CFFCompiler_compileNameIndex(names) {
  25626. var nameIndex = new CFFIndex();
  25627. for (var i = 0, ii = names.length; i < ii; ++i) {
  25628. nameIndex.add(stringToBytes(names[i]));
  25629. }
  25630. return this.compileIndex(nameIndex);
  25631. },
  25632. compileTopDicts: function CFFCompiler_compileTopDicts(dicts,
  25633. length,
  25634. removeCidKeys) {
  25635. var fontDictTrackers = [];
  25636. var fdArrayIndex = new CFFIndex();
  25637. for (var i = 0, ii = dicts.length; i < ii; ++i) {
  25638. var fontDict = dicts[i];
  25639. if (removeCidKeys) {
  25640. fontDict.removeByName('CIDFontVersion');
  25641. fontDict.removeByName('CIDFontRevision');
  25642. fontDict.removeByName('CIDFontType');
  25643. fontDict.removeByName('CIDCount');
  25644. fontDict.removeByName('UIDBase');
  25645. }
  25646. var fontDictTracker = new CFFOffsetTracker();
  25647. var fontDictData = this.compileDict(fontDict, fontDictTracker);
  25648. fontDictTrackers.push(fontDictTracker);
  25649. fdArrayIndex.add(fontDictData);
  25650. fontDictTracker.offset(length);
  25651. }
  25652. fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
  25653. return {
  25654. trackers: fontDictTrackers,
  25655. output: fdArrayIndex
  25656. };
  25657. },
  25658. compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts,
  25659. trackers,
  25660. output) {
  25661. for (var i = 0, ii = dicts.length; i < ii; ++i) {
  25662. var fontDict = dicts[i];
  25663. assert(fontDict.privateDict && fontDict.hasName('Private'),
  25664. 'There must be an private dictionary.');
  25665. var privateDict = fontDict.privateDict;
  25666. var privateDictTracker = new CFFOffsetTracker();
  25667. var privateDictData = this.compileDict(privateDict, privateDictTracker);
  25668. var outputLength = output.length;
  25669. privateDictTracker.offset(outputLength);
  25670. if (!privateDictData.length) {
  25671. // The private dictionary was empty, set the output length to zero to
  25672. // ensure the offset length isn't out of bounds in the eyes of the
  25673. // sanitizer.
  25674. outputLength = 0;
  25675. }
  25676. trackers[i].setEntryLocation('Private',
  25677. [privateDictData.length, outputLength],
  25678. output);
  25679. output.add(privateDictData);
  25680. if (privateDict.subrsIndex && privateDict.hasName('Subrs')) {
  25681. var subrs = this.compileIndex(privateDict.subrsIndex);
  25682. privateDictTracker.setEntryLocation('Subrs', [privateDictData.length],
  25683. output);
  25684. output.add(subrs);
  25685. }
  25686. }
  25687. },
  25688. compileDict: function CFFCompiler_compileDict(dict, offsetTracker) {
  25689. var out = [];
  25690. // The dictionary keys must be in a certain order.
  25691. var order = dict.order;
  25692. for (var i = 0; i < order.length; ++i) {
  25693. var key = order[i];
  25694. if (!(key in dict.values)) {
  25695. continue;
  25696. }
  25697. var values = dict.values[key];
  25698. var types = dict.types[key];
  25699. if (!isArray(types)) {
  25700. types = [types];
  25701. }
  25702. if (!isArray(values)) {
  25703. values = [values];
  25704. }
  25705. // Remove any empty dict values.
  25706. if (values.length === 0) {
  25707. continue;
  25708. }
  25709. for (var j = 0, jj = types.length; j < jj; ++j) {
  25710. var type = types[j];
  25711. var value = values[j];
  25712. switch (type) {
  25713. case 'num':
  25714. case 'sid':
  25715. out = out.concat(this.encodeNumber(value));
  25716. break;
  25717. case 'offset':
  25718. // For offsets we just insert a 32bit integer so we don't have to
  25719. // deal with figuring out the length of the offset when it gets
  25720. // replaced later on by the compiler.
  25721. var name = dict.keyToNameMap[key];
  25722. // Some offsets have the offset and the length, so just record the
  25723. // position of the first one.
  25724. if (!offsetTracker.isTracking(name)) {
  25725. offsetTracker.track(name, out.length);
  25726. }
  25727. out = out.concat([0x1d, 0, 0, 0, 0]);
  25728. break;
  25729. case 'array':
  25730. case 'delta':
  25731. out = out.concat(this.encodeNumber(value));
  25732. for (var k = 1, kk = values.length; k < kk; ++k) {
  25733. out = out.concat(this.encodeNumber(values[k]));
  25734. }
  25735. break;
  25736. default:
  25737. error('Unknown data type of ' + type);
  25738. break;
  25739. }
  25740. }
  25741. out = out.concat(dict.opcodes[key]);
  25742. }
  25743. return out;
  25744. },
  25745. compileStringIndex: function CFFCompiler_compileStringIndex(strings) {
  25746. var stringIndex = new CFFIndex();
  25747. for (var i = 0, ii = strings.length; i < ii; ++i) {
  25748. stringIndex.add(stringToBytes(strings[i]));
  25749. }
  25750. return this.compileIndex(stringIndex);
  25751. },
  25752. compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() {
  25753. var globalSubrIndex = this.cff.globalSubrIndex;
  25754. this.out.writeByteArray(this.compileIndex(globalSubrIndex));
  25755. },
  25756. compileCharStrings: function CFFCompiler_compileCharStrings(charStrings) {
  25757. return this.compileIndex(charStrings);
  25758. },
  25759. compileCharset: function CFFCompiler_compileCharset(charset) {
  25760. return this.compileTypedArray(charset.raw);
  25761. },
  25762. compileEncoding: function CFFCompiler_compileEncoding(encoding) {
  25763. return this.compileTypedArray(encoding.raw);
  25764. },
  25765. compileFDSelect: function CFFCompiler_compileFDSelect(fdSelect) {
  25766. return this.compileTypedArray(fdSelect);
  25767. },
  25768. compileTypedArray: function CFFCompiler_compileTypedArray(data) {
  25769. var out = [];
  25770. for (var i = 0, ii = data.length; i < ii; ++i) {
  25771. out[i] = data[i];
  25772. }
  25773. return out;
  25774. },
  25775. compileIndex: function CFFCompiler_compileIndex(index, trackers) {
  25776. trackers = trackers || [];
  25777. var objects = index.objects;
  25778. // First 2 bytes contains the number of objects contained into this index
  25779. var count = objects.length;
  25780. // If there is no object, just create an index. This technically
  25781. // should just be [0, 0] but OTS has an issue with that.
  25782. if (count === 0) {
  25783. return [0, 0, 0];
  25784. }
  25785. var data = [(count >> 8) & 0xFF, count & 0xff];
  25786. var lastOffset = 1, i;
  25787. for (i = 0; i < count; ++i) {
  25788. lastOffset += objects[i].length;
  25789. }
  25790. var offsetSize;
  25791. if (lastOffset < 0x100) {
  25792. offsetSize = 1;
  25793. } else if (lastOffset < 0x10000) {
  25794. offsetSize = 2;
  25795. } else if (lastOffset < 0x1000000) {
  25796. offsetSize = 3;
  25797. } else {
  25798. offsetSize = 4;
  25799. }
  25800. // Next byte contains the offset size use to reference object in the file
  25801. data.push(offsetSize);
  25802. // Add another offset after this one because we need a new offset
  25803. var relativeOffset = 1;
  25804. for (i = 0; i < count + 1; i++) {
  25805. if (offsetSize === 1) {
  25806. data.push(relativeOffset & 0xFF);
  25807. } else if (offsetSize === 2) {
  25808. data.push((relativeOffset >> 8) & 0xFF,
  25809. relativeOffset & 0xFF);
  25810. } else if (offsetSize === 3) {
  25811. data.push((relativeOffset >> 16) & 0xFF,
  25812. (relativeOffset >> 8) & 0xFF,
  25813. relativeOffset & 0xFF);
  25814. } else {
  25815. data.push((relativeOffset >>> 24) & 0xFF,
  25816. (relativeOffset >> 16) & 0xFF,
  25817. (relativeOffset >> 8) & 0xFF,
  25818. relativeOffset & 0xFF);
  25819. }
  25820. if (objects[i]) {
  25821. relativeOffset += objects[i].length;
  25822. }
  25823. }
  25824. for (i = 0; i < count; i++) {
  25825. // Notify the tracker where the object will be offset in the data.
  25826. if (trackers[i]) {
  25827. trackers[i].offset(data.length);
  25828. }
  25829. for (var j = 0, jj = objects[i].length; j < jj; j++) {
  25830. data.push(objects[i][j]);
  25831. }
  25832. }
  25833. return data;
  25834. }
  25835. };
  25836. return CFFCompiler;
  25837. })();
  25838. // Workaround for seac on Windows.
  25839. (function checkSeacSupport() {
  25840. if (/Windows/.test(navigator.userAgent)) {
  25841. SEAC_ANALYSIS_ENABLED = true;
  25842. }
  25843. })();
  25844. // Workaround for Private Use Area characters in Chrome on Windows
  25845. // http://code.google.com/p/chromium/issues/detail?id=122465
  25846. // https://github.com/mozilla/pdf.js/issues/1689
  25847. (function checkChromeWindows() {
  25848. if (/Windows.*Chrome/.test(navigator.userAgent)) {
  25849. SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = true;
  25850. }
  25851. })();
  25852. var FontRendererFactory = (function FontRendererFactoryClosure() {
  25853. function getLong(data, offset) {
  25854. return (data[offset] << 24) | (data[offset + 1] << 16) |
  25855. (data[offset + 2] << 8) | data[offset + 3];
  25856. }
  25857. function getUshort(data, offset) {
  25858. return (data[offset] << 8) | data[offset + 1];
  25859. }
  25860. function parseCmap(data, start, end) {
  25861. var offset = (getUshort(data, start + 2) === 1 ?
  25862. getLong(data, start + 8) : getLong(data, start + 16));
  25863. var format = getUshort(data, start + offset);
  25864. var length, ranges, p, i;
  25865. if (format === 4) {
  25866. length = getUshort(data, start + offset + 2);
  25867. var segCount = getUshort(data, start + offset + 6) >> 1;
  25868. p = start + offset + 14;
  25869. ranges = [];
  25870. for (i = 0; i < segCount; i++, p += 2) {
  25871. ranges[i] = {end: getUshort(data, p)};
  25872. }
  25873. p += 2;
  25874. for (i = 0; i < segCount; i++, p += 2) {
  25875. ranges[i].start = getUshort(data, p);
  25876. }
  25877. for (i = 0; i < segCount; i++, p += 2) {
  25878. ranges[i].idDelta = getUshort(data, p);
  25879. }
  25880. for (i = 0; i < segCount; i++, p += 2) {
  25881. var idOffset = getUshort(data, p);
  25882. if (idOffset === 0) {
  25883. continue;
  25884. }
  25885. ranges[i].ids = [];
  25886. for (var j = 0, jj = ranges[i].end - ranges[i].start + 1; j < jj; j++) {
  25887. ranges[i].ids[j] = getUshort(data, p + idOffset);
  25888. idOffset += 2;
  25889. }
  25890. }
  25891. return ranges;
  25892. } else if (format === 12) {
  25893. length = getLong(data, start + offset + 4);
  25894. var groups = getLong(data, start + offset + 12);
  25895. p = start + offset + 16;
  25896. ranges = [];
  25897. for (i = 0; i < groups; i++) {
  25898. ranges.push({
  25899. start: getLong(data, p),
  25900. end: getLong(data, p + 4),
  25901. idDelta: getLong(data, p + 8) - getLong(data, p)
  25902. });
  25903. p += 12;
  25904. }
  25905. return ranges;
  25906. }
  25907. error('not supported cmap: ' + format);
  25908. }
  25909. function parseCff(data, start, end) {
  25910. var properties = {};
  25911. var parser = new CFFParser(new Stream(data, start, end - start),
  25912. properties);
  25913. var cff = parser.parse();
  25914. return {
  25915. glyphs: cff.charStrings.objects,
  25916. subrs: (cff.topDict.privateDict && cff.topDict.privateDict.subrsIndex &&
  25917. cff.topDict.privateDict.subrsIndex.objects),
  25918. gsubrs: cff.globalSubrIndex && cff.globalSubrIndex.objects
  25919. };
  25920. }
  25921. function parseGlyfTable(glyf, loca, isGlyphLocationsLong) {
  25922. var itemSize, itemDecode;
  25923. if (isGlyphLocationsLong) {
  25924. itemSize = 4;
  25925. itemDecode = function fontItemDecodeLong(data, offset) {
  25926. return (data[offset] << 24) | (data[offset + 1] << 16) |
  25927. (data[offset + 2] << 8) | data[offset + 3];
  25928. };
  25929. } else {
  25930. itemSize = 2;
  25931. itemDecode = function fontItemDecode(data, offset) {
  25932. return (data[offset] << 9) | (data[offset + 1] << 1);
  25933. };
  25934. }
  25935. var glyphs = [];
  25936. var startOffset = itemDecode(loca, 0);
  25937. for (var j = itemSize; j < loca.length; j += itemSize) {
  25938. var endOffset = itemDecode(loca, j);
  25939. glyphs.push(glyf.subarray(startOffset, endOffset));
  25940. startOffset = endOffset;
  25941. }
  25942. return glyphs;
  25943. }
  25944. function lookupCmap(ranges, unicode) {
  25945. var code = unicode.charCodeAt(0);
  25946. var l = 0, r = ranges.length - 1;
  25947. while (l < r) {
  25948. var c = (l + r + 1) >> 1;
  25949. if (code < ranges[c].start) {
  25950. r = c - 1;
  25951. } else {
  25952. l = c;
  25953. }
  25954. }
  25955. if (ranges[l].start <= code && code <= ranges[l].end) {
  25956. return (ranges[l].idDelta + (ranges[l].ids ?
  25957. ranges[l].ids[code - ranges[l].start] : code)) & 0xFFFF;
  25958. }
  25959. return 0;
  25960. }
  25961. function compileGlyf(code, cmds, font) {
  25962. function moveTo(x, y) {
  25963. cmds.push({cmd: 'moveTo', args: [x, y]});
  25964. }
  25965. function lineTo(x, y) {
  25966. cmds.push({cmd: 'lineTo', args: [x, y]});
  25967. }
  25968. function quadraticCurveTo(xa, ya, x, y) {
  25969. cmds.push({cmd: 'quadraticCurveTo', args: [xa, ya, x, y]});
  25970. }
  25971. var i = 0;
  25972. var numberOfContours = ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25973. var flags;
  25974. var x = 0, y = 0;
  25975. i += 10;
  25976. if (numberOfContours < 0) {
  25977. // composite glyph
  25978. do {
  25979. flags = (code[i] << 8) | code[i + 1];
  25980. var glyphIndex = (code[i + 2] << 8) | code[i + 3];
  25981. i += 4;
  25982. var arg1, arg2;
  25983. if ((flags & 0x01)) {
  25984. arg1 = ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25985. arg2 = ((code[i + 2] << 24) | (code[i + 3] << 16)) >> 16;
  25986. i += 4;
  25987. } else {
  25988. arg1 = code[i++]; arg2 = code[i++];
  25989. }
  25990. if ((flags & 0x02)) {
  25991. x = arg1;
  25992. y = arg2;
  25993. } else {
  25994. x = 0; y = 0; // TODO "they are points" ?
  25995. }
  25996. var scaleX = 1, scaleY = 1, scale01 = 0, scale10 = 0;
  25997. if ((flags & 0x08)) {
  25998. scaleX =
  25999. scaleY = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  26000. i += 2;
  26001. } else if ((flags & 0x40)) {
  26002. scaleX = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  26003. scaleY = ((code[i + 2] << 24) | (code[i + 3] << 16)) / 1073741824;
  26004. i += 4;
  26005. } else if ((flags & 0x80)) {
  26006. scaleX = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  26007. scale01 = ((code[i + 2] << 24) | (code[i + 3] << 16)) / 1073741824;
  26008. scale10 = ((code[i + 4] << 24) | (code[i + 5] << 16)) / 1073741824;
  26009. scaleY = ((code[i + 6] << 24) | (code[i + 7] << 16)) / 1073741824;
  26010. i += 8;
  26011. }
  26012. var subglyph = font.glyphs[glyphIndex];
  26013. if (subglyph) {
  26014. cmds.push({cmd: 'save'});
  26015. cmds.push({cmd: 'transform',
  26016. args: [scaleX, scale01, scale10, scaleY, x, y]});
  26017. compileGlyf(subglyph, cmds, font);
  26018. cmds.push({cmd: 'restore'});
  26019. }
  26020. } while ((flags & 0x20));
  26021. } else {
  26022. // simple glyph
  26023. var endPtsOfContours = [];
  26024. var j, jj;
  26025. for (j = 0; j < numberOfContours; j++) {
  26026. endPtsOfContours.push((code[i] << 8) | code[i + 1]);
  26027. i += 2;
  26028. }
  26029. var instructionLength = (code[i] << 8) | code[i + 1];
  26030. i += 2 + instructionLength; // skipping the instructions
  26031. var numberOfPoints = endPtsOfContours[endPtsOfContours.length - 1] + 1;
  26032. var points = [];
  26033. while (points.length < numberOfPoints) {
  26034. flags = code[i++];
  26035. var repeat = 1;
  26036. if ((flags & 0x08)) {
  26037. repeat += code[i++];
  26038. }
  26039. while (repeat-- > 0) {
  26040. points.push({flags: flags});
  26041. }
  26042. }
  26043. for (j = 0; j < numberOfPoints; j++) {
  26044. switch (points[j].flags & 0x12) {
  26045. case 0x00:
  26046. x += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  26047. i += 2;
  26048. break;
  26049. case 0x02:
  26050. x -= code[i++];
  26051. break;
  26052. case 0x12:
  26053. x += code[i++];
  26054. break;
  26055. }
  26056. points[j].x = x;
  26057. }
  26058. for (j = 0; j < numberOfPoints; j++) {
  26059. switch (points[j].flags & 0x24) {
  26060. case 0x00:
  26061. y += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  26062. i += 2;
  26063. break;
  26064. case 0x04:
  26065. y -= code[i++];
  26066. break;
  26067. case 0x24:
  26068. y += code[i++];
  26069. break;
  26070. }
  26071. points[j].y = y;
  26072. }
  26073. var startPoint = 0;
  26074. for (i = 0; i < numberOfContours; i++) {
  26075. var endPoint = endPtsOfContours[i];
  26076. // contours might have implicit points, which is located in the middle
  26077. // between two neighboring off-curve points
  26078. var contour = points.slice(startPoint, endPoint + 1);
  26079. if ((contour[0].flags & 1)) {
  26080. contour.push(contour[0]); // using start point at the contour end
  26081. } else if ((contour[contour.length - 1].flags & 1)) {
  26082. // first is off-curve point, trying to use one from the end
  26083. contour.unshift(contour[contour.length - 1]);
  26084. } else {
  26085. // start and end are off-curve points, creating implicit one
  26086. var p = {
  26087. flags: 1,
  26088. x: (contour[0].x + contour[contour.length - 1].x) / 2,
  26089. y: (contour[0].y + contour[contour.length - 1].y) / 2
  26090. };
  26091. contour.unshift(p);
  26092. contour.push(p);
  26093. }
  26094. moveTo(contour[0].x, contour[0].y);
  26095. for (j = 1, jj = contour.length; j < jj; j++) {
  26096. if ((contour[j].flags & 1)) {
  26097. lineTo(contour[j].x, contour[j].y);
  26098. } else if ((contour[j + 1].flags & 1)){
  26099. quadraticCurveTo(contour[j].x, contour[j].y,
  26100. contour[j + 1].x, contour[j + 1].y);
  26101. j++;
  26102. } else {
  26103. quadraticCurveTo(contour[j].x, contour[j].y,
  26104. (contour[j].x + contour[j + 1].x) / 2,
  26105. (contour[j].y + contour[j + 1].y) / 2);
  26106. }
  26107. }
  26108. startPoint = endPoint + 1;
  26109. }
  26110. }
  26111. }
  26112. function compileCharString(code, cmds, font) {
  26113. var stack = [];
  26114. var x = 0, y = 0;
  26115. var stems = 0;
  26116. function moveTo(x, y) {
  26117. cmds.push({cmd: 'moveTo', args: [x, y]});
  26118. }
  26119. function lineTo(x, y) {
  26120. cmds.push({cmd: 'lineTo', args: [x, y]});
  26121. }
  26122. function bezierCurveTo(x1, y1, x2, y2, x, y) {
  26123. cmds.push({cmd: 'bezierCurveTo', args: [x1, y1, x2, y2, x, y]});
  26124. }
  26125. function parse(code) {
  26126. var i = 0;
  26127. while (i < code.length) {
  26128. var stackClean = false;
  26129. var v = code[i++];
  26130. var xa, xb, ya, yb, y1, y2, y3, n, subrCode;
  26131. switch (v) {
  26132. case 1: // hstem
  26133. stems += stack.length >> 1;
  26134. stackClean = true;
  26135. break;
  26136. case 3: // vstem
  26137. stems += stack.length >> 1;
  26138. stackClean = true;
  26139. break;
  26140. case 4: // vmoveto
  26141. y += stack.pop();
  26142. moveTo(x, y);
  26143. stackClean = true;
  26144. break;
  26145. case 5: // rlineto
  26146. while (stack.length > 0) {
  26147. x += stack.shift();
  26148. y += stack.shift();
  26149. lineTo(x, y);
  26150. }
  26151. break;
  26152. case 6: // hlineto
  26153. while (stack.length > 0) {
  26154. x += stack.shift();
  26155. lineTo(x, y);
  26156. if (stack.length === 0) {
  26157. break;
  26158. }
  26159. y += stack.shift();
  26160. lineTo(x, y);
  26161. }
  26162. break;
  26163. case 7: // vlineto
  26164. while (stack.length > 0) {
  26165. y += stack.shift();
  26166. lineTo(x, y);
  26167. if (stack.length === 0) {
  26168. break;
  26169. }
  26170. x += stack.shift();
  26171. lineTo(x, y);
  26172. }
  26173. break;
  26174. case 8: // rrcurveto
  26175. while (stack.length > 0) {
  26176. xa = x + stack.shift(); ya = y + stack.shift();
  26177. xb = xa + stack.shift(); yb = ya + stack.shift();
  26178. x = xb + stack.shift(); y = yb + stack.shift();
  26179. bezierCurveTo(xa, ya, xb, yb, x, y);
  26180. }
  26181. break;
  26182. case 10: // callsubr
  26183. n = stack.pop() + font.subrsBias;
  26184. subrCode = font.subrs[n];
  26185. if (subrCode) {
  26186. parse(subrCode);
  26187. }
  26188. break;
  26189. case 11: // return
  26190. return;
  26191. case 12:
  26192. v = code[i++];
  26193. switch (v) {
  26194. case 34: // flex
  26195. xa = x + stack.shift();
  26196. xb = xa + stack.shift(); y1 = y + stack.shift();
  26197. x = xb + stack.shift();
  26198. bezierCurveTo(xa, y, xb, y1, x, y1);
  26199. xa = x + stack.shift();
  26200. xb = xa + stack.shift();
  26201. x = xb + stack.shift();
  26202. bezierCurveTo(xa, y1, xb, y, x, y);
  26203. break;
  26204. case 35: // flex
  26205. xa = x + stack.shift(); ya = y + stack.shift();
  26206. xb = xa + stack.shift(); yb = ya + stack.shift();
  26207. x = xb + stack.shift(); y = yb + stack.shift();
  26208. bezierCurveTo(xa, ya, xb, yb, x, y);
  26209. xa = x + stack.shift(); ya = y + stack.shift();
  26210. xb = xa + stack.shift(); yb = ya + stack.shift();
  26211. x = xb + stack.shift(); y = yb + stack.shift();
  26212. bezierCurveTo(xa, ya, xb, yb, x, y);
  26213. stack.pop(); // fd
  26214. break;
  26215. case 36: // hflex1
  26216. xa = x + stack.shift(); y1 = y + stack.shift();
  26217. xb = xa + stack.shift(); y2 = y1 + stack.shift();
  26218. x = xb + stack.shift();
  26219. bezierCurveTo(xa, y1, xb, y2, x, y2);
  26220. xa = x + stack.shift();
  26221. xb = xa + stack.shift(); y3 = y2 + stack.shift();
  26222. x = xb + stack.shift();
  26223. bezierCurveTo(xa, y2, xb, y3, x, y);
  26224. break;
  26225. case 37: // flex1
  26226. var x0 = x, y0 = y;
  26227. xa = x + stack.shift(); ya = y + stack.shift();
  26228. xb = xa + stack.shift(); yb = ya + stack.shift();
  26229. x = xb + stack.shift(); y = yb + stack.shift();
  26230. bezierCurveTo(xa, ya, xb, yb, x, y);
  26231. xa = x + stack.shift(); ya = y + stack.shift();
  26232. xb = xa + stack.shift(); yb = ya + stack.shift();
  26233. x = xb; y = yb;
  26234. if (Math.abs(x - x0) > Math.abs(y - y0)) {
  26235. x += stack.shift();
  26236. } else {
  26237. y += stack.shift();
  26238. }
  26239. bezierCurveTo(xa, ya, xb, yb, x, y);
  26240. break;
  26241. default:
  26242. error('unknown operator: 12 ' + v);
  26243. }
  26244. break;
  26245. case 14: // endchar
  26246. if (stack.length >= 4) {
  26247. var achar = stack.pop();
  26248. var bchar = stack.pop();
  26249. y = stack.pop();
  26250. x = stack.pop();
  26251. cmds.push({cmd: 'save'});
  26252. cmds.push({cmd: 'translate', args: [x, y]});
  26253. var gid = lookupCmap(font.cmap, String.fromCharCode(
  26254. font.glyphNameMap[Encodings.StandardEncoding[achar]]));
  26255. compileCharString(font.glyphs[gid], cmds, font);
  26256. cmds.push({cmd: 'restore'});
  26257. gid = lookupCmap(font.cmap, String.fromCharCode(
  26258. font.glyphNameMap[Encodings.StandardEncoding[bchar]]));
  26259. compileCharString(font.glyphs[gid], cmds, font);
  26260. }
  26261. return;
  26262. case 18: // hstemhm
  26263. stems += stack.length >> 1;
  26264. stackClean = true;
  26265. break;
  26266. case 19: // hintmask
  26267. stems += stack.length >> 1;
  26268. i += (stems + 7) >> 3;
  26269. stackClean = true;
  26270. break;
  26271. case 20: // cntrmask
  26272. stems += stack.length >> 1;
  26273. i += (stems + 7) >> 3;
  26274. stackClean = true;
  26275. break;
  26276. case 21: // rmoveto
  26277. y += stack.pop();
  26278. x += stack.pop();
  26279. moveTo(x, y);
  26280. stackClean = true;
  26281. break;
  26282. case 22: // hmoveto
  26283. x += stack.pop();
  26284. moveTo(x, y);
  26285. stackClean = true;
  26286. break;
  26287. case 23: // vstemhm
  26288. stems += stack.length >> 1;
  26289. stackClean = true;
  26290. break;
  26291. case 24: // rcurveline
  26292. while (stack.length > 2) {
  26293. xa = x + stack.shift(); ya = y + stack.shift();
  26294. xb = xa + stack.shift(); yb = ya + stack.shift();
  26295. x = xb + stack.shift(); y = yb + stack.shift();
  26296. bezierCurveTo(xa, ya, xb, yb, x, y);
  26297. }
  26298. x += stack.shift();
  26299. y += stack.shift();
  26300. lineTo(x, y);
  26301. break;
  26302. case 25: // rlinecurve
  26303. while (stack.length > 6) {
  26304. x += stack.shift();
  26305. y += stack.shift();
  26306. lineTo(x, y);
  26307. }
  26308. xa = x + stack.shift(); ya = y + stack.shift();
  26309. xb = xa + stack.shift(); yb = ya + stack.shift();
  26310. x = xb + stack.shift(); y = yb + stack.shift();
  26311. bezierCurveTo(xa, ya, xb, yb, x, y);
  26312. break;
  26313. case 26: // vvcurveto
  26314. if (stack.length % 2) {
  26315. x += stack.shift();
  26316. }
  26317. while (stack.length > 0) {
  26318. xa = x; ya = y + stack.shift();
  26319. xb = xa + stack.shift(); yb = ya + stack.shift();
  26320. x = xb; y = yb + stack.shift();
  26321. bezierCurveTo(xa, ya, xb, yb, x, y);
  26322. }
  26323. break;
  26324. case 27: // hhcurveto
  26325. if (stack.length % 2) {
  26326. y += stack.shift();
  26327. }
  26328. while (stack.length > 0) {
  26329. xa = x + stack.shift(); ya = y;
  26330. xb = xa + stack.shift(); yb = ya + stack.shift();
  26331. x = xb + stack.shift(); y = yb;
  26332. bezierCurveTo(xa, ya, xb, yb, x, y);
  26333. }
  26334. break;
  26335. case 28:
  26336. stack.push(((code[i] << 24) | (code[i + 1] << 16)) >> 16);
  26337. i += 2;
  26338. break;
  26339. case 29: // callgsubr
  26340. n = stack.pop() + font.gsubrsBias;
  26341. subrCode = font.gsubrs[n];
  26342. if (subrCode) {
  26343. parse(subrCode);
  26344. }
  26345. break;
  26346. case 30: // vhcurveto
  26347. while (stack.length > 0) {
  26348. xa = x; ya = y + stack.shift();
  26349. xb = xa + stack.shift(); yb = ya + stack.shift();
  26350. x = xb + stack.shift();
  26351. y = yb + (stack.length === 1 ? stack.shift() : 0);
  26352. bezierCurveTo(xa, ya, xb, yb, x, y);
  26353. if (stack.length === 0) {
  26354. break;
  26355. }
  26356. xa = x + stack.shift(); ya = y;
  26357. xb = xa + stack.shift(); yb = ya + stack.shift();
  26358. y = yb + stack.shift();
  26359. x = xb + (stack.length === 1 ? stack.shift() : 0);
  26360. bezierCurveTo(xa, ya, xb, yb, x, y);
  26361. }
  26362. break;
  26363. case 31: // hvcurveto
  26364. while (stack.length > 0) {
  26365. xa = x + stack.shift(); ya = y;
  26366. xb = xa + stack.shift(); yb = ya + stack.shift();
  26367. y = yb + stack.shift();
  26368. x = xb + (stack.length === 1 ? stack.shift() : 0);
  26369. bezierCurveTo(xa, ya, xb, yb, x, y);
  26370. if (stack.length === 0) {
  26371. break;
  26372. }
  26373. xa = x; ya = y + stack.shift();
  26374. xb = xa + stack.shift(); yb = ya + stack.shift();
  26375. x = xb + stack.shift();
  26376. y = yb + (stack.length === 1 ? stack.shift() : 0);
  26377. bezierCurveTo(xa, ya, xb, yb, x, y);
  26378. }
  26379. break;
  26380. default:
  26381. if (v < 32) {
  26382. error('unknown operator: ' + v);
  26383. }
  26384. if (v < 247) {
  26385. stack.push(v - 139);
  26386. } else if (v < 251) {
  26387. stack.push((v - 247) * 256 + code[i++] + 108);
  26388. } else if (v < 255) {
  26389. stack.push(-(v - 251) * 256 - code[i++] - 108);
  26390. } else {
  26391. stack.push(((code[i] << 24) | (code[i + 1] << 16) |
  26392. (code[i + 2] << 8) | code[i + 3]) / 65536);
  26393. i += 4;
  26394. }
  26395. break;
  26396. }
  26397. if (stackClean) {
  26398. stack.length = 0;
  26399. }
  26400. }
  26401. }
  26402. parse(code);
  26403. }
  26404. var noop = '';
  26405. function CompiledFont(fontMatrix) {
  26406. this.compiledGlyphs = {};
  26407. this.fontMatrix = fontMatrix;
  26408. }
  26409. CompiledFont.prototype = {
  26410. getPathJs: function (unicode) {
  26411. var gid = lookupCmap(this.cmap, unicode);
  26412. var fn = this.compiledGlyphs[gid];
  26413. if (!fn) {
  26414. this.compiledGlyphs[gid] = fn = this.compileGlyph(this.glyphs[gid]);
  26415. }
  26416. return fn;
  26417. },
  26418. compileGlyph: function (code) {
  26419. if (!code || code.length === 0 || code[0] === 14) {
  26420. return noop;
  26421. }
  26422. var cmds = [];
  26423. cmds.push({cmd: 'save'});
  26424. cmds.push({cmd: 'transform', args: this.fontMatrix.slice()});
  26425. cmds.push({cmd: 'scale', args: ['size', '-size']});
  26426. this.compileGlyphImpl(code, cmds);
  26427. cmds.push({cmd: 'restore'});
  26428. return cmds;
  26429. },
  26430. compileGlyphImpl: function () {
  26431. error('Children classes should implement this.');
  26432. },
  26433. hasBuiltPath: function (unicode) {
  26434. var gid = lookupCmap(this.cmap, unicode);
  26435. return gid in this.compiledGlyphs;
  26436. }
  26437. };
  26438. function TrueTypeCompiled(glyphs, cmap, fontMatrix) {
  26439. fontMatrix = fontMatrix || [0.000488, 0, 0, 0.000488, 0, 0];
  26440. CompiledFont.call(this, fontMatrix);
  26441. this.glyphs = glyphs;
  26442. this.cmap = cmap;
  26443. this.compiledGlyphs = [];
  26444. }
  26445. Util.inherit(TrueTypeCompiled, CompiledFont, {
  26446. compileGlyphImpl: function (code, cmds) {
  26447. compileGlyf(code, cmds, this);
  26448. }
  26449. });
  26450. function Type2Compiled(cffInfo, cmap, fontMatrix, glyphNameMap) {
  26451. fontMatrix = fontMatrix || [0.001, 0, 0, 0.001, 0, 0];
  26452. CompiledFont.call(this, fontMatrix);
  26453. this.glyphs = cffInfo.glyphs;
  26454. this.gsubrs = cffInfo.gsubrs || [];
  26455. this.subrs = cffInfo.subrs || [];
  26456. this.cmap = cmap;
  26457. this.glyphNameMap = glyphNameMap || GlyphsUnicode;
  26458. this.compiledGlyphs = [];
  26459. this.gsubrsBias = (this.gsubrs.length < 1240 ?
  26460. 107 : (this.gsubrs.length < 33900 ? 1131 : 32768));
  26461. this.subrsBias = (this.subrs.length < 1240 ?
  26462. 107 : (this.subrs.length < 33900 ? 1131 : 32768));
  26463. }
  26464. Util.inherit(Type2Compiled, CompiledFont, {
  26465. compileGlyphImpl: function (code, cmds) {
  26466. compileCharString(code, cmds, this);
  26467. }
  26468. });
  26469. return {
  26470. create: function FontRendererFactory_create(font) {
  26471. var data = new Uint8Array(font.data);
  26472. var cmap, glyf, loca, cff, indexToLocFormat, unitsPerEm;
  26473. var numTables = getUshort(data, 4);
  26474. for (var i = 0, p = 12; i < numTables; i++, p += 16) {
  26475. var tag = bytesToString(data.subarray(p, p + 4));
  26476. var offset = getLong(data, p + 8);
  26477. var length = getLong(data, p + 12);
  26478. switch (tag) {
  26479. case 'cmap':
  26480. cmap = parseCmap(data, offset, offset + length);
  26481. break;
  26482. case 'glyf':
  26483. glyf = data.subarray(offset, offset + length);
  26484. break;
  26485. case 'loca':
  26486. loca = data.subarray(offset, offset + length);
  26487. break;
  26488. case 'head':
  26489. unitsPerEm = getUshort(data, offset + 18);
  26490. indexToLocFormat = getUshort(data, offset + 50);
  26491. break;
  26492. case 'CFF ':
  26493. cff = parseCff(data, offset, offset + length);
  26494. break;
  26495. }
  26496. }
  26497. if (glyf) {
  26498. var fontMatrix = (!unitsPerEm ? font.fontMatrix :
  26499. [1 / unitsPerEm, 0, 0, 1 / unitsPerEm, 0, 0]);
  26500. return new TrueTypeCompiled(
  26501. parseGlyfTable(glyf, loca, indexToLocFormat), cmap, fontMatrix);
  26502. } else {
  26503. return new Type2Compiled(cff, cmap, font.fontMatrix, font.glyphNameMap);
  26504. }
  26505. }
  26506. };
  26507. })();
  26508. var GlyphsUnicode = {
  26509. A: 0x0041,
  26510. AE: 0x00C6,
  26511. AEacute: 0x01FC,
  26512. AEmacron: 0x01E2,
  26513. AEsmall: 0xF7E6,
  26514. Aacute: 0x00C1,
  26515. Aacutesmall: 0xF7E1,
  26516. Abreve: 0x0102,
  26517. Abreveacute: 0x1EAE,
  26518. Abrevecyrillic: 0x04D0,
  26519. Abrevedotbelow: 0x1EB6,
  26520. Abrevegrave: 0x1EB0,
  26521. Abrevehookabove: 0x1EB2,
  26522. Abrevetilde: 0x1EB4,
  26523. Acaron: 0x01CD,
  26524. Acircle: 0x24B6,
  26525. Acircumflex: 0x00C2,
  26526. Acircumflexacute: 0x1EA4,
  26527. Acircumflexdotbelow: 0x1EAC,
  26528. Acircumflexgrave: 0x1EA6,
  26529. Acircumflexhookabove: 0x1EA8,
  26530. Acircumflexsmall: 0xF7E2,
  26531. Acircumflextilde: 0x1EAA,
  26532. Acute: 0xF6C9,
  26533. Acutesmall: 0xF7B4,
  26534. Acyrillic: 0x0410,
  26535. Adblgrave: 0x0200,
  26536. Adieresis: 0x00C4,
  26537. Adieresiscyrillic: 0x04D2,
  26538. Adieresismacron: 0x01DE,
  26539. Adieresissmall: 0xF7E4,
  26540. Adotbelow: 0x1EA0,
  26541. Adotmacron: 0x01E0,
  26542. Agrave: 0x00C0,
  26543. Agravesmall: 0xF7E0,
  26544. Ahookabove: 0x1EA2,
  26545. Aiecyrillic: 0x04D4,
  26546. Ainvertedbreve: 0x0202,
  26547. Alpha: 0x0391,
  26548. Alphatonos: 0x0386,
  26549. Amacron: 0x0100,
  26550. Amonospace: 0xFF21,
  26551. Aogonek: 0x0104,
  26552. Aring: 0x00C5,
  26553. Aringacute: 0x01FA,
  26554. Aringbelow: 0x1E00,
  26555. Aringsmall: 0xF7E5,
  26556. Asmall: 0xF761,
  26557. Atilde: 0x00C3,
  26558. Atildesmall: 0xF7E3,
  26559. Aybarmenian: 0x0531,
  26560. B: 0x0042,
  26561. Bcircle: 0x24B7,
  26562. Bdotaccent: 0x1E02,
  26563. Bdotbelow: 0x1E04,
  26564. Becyrillic: 0x0411,
  26565. Benarmenian: 0x0532,
  26566. Beta: 0x0392,
  26567. Bhook: 0x0181,
  26568. Blinebelow: 0x1E06,
  26569. Bmonospace: 0xFF22,
  26570. Brevesmall: 0xF6F4,
  26571. Bsmall: 0xF762,
  26572. Btopbar: 0x0182,
  26573. C: 0x0043,
  26574. Caarmenian: 0x053E,
  26575. Cacute: 0x0106,
  26576. Caron: 0xF6CA,
  26577. Caronsmall: 0xF6F5,
  26578. Ccaron: 0x010C,
  26579. Ccedilla: 0x00C7,
  26580. Ccedillaacute: 0x1E08,
  26581. Ccedillasmall: 0xF7E7,
  26582. Ccircle: 0x24B8,
  26583. Ccircumflex: 0x0108,
  26584. Cdot: 0x010A,
  26585. Cdotaccent: 0x010A,
  26586. Cedillasmall: 0xF7B8,
  26587. Chaarmenian: 0x0549,
  26588. Cheabkhasiancyrillic: 0x04BC,
  26589. Checyrillic: 0x0427,
  26590. Chedescenderabkhasiancyrillic: 0x04BE,
  26591. Chedescendercyrillic: 0x04B6,
  26592. Chedieresiscyrillic: 0x04F4,
  26593. Cheharmenian: 0x0543,
  26594. Chekhakassiancyrillic: 0x04CB,
  26595. Cheverticalstrokecyrillic: 0x04B8,
  26596. Chi: 0x03A7,
  26597. Chook: 0x0187,
  26598. Circumflexsmall: 0xF6F6,
  26599. Cmonospace: 0xFF23,
  26600. Coarmenian: 0x0551,
  26601. Csmall: 0xF763,
  26602. D: 0x0044,
  26603. DZ: 0x01F1,
  26604. DZcaron: 0x01C4,
  26605. Daarmenian: 0x0534,
  26606. Dafrican: 0x0189,
  26607. Dcaron: 0x010E,
  26608. Dcedilla: 0x1E10,
  26609. Dcircle: 0x24B9,
  26610. Dcircumflexbelow: 0x1E12,
  26611. Dcroat: 0x0110,
  26612. Ddotaccent: 0x1E0A,
  26613. Ddotbelow: 0x1E0C,
  26614. Decyrillic: 0x0414,
  26615. Deicoptic: 0x03EE,
  26616. Delta: 0x2206,
  26617. Deltagreek: 0x0394,
  26618. Dhook: 0x018A,
  26619. Dieresis: 0xF6CB,
  26620. DieresisAcute: 0xF6CC,
  26621. DieresisGrave: 0xF6CD,
  26622. Dieresissmall: 0xF7A8,
  26623. Digammagreek: 0x03DC,
  26624. Djecyrillic: 0x0402,
  26625. Dlinebelow: 0x1E0E,
  26626. Dmonospace: 0xFF24,
  26627. Dotaccentsmall: 0xF6F7,
  26628. Dslash: 0x0110,
  26629. Dsmall: 0xF764,
  26630. Dtopbar: 0x018B,
  26631. Dz: 0x01F2,
  26632. Dzcaron: 0x01C5,
  26633. Dzeabkhasiancyrillic: 0x04E0,
  26634. Dzecyrillic: 0x0405,
  26635. Dzhecyrillic: 0x040F,
  26636. E: 0x0045,
  26637. Eacute: 0x00C9,
  26638. Eacutesmall: 0xF7E9,
  26639. Ebreve: 0x0114,
  26640. Ecaron: 0x011A,
  26641. Ecedillabreve: 0x1E1C,
  26642. Echarmenian: 0x0535,
  26643. Ecircle: 0x24BA,
  26644. Ecircumflex: 0x00CA,
  26645. Ecircumflexacute: 0x1EBE,
  26646. Ecircumflexbelow: 0x1E18,
  26647. Ecircumflexdotbelow: 0x1EC6,
  26648. Ecircumflexgrave: 0x1EC0,
  26649. Ecircumflexhookabove: 0x1EC2,
  26650. Ecircumflexsmall: 0xF7EA,
  26651. Ecircumflextilde: 0x1EC4,
  26652. Ecyrillic: 0x0404,
  26653. Edblgrave: 0x0204,
  26654. Edieresis: 0x00CB,
  26655. Edieresissmall: 0xF7EB,
  26656. Edot: 0x0116,
  26657. Edotaccent: 0x0116,
  26658. Edotbelow: 0x1EB8,
  26659. Efcyrillic: 0x0424,
  26660. Egrave: 0x00C8,
  26661. Egravesmall: 0xF7E8,
  26662. Eharmenian: 0x0537,
  26663. Ehookabove: 0x1EBA,
  26664. Eightroman: 0x2167,
  26665. Einvertedbreve: 0x0206,
  26666. Eiotifiedcyrillic: 0x0464,
  26667. Elcyrillic: 0x041B,
  26668. Elevenroman: 0x216A,
  26669. Emacron: 0x0112,
  26670. Emacronacute: 0x1E16,
  26671. Emacrongrave: 0x1E14,
  26672. Emcyrillic: 0x041C,
  26673. Emonospace: 0xFF25,
  26674. Encyrillic: 0x041D,
  26675. Endescendercyrillic: 0x04A2,
  26676. Eng: 0x014A,
  26677. Enghecyrillic: 0x04A4,
  26678. Enhookcyrillic: 0x04C7,
  26679. Eogonek: 0x0118,
  26680. Eopen: 0x0190,
  26681. Epsilon: 0x0395,
  26682. Epsilontonos: 0x0388,
  26683. Ercyrillic: 0x0420,
  26684. Ereversed: 0x018E,
  26685. Ereversedcyrillic: 0x042D,
  26686. Escyrillic: 0x0421,
  26687. Esdescendercyrillic: 0x04AA,
  26688. Esh: 0x01A9,
  26689. Esmall: 0xF765,
  26690. Eta: 0x0397,
  26691. Etarmenian: 0x0538,
  26692. Etatonos: 0x0389,
  26693. Eth: 0x00D0,
  26694. Ethsmall: 0xF7F0,
  26695. Etilde: 0x1EBC,
  26696. Etildebelow: 0x1E1A,
  26697. Euro: 0x20AC,
  26698. Ezh: 0x01B7,
  26699. Ezhcaron: 0x01EE,
  26700. Ezhreversed: 0x01B8,
  26701. F: 0x0046,
  26702. Fcircle: 0x24BB,
  26703. Fdotaccent: 0x1E1E,
  26704. Feharmenian: 0x0556,
  26705. Feicoptic: 0x03E4,
  26706. Fhook: 0x0191,
  26707. Fitacyrillic: 0x0472,
  26708. Fiveroman: 0x2164,
  26709. Fmonospace: 0xFF26,
  26710. Fourroman: 0x2163,
  26711. Fsmall: 0xF766,
  26712. G: 0x0047,
  26713. GBsquare: 0x3387,
  26714. Gacute: 0x01F4,
  26715. Gamma: 0x0393,
  26716. Gammaafrican: 0x0194,
  26717. Gangiacoptic: 0x03EA,
  26718. Gbreve: 0x011E,
  26719. Gcaron: 0x01E6,
  26720. Gcedilla: 0x0122,
  26721. Gcircle: 0x24BC,
  26722. Gcircumflex: 0x011C,
  26723. Gcommaaccent: 0x0122,
  26724. Gdot: 0x0120,
  26725. Gdotaccent: 0x0120,
  26726. Gecyrillic: 0x0413,
  26727. Ghadarmenian: 0x0542,
  26728. Ghemiddlehookcyrillic: 0x0494,
  26729. Ghestrokecyrillic: 0x0492,
  26730. Gheupturncyrillic: 0x0490,
  26731. Ghook: 0x0193,
  26732. Gimarmenian: 0x0533,
  26733. Gjecyrillic: 0x0403,
  26734. Gmacron: 0x1E20,
  26735. Gmonospace: 0xFF27,
  26736. Grave: 0xF6CE,
  26737. Gravesmall: 0xF760,
  26738. Gsmall: 0xF767,
  26739. Gsmallhook: 0x029B,
  26740. Gstroke: 0x01E4,
  26741. H: 0x0048,
  26742. H18533: 0x25CF,
  26743. H18543: 0x25AA,
  26744. H18551: 0x25AB,
  26745. H22073: 0x25A1,
  26746. HPsquare: 0x33CB,
  26747. Haabkhasiancyrillic: 0x04A8,
  26748. Hadescendercyrillic: 0x04B2,
  26749. Hardsigncyrillic: 0x042A,
  26750. Hbar: 0x0126,
  26751. Hbrevebelow: 0x1E2A,
  26752. Hcedilla: 0x1E28,
  26753. Hcircle: 0x24BD,
  26754. Hcircumflex: 0x0124,
  26755. Hdieresis: 0x1E26,
  26756. Hdotaccent: 0x1E22,
  26757. Hdotbelow: 0x1E24,
  26758. Hmonospace: 0xFF28,
  26759. Hoarmenian: 0x0540,
  26760. Horicoptic: 0x03E8,
  26761. Hsmall: 0xF768,
  26762. Hungarumlaut: 0xF6CF,
  26763. Hungarumlautsmall: 0xF6F8,
  26764. Hzsquare: 0x3390,
  26765. I: 0x0049,
  26766. IAcyrillic: 0x042F,
  26767. IJ: 0x0132,
  26768. IUcyrillic: 0x042E,
  26769. Iacute: 0x00CD,
  26770. Iacutesmall: 0xF7ED,
  26771. Ibreve: 0x012C,
  26772. Icaron: 0x01CF,
  26773. Icircle: 0x24BE,
  26774. Icircumflex: 0x00CE,
  26775. Icircumflexsmall: 0xF7EE,
  26776. Icyrillic: 0x0406,
  26777. Idblgrave: 0x0208,
  26778. Idieresis: 0x00CF,
  26779. Idieresisacute: 0x1E2E,
  26780. Idieresiscyrillic: 0x04E4,
  26781. Idieresissmall: 0xF7EF,
  26782. Idot: 0x0130,
  26783. Idotaccent: 0x0130,
  26784. Idotbelow: 0x1ECA,
  26785. Iebrevecyrillic: 0x04D6,
  26786. Iecyrillic: 0x0415,
  26787. Ifraktur: 0x2111,
  26788. Igrave: 0x00CC,
  26789. Igravesmall: 0xF7EC,
  26790. Ihookabove: 0x1EC8,
  26791. Iicyrillic: 0x0418,
  26792. Iinvertedbreve: 0x020A,
  26793. Iishortcyrillic: 0x0419,
  26794. Imacron: 0x012A,
  26795. Imacroncyrillic: 0x04E2,
  26796. Imonospace: 0xFF29,
  26797. Iniarmenian: 0x053B,
  26798. Iocyrillic: 0x0401,
  26799. Iogonek: 0x012E,
  26800. Iota: 0x0399,
  26801. Iotaafrican: 0x0196,
  26802. Iotadieresis: 0x03AA,
  26803. Iotatonos: 0x038A,
  26804. Ismall: 0xF769,
  26805. Istroke: 0x0197,
  26806. Itilde: 0x0128,
  26807. Itildebelow: 0x1E2C,
  26808. Izhitsacyrillic: 0x0474,
  26809. Izhitsadblgravecyrillic: 0x0476,
  26810. J: 0x004A,
  26811. Jaarmenian: 0x0541,
  26812. Jcircle: 0x24BF,
  26813. Jcircumflex: 0x0134,
  26814. Jecyrillic: 0x0408,
  26815. Jheharmenian: 0x054B,
  26816. Jmonospace: 0xFF2A,
  26817. Jsmall: 0xF76A,
  26818. K: 0x004B,
  26819. KBsquare: 0x3385,
  26820. KKsquare: 0x33CD,
  26821. Kabashkircyrillic: 0x04A0,
  26822. Kacute: 0x1E30,
  26823. Kacyrillic: 0x041A,
  26824. Kadescendercyrillic: 0x049A,
  26825. Kahookcyrillic: 0x04C3,
  26826. Kappa: 0x039A,
  26827. Kastrokecyrillic: 0x049E,
  26828. Kaverticalstrokecyrillic: 0x049C,
  26829. Kcaron: 0x01E8,
  26830. Kcedilla: 0x0136,
  26831. Kcircle: 0x24C0,
  26832. Kcommaaccent: 0x0136,
  26833. Kdotbelow: 0x1E32,
  26834. Keharmenian: 0x0554,
  26835. Kenarmenian: 0x053F,
  26836. Khacyrillic: 0x0425,
  26837. Kheicoptic: 0x03E6,
  26838. Khook: 0x0198,
  26839. Kjecyrillic: 0x040C,
  26840. Klinebelow: 0x1E34,
  26841. Kmonospace: 0xFF2B,
  26842. Koppacyrillic: 0x0480,
  26843. Koppagreek: 0x03DE,
  26844. Ksicyrillic: 0x046E,
  26845. Ksmall: 0xF76B,
  26846. L: 0x004C,
  26847. LJ: 0x01C7,
  26848. LL: 0xF6BF,
  26849. Lacute: 0x0139,
  26850. Lambda: 0x039B,
  26851. Lcaron: 0x013D,
  26852. Lcedilla: 0x013B,
  26853. Lcircle: 0x24C1,
  26854. Lcircumflexbelow: 0x1E3C,
  26855. Lcommaaccent: 0x013B,
  26856. Ldot: 0x013F,
  26857. Ldotaccent: 0x013F,
  26858. Ldotbelow: 0x1E36,
  26859. Ldotbelowmacron: 0x1E38,
  26860. Liwnarmenian: 0x053C,
  26861. Lj: 0x01C8,
  26862. Ljecyrillic: 0x0409,
  26863. Llinebelow: 0x1E3A,
  26864. Lmonospace: 0xFF2C,
  26865. Lslash: 0x0141,
  26866. Lslashsmall: 0xF6F9,
  26867. Lsmall: 0xF76C,
  26868. M: 0x004D,
  26869. MBsquare: 0x3386,
  26870. Macron: 0xF6D0,
  26871. Macronsmall: 0xF7AF,
  26872. Macute: 0x1E3E,
  26873. Mcircle: 0x24C2,
  26874. Mdotaccent: 0x1E40,
  26875. Mdotbelow: 0x1E42,
  26876. Menarmenian: 0x0544,
  26877. Mmonospace: 0xFF2D,
  26878. Msmall: 0xF76D,
  26879. Mturned: 0x019C,
  26880. Mu: 0x039C,
  26881. N: 0x004E,
  26882. NJ: 0x01CA,
  26883. Nacute: 0x0143,
  26884. Ncaron: 0x0147,
  26885. Ncedilla: 0x0145,
  26886. Ncircle: 0x24C3,
  26887. Ncircumflexbelow: 0x1E4A,
  26888. Ncommaaccent: 0x0145,
  26889. Ndotaccent: 0x1E44,
  26890. Ndotbelow: 0x1E46,
  26891. Nhookleft: 0x019D,
  26892. Nineroman: 0x2168,
  26893. Nj: 0x01CB,
  26894. Njecyrillic: 0x040A,
  26895. Nlinebelow: 0x1E48,
  26896. Nmonospace: 0xFF2E,
  26897. Nowarmenian: 0x0546,
  26898. Nsmall: 0xF76E,
  26899. Ntilde: 0x00D1,
  26900. Ntildesmall: 0xF7F1,
  26901. Nu: 0x039D,
  26902. O: 0x004F,
  26903. OE: 0x0152,
  26904. OEsmall: 0xF6FA,
  26905. Oacute: 0x00D3,
  26906. Oacutesmall: 0xF7F3,
  26907. Obarredcyrillic: 0x04E8,
  26908. Obarreddieresiscyrillic: 0x04EA,
  26909. Obreve: 0x014E,
  26910. Ocaron: 0x01D1,
  26911. Ocenteredtilde: 0x019F,
  26912. Ocircle: 0x24C4,
  26913. Ocircumflex: 0x00D4,
  26914. Ocircumflexacute: 0x1ED0,
  26915. Ocircumflexdotbelow: 0x1ED8,
  26916. Ocircumflexgrave: 0x1ED2,
  26917. Ocircumflexhookabove: 0x1ED4,
  26918. Ocircumflexsmall: 0xF7F4,
  26919. Ocircumflextilde: 0x1ED6,
  26920. Ocyrillic: 0x041E,
  26921. Odblacute: 0x0150,
  26922. Odblgrave: 0x020C,
  26923. Odieresis: 0x00D6,
  26924. Odieresiscyrillic: 0x04E6,
  26925. Odieresissmall: 0xF7F6,
  26926. Odotbelow: 0x1ECC,
  26927. Ogoneksmall: 0xF6FB,
  26928. Ograve: 0x00D2,
  26929. Ogravesmall: 0xF7F2,
  26930. Oharmenian: 0x0555,
  26931. Ohm: 0x2126,
  26932. Ohookabove: 0x1ECE,
  26933. Ohorn: 0x01A0,
  26934. Ohornacute: 0x1EDA,
  26935. Ohorndotbelow: 0x1EE2,
  26936. Ohorngrave: 0x1EDC,
  26937. Ohornhookabove: 0x1EDE,
  26938. Ohorntilde: 0x1EE0,
  26939. Ohungarumlaut: 0x0150,
  26940. Oi: 0x01A2,
  26941. Oinvertedbreve: 0x020E,
  26942. Omacron: 0x014C,
  26943. Omacronacute: 0x1E52,
  26944. Omacrongrave: 0x1E50,
  26945. Omega: 0x2126,
  26946. Omegacyrillic: 0x0460,
  26947. Omegagreek: 0x03A9,
  26948. Omegaroundcyrillic: 0x047A,
  26949. Omegatitlocyrillic: 0x047C,
  26950. Omegatonos: 0x038F,
  26951. Omicron: 0x039F,
  26952. Omicrontonos: 0x038C,
  26953. Omonospace: 0xFF2F,
  26954. Oneroman: 0x2160,
  26955. Oogonek: 0x01EA,
  26956. Oogonekmacron: 0x01EC,
  26957. Oopen: 0x0186,
  26958. Oslash: 0x00D8,
  26959. Oslashacute: 0x01FE,
  26960. Oslashsmall: 0xF7F8,
  26961. Osmall: 0xF76F,
  26962. Ostrokeacute: 0x01FE,
  26963. Otcyrillic: 0x047E,
  26964. Otilde: 0x00D5,
  26965. Otildeacute: 0x1E4C,
  26966. Otildedieresis: 0x1E4E,
  26967. Otildesmall: 0xF7F5,
  26968. P: 0x0050,
  26969. Pacute: 0x1E54,
  26970. Pcircle: 0x24C5,
  26971. Pdotaccent: 0x1E56,
  26972. Pecyrillic: 0x041F,
  26973. Peharmenian: 0x054A,
  26974. Pemiddlehookcyrillic: 0x04A6,
  26975. Phi: 0x03A6,
  26976. Phook: 0x01A4,
  26977. Pi: 0x03A0,
  26978. Piwrarmenian: 0x0553,
  26979. Pmonospace: 0xFF30,
  26980. Psi: 0x03A8,
  26981. Psicyrillic: 0x0470,
  26982. Psmall: 0xF770,
  26983. Q: 0x0051,
  26984. Qcircle: 0x24C6,
  26985. Qmonospace: 0xFF31,
  26986. Qsmall: 0xF771,
  26987. R: 0x0052,
  26988. Raarmenian: 0x054C,
  26989. Racute: 0x0154,
  26990. Rcaron: 0x0158,
  26991. Rcedilla: 0x0156,
  26992. Rcircle: 0x24C7,
  26993. Rcommaaccent: 0x0156,
  26994. Rdblgrave: 0x0210,
  26995. Rdotaccent: 0x1E58,
  26996. Rdotbelow: 0x1E5A,
  26997. Rdotbelowmacron: 0x1E5C,
  26998. Reharmenian: 0x0550,
  26999. Rfraktur: 0x211C,
  27000. Rho: 0x03A1,
  27001. Ringsmall: 0xF6FC,
  27002. Rinvertedbreve: 0x0212,
  27003. Rlinebelow: 0x1E5E,
  27004. Rmonospace: 0xFF32,
  27005. Rsmall: 0xF772,
  27006. Rsmallinverted: 0x0281,
  27007. Rsmallinvertedsuperior: 0x02B6,
  27008. S: 0x0053,
  27009. SF010000: 0x250C,
  27010. SF020000: 0x2514,
  27011. SF030000: 0x2510,
  27012. SF040000: 0x2518,
  27013. SF050000: 0x253C,
  27014. SF060000: 0x252C,
  27015. SF070000: 0x2534,
  27016. SF080000: 0x251C,
  27017. SF090000: 0x2524,
  27018. SF100000: 0x2500,
  27019. SF110000: 0x2502,
  27020. SF190000: 0x2561,
  27021. SF200000: 0x2562,
  27022. SF210000: 0x2556,
  27023. SF220000: 0x2555,
  27024. SF230000: 0x2563,
  27025. SF240000: 0x2551,
  27026. SF250000: 0x2557,
  27027. SF260000: 0x255D,
  27028. SF270000: 0x255C,
  27029. SF280000: 0x255B,
  27030. SF360000: 0x255E,
  27031. SF370000: 0x255F,
  27032. SF380000: 0x255A,
  27033. SF390000: 0x2554,
  27034. SF400000: 0x2569,
  27035. SF410000: 0x2566,
  27036. SF420000: 0x2560,
  27037. SF430000: 0x2550,
  27038. SF440000: 0x256C,
  27039. SF450000: 0x2567,
  27040. SF460000: 0x2568,
  27041. SF470000: 0x2564,
  27042. SF480000: 0x2565,
  27043. SF490000: 0x2559,
  27044. SF500000: 0x2558,
  27045. SF510000: 0x2552,
  27046. SF520000: 0x2553,
  27047. SF530000: 0x256B,
  27048. SF540000: 0x256A,
  27049. Sacute: 0x015A,
  27050. Sacutedotaccent: 0x1E64,
  27051. Sampigreek: 0x03E0,
  27052. Scaron: 0x0160,
  27053. Scarondotaccent: 0x1E66,
  27054. Scaronsmall: 0xF6FD,
  27055. Scedilla: 0x015E,
  27056. Schwa: 0x018F,
  27057. Schwacyrillic: 0x04D8,
  27058. Schwadieresiscyrillic: 0x04DA,
  27059. Scircle: 0x24C8,
  27060. Scircumflex: 0x015C,
  27061. Scommaaccent: 0x0218,
  27062. Sdotaccent: 0x1E60,
  27063. Sdotbelow: 0x1E62,
  27064. Sdotbelowdotaccent: 0x1E68,
  27065. Seharmenian: 0x054D,
  27066. Sevenroman: 0x2166,
  27067. Shaarmenian: 0x0547,
  27068. Shacyrillic: 0x0428,
  27069. Shchacyrillic: 0x0429,
  27070. Sheicoptic: 0x03E2,
  27071. Shhacyrillic: 0x04BA,
  27072. Shimacoptic: 0x03EC,
  27073. Sigma: 0x03A3,
  27074. Sixroman: 0x2165,
  27075. Smonospace: 0xFF33,
  27076. Softsigncyrillic: 0x042C,
  27077. Ssmall: 0xF773,
  27078. Stigmagreek: 0x03DA,
  27079. T: 0x0054,
  27080. Tau: 0x03A4,
  27081. Tbar: 0x0166,
  27082. Tcaron: 0x0164,
  27083. Tcedilla: 0x0162,
  27084. Tcircle: 0x24C9,
  27085. Tcircumflexbelow: 0x1E70,
  27086. Tcommaaccent: 0x0162,
  27087. Tdotaccent: 0x1E6A,
  27088. Tdotbelow: 0x1E6C,
  27089. Tecyrillic: 0x0422,
  27090. Tedescendercyrillic: 0x04AC,
  27091. Tenroman: 0x2169,
  27092. Tetsecyrillic: 0x04B4,
  27093. Theta: 0x0398,
  27094. Thook: 0x01AC,
  27095. Thorn: 0x00DE,
  27096. Thornsmall: 0xF7FE,
  27097. Threeroman: 0x2162,
  27098. Tildesmall: 0xF6FE,
  27099. Tiwnarmenian: 0x054F,
  27100. Tlinebelow: 0x1E6E,
  27101. Tmonospace: 0xFF34,
  27102. Toarmenian: 0x0539,
  27103. Tonefive: 0x01BC,
  27104. Tonesix: 0x0184,
  27105. Tonetwo: 0x01A7,
  27106. Tretroflexhook: 0x01AE,
  27107. Tsecyrillic: 0x0426,
  27108. Tshecyrillic: 0x040B,
  27109. Tsmall: 0xF774,
  27110. Twelveroman: 0x216B,
  27111. Tworoman: 0x2161,
  27112. U: 0x0055,
  27113. Uacute: 0x00DA,
  27114. Uacutesmall: 0xF7FA,
  27115. Ubreve: 0x016C,
  27116. Ucaron: 0x01D3,
  27117. Ucircle: 0x24CA,
  27118. Ucircumflex: 0x00DB,
  27119. Ucircumflexbelow: 0x1E76,
  27120. Ucircumflexsmall: 0xF7FB,
  27121. Ucyrillic: 0x0423,
  27122. Udblacute: 0x0170,
  27123. Udblgrave: 0x0214,
  27124. Udieresis: 0x00DC,
  27125. Udieresisacute: 0x01D7,
  27126. Udieresisbelow: 0x1E72,
  27127. Udieresiscaron: 0x01D9,
  27128. Udieresiscyrillic: 0x04F0,
  27129. Udieresisgrave: 0x01DB,
  27130. Udieresismacron: 0x01D5,
  27131. Udieresissmall: 0xF7FC,
  27132. Udotbelow: 0x1EE4,
  27133. Ugrave: 0x00D9,
  27134. Ugravesmall: 0xF7F9,
  27135. Uhookabove: 0x1EE6,
  27136. Uhorn: 0x01AF,
  27137. Uhornacute: 0x1EE8,
  27138. Uhorndotbelow: 0x1EF0,
  27139. Uhorngrave: 0x1EEA,
  27140. Uhornhookabove: 0x1EEC,
  27141. Uhorntilde: 0x1EEE,
  27142. Uhungarumlaut: 0x0170,
  27143. Uhungarumlautcyrillic: 0x04F2,
  27144. Uinvertedbreve: 0x0216,
  27145. Ukcyrillic: 0x0478,
  27146. Umacron: 0x016A,
  27147. Umacroncyrillic: 0x04EE,
  27148. Umacrondieresis: 0x1E7A,
  27149. Umonospace: 0xFF35,
  27150. Uogonek: 0x0172,
  27151. Upsilon: 0x03A5,
  27152. Upsilon1: 0x03D2,
  27153. Upsilonacutehooksymbolgreek: 0x03D3,
  27154. Upsilonafrican: 0x01B1,
  27155. Upsilondieresis: 0x03AB,
  27156. Upsilondieresishooksymbolgreek: 0x03D4,
  27157. Upsilonhooksymbol: 0x03D2,
  27158. Upsilontonos: 0x038E,
  27159. Uring: 0x016E,
  27160. Ushortcyrillic: 0x040E,
  27161. Usmall: 0xF775,
  27162. Ustraightcyrillic: 0x04AE,
  27163. Ustraightstrokecyrillic: 0x04B0,
  27164. Utilde: 0x0168,
  27165. Utildeacute: 0x1E78,
  27166. Utildebelow: 0x1E74,
  27167. V: 0x0056,
  27168. Vcircle: 0x24CB,
  27169. Vdotbelow: 0x1E7E,
  27170. Vecyrillic: 0x0412,
  27171. Vewarmenian: 0x054E,
  27172. Vhook: 0x01B2,
  27173. Vmonospace: 0xFF36,
  27174. Voarmenian: 0x0548,
  27175. Vsmall: 0xF776,
  27176. Vtilde: 0x1E7C,
  27177. W: 0x0057,
  27178. Wacute: 0x1E82,
  27179. Wcircle: 0x24CC,
  27180. Wcircumflex: 0x0174,
  27181. Wdieresis: 0x1E84,
  27182. Wdotaccent: 0x1E86,
  27183. Wdotbelow: 0x1E88,
  27184. Wgrave: 0x1E80,
  27185. Wmonospace: 0xFF37,
  27186. Wsmall: 0xF777,
  27187. X: 0x0058,
  27188. Xcircle: 0x24CD,
  27189. Xdieresis: 0x1E8C,
  27190. Xdotaccent: 0x1E8A,
  27191. Xeharmenian: 0x053D,
  27192. Xi: 0x039E,
  27193. Xmonospace: 0xFF38,
  27194. Xsmall: 0xF778,
  27195. Y: 0x0059,
  27196. Yacute: 0x00DD,
  27197. Yacutesmall: 0xF7FD,
  27198. Yatcyrillic: 0x0462,
  27199. Ycircle: 0x24CE,
  27200. Ycircumflex: 0x0176,
  27201. Ydieresis: 0x0178,
  27202. Ydieresissmall: 0xF7FF,
  27203. Ydotaccent: 0x1E8E,
  27204. Ydotbelow: 0x1EF4,
  27205. Yericyrillic: 0x042B,
  27206. Yerudieresiscyrillic: 0x04F8,
  27207. Ygrave: 0x1EF2,
  27208. Yhook: 0x01B3,
  27209. Yhookabove: 0x1EF6,
  27210. Yiarmenian: 0x0545,
  27211. Yicyrillic: 0x0407,
  27212. Yiwnarmenian: 0x0552,
  27213. Ymonospace: 0xFF39,
  27214. Ysmall: 0xF779,
  27215. Ytilde: 0x1EF8,
  27216. Yusbigcyrillic: 0x046A,
  27217. Yusbigiotifiedcyrillic: 0x046C,
  27218. Yuslittlecyrillic: 0x0466,
  27219. Yuslittleiotifiedcyrillic: 0x0468,
  27220. Z: 0x005A,
  27221. Zaarmenian: 0x0536,
  27222. Zacute: 0x0179,
  27223. Zcaron: 0x017D,
  27224. Zcaronsmall: 0xF6FF,
  27225. Zcircle: 0x24CF,
  27226. Zcircumflex: 0x1E90,
  27227. Zdot: 0x017B,
  27228. Zdotaccent: 0x017B,
  27229. Zdotbelow: 0x1E92,
  27230. Zecyrillic: 0x0417,
  27231. Zedescendercyrillic: 0x0498,
  27232. Zedieresiscyrillic: 0x04DE,
  27233. Zeta: 0x0396,
  27234. Zhearmenian: 0x053A,
  27235. Zhebrevecyrillic: 0x04C1,
  27236. Zhecyrillic: 0x0416,
  27237. Zhedescendercyrillic: 0x0496,
  27238. Zhedieresiscyrillic: 0x04DC,
  27239. Zlinebelow: 0x1E94,
  27240. Zmonospace: 0xFF3A,
  27241. Zsmall: 0xF77A,
  27242. Zstroke: 0x01B5,
  27243. a: 0x0061,
  27244. aabengali: 0x0986,
  27245. aacute: 0x00E1,
  27246. aadeva: 0x0906,
  27247. aagujarati: 0x0A86,
  27248. aagurmukhi: 0x0A06,
  27249. aamatragurmukhi: 0x0A3E,
  27250. aarusquare: 0x3303,
  27251. aavowelsignbengali: 0x09BE,
  27252. aavowelsigndeva: 0x093E,
  27253. aavowelsigngujarati: 0x0ABE,
  27254. abbreviationmarkarmenian: 0x055F,
  27255. abbreviationsigndeva: 0x0970,
  27256. abengali: 0x0985,
  27257. abopomofo: 0x311A,
  27258. abreve: 0x0103,
  27259. abreveacute: 0x1EAF,
  27260. abrevecyrillic: 0x04D1,
  27261. abrevedotbelow: 0x1EB7,
  27262. abrevegrave: 0x1EB1,
  27263. abrevehookabove: 0x1EB3,
  27264. abrevetilde: 0x1EB5,
  27265. acaron: 0x01CE,
  27266. acircle: 0x24D0,
  27267. acircumflex: 0x00E2,
  27268. acircumflexacute: 0x1EA5,
  27269. acircumflexdotbelow: 0x1EAD,
  27270. acircumflexgrave: 0x1EA7,
  27271. acircumflexhookabove: 0x1EA9,
  27272. acircumflextilde: 0x1EAB,
  27273. acute: 0x00B4,
  27274. acutebelowcmb: 0x0317,
  27275. acutecmb: 0x0301,
  27276. acutecomb: 0x0301,
  27277. acutedeva: 0x0954,
  27278. acutelowmod: 0x02CF,
  27279. acutetonecmb: 0x0341,
  27280. acyrillic: 0x0430,
  27281. adblgrave: 0x0201,
  27282. addakgurmukhi: 0x0A71,
  27283. adeva: 0x0905,
  27284. adieresis: 0x00E4,
  27285. adieresiscyrillic: 0x04D3,
  27286. adieresismacron: 0x01DF,
  27287. adotbelow: 0x1EA1,
  27288. adotmacron: 0x01E1,
  27289. ae: 0x00E6,
  27290. aeacute: 0x01FD,
  27291. aekorean: 0x3150,
  27292. aemacron: 0x01E3,
  27293. afii00208: 0x2015,
  27294. afii08941: 0x20A4,
  27295. afii10017: 0x0410,
  27296. afii10018: 0x0411,
  27297. afii10019: 0x0412,
  27298. afii10020: 0x0413,
  27299. afii10021: 0x0414,
  27300. afii10022: 0x0415,
  27301. afii10023: 0x0401,
  27302. afii10024: 0x0416,
  27303. afii10025: 0x0417,
  27304. afii10026: 0x0418,
  27305. afii10027: 0x0419,
  27306. afii10028: 0x041A,
  27307. afii10029: 0x041B,
  27308. afii10030: 0x041C,
  27309. afii10031: 0x041D,
  27310. afii10032: 0x041E,
  27311. afii10033: 0x041F,
  27312. afii10034: 0x0420,
  27313. afii10035: 0x0421,
  27314. afii10036: 0x0422,
  27315. afii10037: 0x0423,
  27316. afii10038: 0x0424,
  27317. afii10039: 0x0425,
  27318. afii10040: 0x0426,
  27319. afii10041: 0x0427,
  27320. afii10042: 0x0428,
  27321. afii10043: 0x0429,
  27322. afii10044: 0x042A,
  27323. afii10045: 0x042B,
  27324. afii10046: 0x042C,
  27325. afii10047: 0x042D,
  27326. afii10048: 0x042E,
  27327. afii10049: 0x042F,
  27328. afii10050: 0x0490,
  27329. afii10051: 0x0402,
  27330. afii10052: 0x0403,
  27331. afii10053: 0x0404,
  27332. afii10054: 0x0405,
  27333. afii10055: 0x0406,
  27334. afii10056: 0x0407,
  27335. afii10057: 0x0408,
  27336. afii10058: 0x0409,
  27337. afii10059: 0x040A,
  27338. afii10060: 0x040B,
  27339. afii10061: 0x040C,
  27340. afii10062: 0x040E,
  27341. afii10063: 0xF6C4,
  27342. afii10064: 0xF6C5,
  27343. afii10065: 0x0430,
  27344. afii10066: 0x0431,
  27345. afii10067: 0x0432,
  27346. afii10068: 0x0433,
  27347. afii10069: 0x0434,
  27348. afii10070: 0x0435,
  27349. afii10071: 0x0451,
  27350. afii10072: 0x0436,
  27351. afii10073: 0x0437,
  27352. afii10074: 0x0438,
  27353. afii10075: 0x0439,
  27354. afii10076: 0x043A,
  27355. afii10077: 0x043B,
  27356. afii10078: 0x043C,
  27357. afii10079: 0x043D,
  27358. afii10080: 0x043E,
  27359. afii10081: 0x043F,
  27360. afii10082: 0x0440,
  27361. afii10083: 0x0441,
  27362. afii10084: 0x0442,
  27363. afii10085: 0x0443,
  27364. afii10086: 0x0444,
  27365. afii10087: 0x0445,
  27366. afii10088: 0x0446,
  27367. afii10089: 0x0447,
  27368. afii10090: 0x0448,
  27369. afii10091: 0x0449,
  27370. afii10092: 0x044A,
  27371. afii10093: 0x044B,
  27372. afii10094: 0x044C,
  27373. afii10095: 0x044D,
  27374. afii10096: 0x044E,
  27375. afii10097: 0x044F,
  27376. afii10098: 0x0491,
  27377. afii10099: 0x0452,
  27378. afii10100: 0x0453,
  27379. afii10101: 0x0454,
  27380. afii10102: 0x0455,
  27381. afii10103: 0x0456,
  27382. afii10104: 0x0457,
  27383. afii10105: 0x0458,
  27384. afii10106: 0x0459,
  27385. afii10107: 0x045A,
  27386. afii10108: 0x045B,
  27387. afii10109: 0x045C,
  27388. afii10110: 0x045E,
  27389. afii10145: 0x040F,
  27390. afii10146: 0x0462,
  27391. afii10147: 0x0472,
  27392. afii10148: 0x0474,
  27393. afii10192: 0xF6C6,
  27394. afii10193: 0x045F,
  27395. afii10194: 0x0463,
  27396. afii10195: 0x0473,
  27397. afii10196: 0x0475,
  27398. afii10831: 0xF6C7,
  27399. afii10832: 0xF6C8,
  27400. afii10846: 0x04D9,
  27401. afii299: 0x200E,
  27402. afii300: 0x200F,
  27403. afii301: 0x200D,
  27404. afii57381: 0x066A,
  27405. afii57388: 0x060C,
  27406. afii57392: 0x0660,
  27407. afii57393: 0x0661,
  27408. afii57394: 0x0662,
  27409. afii57395: 0x0663,
  27410. afii57396: 0x0664,
  27411. afii57397: 0x0665,
  27412. afii57398: 0x0666,
  27413. afii57399: 0x0667,
  27414. afii57400: 0x0668,
  27415. afii57401: 0x0669,
  27416. afii57403: 0x061B,
  27417. afii57407: 0x061F,
  27418. afii57409: 0x0621,
  27419. afii57410: 0x0622,
  27420. afii57411: 0x0623,
  27421. afii57412: 0x0624,
  27422. afii57413: 0x0625,
  27423. afii57414: 0x0626,
  27424. afii57415: 0x0627,
  27425. afii57416: 0x0628,
  27426. afii57417: 0x0629,
  27427. afii57418: 0x062A,
  27428. afii57419: 0x062B,
  27429. afii57420: 0x062C,
  27430. afii57421: 0x062D,
  27431. afii57422: 0x062E,
  27432. afii57423: 0x062F,
  27433. afii57424: 0x0630,
  27434. afii57425: 0x0631,
  27435. afii57426: 0x0632,
  27436. afii57427: 0x0633,
  27437. afii57428: 0x0634,
  27438. afii57429: 0x0635,
  27439. afii57430: 0x0636,
  27440. afii57431: 0x0637,
  27441. afii57432: 0x0638,
  27442. afii57433: 0x0639,
  27443. afii57434: 0x063A,
  27444. afii57440: 0x0640,
  27445. afii57441: 0x0641,
  27446. afii57442: 0x0642,
  27447. afii57443: 0x0643,
  27448. afii57444: 0x0644,
  27449. afii57445: 0x0645,
  27450. afii57446: 0x0646,
  27451. afii57448: 0x0648,
  27452. afii57449: 0x0649,
  27453. afii57450: 0x064A,
  27454. afii57451: 0x064B,
  27455. afii57452: 0x064C,
  27456. afii57453: 0x064D,
  27457. afii57454: 0x064E,
  27458. afii57455: 0x064F,
  27459. afii57456: 0x0650,
  27460. afii57457: 0x0651,
  27461. afii57458: 0x0652,
  27462. afii57470: 0x0647,
  27463. afii57505: 0x06A4,
  27464. afii57506: 0x067E,
  27465. afii57507: 0x0686,
  27466. afii57508: 0x0698,
  27467. afii57509: 0x06AF,
  27468. afii57511: 0x0679,
  27469. afii57512: 0x0688,
  27470. afii57513: 0x0691,
  27471. afii57514: 0x06BA,
  27472. afii57519: 0x06D2,
  27473. afii57534: 0x06D5,
  27474. afii57636: 0x20AA,
  27475. afii57645: 0x05BE,
  27476. afii57658: 0x05C3,
  27477. afii57664: 0x05D0,
  27478. afii57665: 0x05D1,
  27479. afii57666: 0x05D2,
  27480. afii57667: 0x05D3,
  27481. afii57668: 0x05D4,
  27482. afii57669: 0x05D5,
  27483. afii57670: 0x05D6,
  27484. afii57671: 0x05D7,
  27485. afii57672: 0x05D8,
  27486. afii57673: 0x05D9,
  27487. afii57674: 0x05DA,
  27488. afii57675: 0x05DB,
  27489. afii57676: 0x05DC,
  27490. afii57677: 0x05DD,
  27491. afii57678: 0x05DE,
  27492. afii57679: 0x05DF,
  27493. afii57680: 0x05E0,
  27494. afii57681: 0x05E1,
  27495. afii57682: 0x05E2,
  27496. afii57683: 0x05E3,
  27497. afii57684: 0x05E4,
  27498. afii57685: 0x05E5,
  27499. afii57686: 0x05E6,
  27500. afii57687: 0x05E7,
  27501. afii57688: 0x05E8,
  27502. afii57689: 0x05E9,
  27503. afii57690: 0x05EA,
  27504. afii57694: 0xFB2A,
  27505. afii57695: 0xFB2B,
  27506. afii57700: 0xFB4B,
  27507. afii57705: 0xFB1F,
  27508. afii57716: 0x05F0,
  27509. afii57717: 0x05F1,
  27510. afii57718: 0x05F2,
  27511. afii57723: 0xFB35,
  27512. afii57793: 0x05B4,
  27513. afii57794: 0x05B5,
  27514. afii57795: 0x05B6,
  27515. afii57796: 0x05BB,
  27516. afii57797: 0x05B8,
  27517. afii57798: 0x05B7,
  27518. afii57799: 0x05B0,
  27519. afii57800: 0x05B2,
  27520. afii57801: 0x05B1,
  27521. afii57802: 0x05B3,
  27522. afii57803: 0x05C2,
  27523. afii57804: 0x05C1,
  27524. afii57806: 0x05B9,
  27525. afii57807: 0x05BC,
  27526. afii57839: 0x05BD,
  27527. afii57841: 0x05BF,
  27528. afii57842: 0x05C0,
  27529. afii57929: 0x02BC,
  27530. afii61248: 0x2105,
  27531. afii61289: 0x2113,
  27532. afii61352: 0x2116,
  27533. afii61573: 0x202C,
  27534. afii61574: 0x202D,
  27535. afii61575: 0x202E,
  27536. afii61664: 0x200C,
  27537. afii63167: 0x066D,
  27538. afii64937: 0x02BD,
  27539. agrave: 0x00E0,
  27540. agujarati: 0x0A85,
  27541. agurmukhi: 0x0A05,
  27542. ahiragana: 0x3042,
  27543. ahookabove: 0x1EA3,
  27544. aibengali: 0x0990,
  27545. aibopomofo: 0x311E,
  27546. aideva: 0x0910,
  27547. aiecyrillic: 0x04D5,
  27548. aigujarati: 0x0A90,
  27549. aigurmukhi: 0x0A10,
  27550. aimatragurmukhi: 0x0A48,
  27551. ainarabic: 0x0639,
  27552. ainfinalarabic: 0xFECA,
  27553. aininitialarabic: 0xFECB,
  27554. ainmedialarabic: 0xFECC,
  27555. ainvertedbreve: 0x0203,
  27556. aivowelsignbengali: 0x09C8,
  27557. aivowelsigndeva: 0x0948,
  27558. aivowelsigngujarati: 0x0AC8,
  27559. akatakana: 0x30A2,
  27560. akatakanahalfwidth: 0xFF71,
  27561. akorean: 0x314F,
  27562. alef: 0x05D0,
  27563. alefarabic: 0x0627,
  27564. alefdageshhebrew: 0xFB30,
  27565. aleffinalarabic: 0xFE8E,
  27566. alefhamzaabovearabic: 0x0623,
  27567. alefhamzaabovefinalarabic: 0xFE84,
  27568. alefhamzabelowarabic: 0x0625,
  27569. alefhamzabelowfinalarabic: 0xFE88,
  27570. alefhebrew: 0x05D0,
  27571. aleflamedhebrew: 0xFB4F,
  27572. alefmaddaabovearabic: 0x0622,
  27573. alefmaddaabovefinalarabic: 0xFE82,
  27574. alefmaksuraarabic: 0x0649,
  27575. alefmaksurafinalarabic: 0xFEF0,
  27576. alefmaksurainitialarabic: 0xFEF3,
  27577. alefmaksuramedialarabic: 0xFEF4,
  27578. alefpatahhebrew: 0xFB2E,
  27579. alefqamatshebrew: 0xFB2F,
  27580. aleph: 0x2135,
  27581. allequal: 0x224C,
  27582. alpha: 0x03B1,
  27583. alphatonos: 0x03AC,
  27584. amacron: 0x0101,
  27585. amonospace: 0xFF41,
  27586. ampersand: 0x0026,
  27587. ampersandmonospace: 0xFF06,
  27588. ampersandsmall: 0xF726,
  27589. amsquare: 0x33C2,
  27590. anbopomofo: 0x3122,
  27591. angbopomofo: 0x3124,
  27592. angbracketleft: 0x3008, // This glyph is missing from Adobe's original list.
  27593. angbracketright: 0x3009, // This glyph is missing from Adobe's original list.
  27594. angkhankhuthai: 0x0E5A,
  27595. angle: 0x2220,
  27596. anglebracketleft: 0x3008,
  27597. anglebracketleftvertical: 0xFE3F,
  27598. anglebracketright: 0x3009,
  27599. anglebracketrightvertical: 0xFE40,
  27600. angleleft: 0x2329,
  27601. angleright: 0x232A,
  27602. angstrom: 0x212B,
  27603. anoteleia: 0x0387,
  27604. anudattadeva: 0x0952,
  27605. anusvarabengali: 0x0982,
  27606. anusvaradeva: 0x0902,
  27607. anusvaragujarati: 0x0A82,
  27608. aogonek: 0x0105,
  27609. apaatosquare: 0x3300,
  27610. aparen: 0x249C,
  27611. apostrophearmenian: 0x055A,
  27612. apostrophemod: 0x02BC,
  27613. apple: 0xF8FF,
  27614. approaches: 0x2250,
  27615. approxequal: 0x2248,
  27616. approxequalorimage: 0x2252,
  27617. approximatelyequal: 0x2245,
  27618. araeaekorean: 0x318E,
  27619. araeakorean: 0x318D,
  27620. arc: 0x2312,
  27621. arighthalfring: 0x1E9A,
  27622. aring: 0x00E5,
  27623. aringacute: 0x01FB,
  27624. aringbelow: 0x1E01,
  27625. arrowboth: 0x2194,
  27626. arrowdashdown: 0x21E3,
  27627. arrowdashleft: 0x21E0,
  27628. arrowdashright: 0x21E2,
  27629. arrowdashup: 0x21E1,
  27630. arrowdblboth: 0x21D4,
  27631. arrowdbldown: 0x21D3,
  27632. arrowdblleft: 0x21D0,
  27633. arrowdblright: 0x21D2,
  27634. arrowdblup: 0x21D1,
  27635. arrowdown: 0x2193,
  27636. arrowdownleft: 0x2199,
  27637. arrowdownright: 0x2198,
  27638. arrowdownwhite: 0x21E9,
  27639. arrowheaddownmod: 0x02C5,
  27640. arrowheadleftmod: 0x02C2,
  27641. arrowheadrightmod: 0x02C3,
  27642. arrowheadupmod: 0x02C4,
  27643. arrowhorizex: 0xF8E7,
  27644. arrowleft: 0x2190,
  27645. arrowleftdbl: 0x21D0,
  27646. arrowleftdblstroke: 0x21CD,
  27647. arrowleftoverright: 0x21C6,
  27648. arrowleftwhite: 0x21E6,
  27649. arrowright: 0x2192,
  27650. arrowrightdblstroke: 0x21CF,
  27651. arrowrightheavy: 0x279E,
  27652. arrowrightoverleft: 0x21C4,
  27653. arrowrightwhite: 0x21E8,
  27654. arrowtableft: 0x21E4,
  27655. arrowtabright: 0x21E5,
  27656. arrowup: 0x2191,
  27657. arrowupdn: 0x2195,
  27658. arrowupdnbse: 0x21A8,
  27659. arrowupdownbase: 0x21A8,
  27660. arrowupleft: 0x2196,
  27661. arrowupleftofdown: 0x21C5,
  27662. arrowupright: 0x2197,
  27663. arrowupwhite: 0x21E7,
  27664. arrowvertex: 0xF8E6,
  27665. asciicircum: 0x005E,
  27666. asciicircummonospace: 0xFF3E,
  27667. asciitilde: 0x007E,
  27668. asciitildemonospace: 0xFF5E,
  27669. ascript: 0x0251,
  27670. ascriptturned: 0x0252,
  27671. asmallhiragana: 0x3041,
  27672. asmallkatakana: 0x30A1,
  27673. asmallkatakanahalfwidth: 0xFF67,
  27674. asterisk: 0x002A,
  27675. asteriskaltonearabic: 0x066D,
  27676. asteriskarabic: 0x066D,
  27677. asteriskmath: 0x2217,
  27678. asteriskmonospace: 0xFF0A,
  27679. asterisksmall: 0xFE61,
  27680. asterism: 0x2042,
  27681. asuperior: 0xF6E9,
  27682. asymptoticallyequal: 0x2243,
  27683. at: 0x0040,
  27684. atilde: 0x00E3,
  27685. atmonospace: 0xFF20,
  27686. atsmall: 0xFE6B,
  27687. aturned: 0x0250,
  27688. aubengali: 0x0994,
  27689. aubopomofo: 0x3120,
  27690. audeva: 0x0914,
  27691. augujarati: 0x0A94,
  27692. augurmukhi: 0x0A14,
  27693. aulengthmarkbengali: 0x09D7,
  27694. aumatragurmukhi: 0x0A4C,
  27695. auvowelsignbengali: 0x09CC,
  27696. auvowelsigndeva: 0x094C,
  27697. auvowelsigngujarati: 0x0ACC,
  27698. avagrahadeva: 0x093D,
  27699. aybarmenian: 0x0561,
  27700. ayin: 0x05E2,
  27701. ayinaltonehebrew: 0xFB20,
  27702. ayinhebrew: 0x05E2,
  27703. b: 0x0062,
  27704. babengali: 0x09AC,
  27705. backslash: 0x005C,
  27706. backslashmonospace: 0xFF3C,
  27707. badeva: 0x092C,
  27708. bagujarati: 0x0AAC,
  27709. bagurmukhi: 0x0A2C,
  27710. bahiragana: 0x3070,
  27711. bahtthai: 0x0E3F,
  27712. bakatakana: 0x30D0,
  27713. bar: 0x007C,
  27714. barmonospace: 0xFF5C,
  27715. bbopomofo: 0x3105,
  27716. bcircle: 0x24D1,
  27717. bdotaccent: 0x1E03,
  27718. bdotbelow: 0x1E05,
  27719. beamedsixteenthnotes: 0x266C,
  27720. because: 0x2235,
  27721. becyrillic: 0x0431,
  27722. beharabic: 0x0628,
  27723. behfinalarabic: 0xFE90,
  27724. behinitialarabic: 0xFE91,
  27725. behiragana: 0x3079,
  27726. behmedialarabic: 0xFE92,
  27727. behmeeminitialarabic: 0xFC9F,
  27728. behmeemisolatedarabic: 0xFC08,
  27729. behnoonfinalarabic: 0xFC6D,
  27730. bekatakana: 0x30D9,
  27731. benarmenian: 0x0562,
  27732. bet: 0x05D1,
  27733. beta: 0x03B2,
  27734. betasymbolgreek: 0x03D0,
  27735. betdagesh: 0xFB31,
  27736. betdageshhebrew: 0xFB31,
  27737. bethebrew: 0x05D1,
  27738. betrafehebrew: 0xFB4C,
  27739. bhabengali: 0x09AD,
  27740. bhadeva: 0x092D,
  27741. bhagujarati: 0x0AAD,
  27742. bhagurmukhi: 0x0A2D,
  27743. bhook: 0x0253,
  27744. bihiragana: 0x3073,
  27745. bikatakana: 0x30D3,
  27746. bilabialclick: 0x0298,
  27747. bindigurmukhi: 0x0A02,
  27748. birusquare: 0x3331,
  27749. blackcircle: 0x25CF,
  27750. blackdiamond: 0x25C6,
  27751. blackdownpointingtriangle: 0x25BC,
  27752. blackleftpointingpointer: 0x25C4,
  27753. blackleftpointingtriangle: 0x25C0,
  27754. blacklenticularbracketleft: 0x3010,
  27755. blacklenticularbracketleftvertical: 0xFE3B,
  27756. blacklenticularbracketright: 0x3011,
  27757. blacklenticularbracketrightvertical: 0xFE3C,
  27758. blacklowerlefttriangle: 0x25E3,
  27759. blacklowerrighttriangle: 0x25E2,
  27760. blackrectangle: 0x25AC,
  27761. blackrightpointingpointer: 0x25BA,
  27762. blackrightpointingtriangle: 0x25B6,
  27763. blacksmallsquare: 0x25AA,
  27764. blacksmilingface: 0x263B,
  27765. blacksquare: 0x25A0,
  27766. blackstar: 0x2605,
  27767. blackupperlefttriangle: 0x25E4,
  27768. blackupperrighttriangle: 0x25E5,
  27769. blackuppointingsmalltriangle: 0x25B4,
  27770. blackuppointingtriangle: 0x25B2,
  27771. blank: 0x2423,
  27772. blinebelow: 0x1E07,
  27773. block: 0x2588,
  27774. bmonospace: 0xFF42,
  27775. bobaimaithai: 0x0E1A,
  27776. bohiragana: 0x307C,
  27777. bokatakana: 0x30DC,
  27778. bparen: 0x249D,
  27779. bqsquare: 0x33C3,
  27780. braceex: 0xF8F4,
  27781. braceleft: 0x007B,
  27782. braceleftbt: 0xF8F3,
  27783. braceleftmid: 0xF8F2,
  27784. braceleftmonospace: 0xFF5B,
  27785. braceleftsmall: 0xFE5B,
  27786. bracelefttp: 0xF8F1,
  27787. braceleftvertical: 0xFE37,
  27788. braceright: 0x007D,
  27789. bracerightbt: 0xF8FE,
  27790. bracerightmid: 0xF8FD,
  27791. bracerightmonospace: 0xFF5D,
  27792. bracerightsmall: 0xFE5C,
  27793. bracerighttp: 0xF8FC,
  27794. bracerightvertical: 0xFE38,
  27795. bracketleft: 0x005B,
  27796. bracketleftbt: 0xF8F0,
  27797. bracketleftex: 0xF8EF,
  27798. bracketleftmonospace: 0xFF3B,
  27799. bracketlefttp: 0xF8EE,
  27800. bracketright: 0x005D,
  27801. bracketrightbt: 0xF8FB,
  27802. bracketrightex: 0xF8FA,
  27803. bracketrightmonospace: 0xFF3D,
  27804. bracketrighttp: 0xF8F9,
  27805. breve: 0x02D8,
  27806. brevebelowcmb: 0x032E,
  27807. brevecmb: 0x0306,
  27808. breveinvertedbelowcmb: 0x032F,
  27809. breveinvertedcmb: 0x0311,
  27810. breveinverteddoublecmb: 0x0361,
  27811. bridgebelowcmb: 0x032A,
  27812. bridgeinvertedbelowcmb: 0x033A,
  27813. brokenbar: 0x00A6,
  27814. bstroke: 0x0180,
  27815. bsuperior: 0xF6EA,
  27816. btopbar: 0x0183,
  27817. buhiragana: 0x3076,
  27818. bukatakana: 0x30D6,
  27819. bullet: 0x2022,
  27820. bulletinverse: 0x25D8,
  27821. bulletoperator: 0x2219,
  27822. bullseye: 0x25CE,
  27823. c: 0x0063,
  27824. caarmenian: 0x056E,
  27825. cabengali: 0x099A,
  27826. cacute: 0x0107,
  27827. cadeva: 0x091A,
  27828. cagujarati: 0x0A9A,
  27829. cagurmukhi: 0x0A1A,
  27830. calsquare: 0x3388,
  27831. candrabindubengali: 0x0981,
  27832. candrabinducmb: 0x0310,
  27833. candrabindudeva: 0x0901,
  27834. candrabindugujarati: 0x0A81,
  27835. capslock: 0x21EA,
  27836. careof: 0x2105,
  27837. caron: 0x02C7,
  27838. caronbelowcmb: 0x032C,
  27839. caroncmb: 0x030C,
  27840. carriagereturn: 0x21B5,
  27841. cbopomofo: 0x3118,
  27842. ccaron: 0x010D,
  27843. ccedilla: 0x00E7,
  27844. ccedillaacute: 0x1E09,
  27845. ccircle: 0x24D2,
  27846. ccircumflex: 0x0109,
  27847. ccurl: 0x0255,
  27848. cdot: 0x010B,
  27849. cdotaccent: 0x010B,
  27850. cdsquare: 0x33C5,
  27851. cedilla: 0x00B8,
  27852. cedillacmb: 0x0327,
  27853. cent: 0x00A2,
  27854. centigrade: 0x2103,
  27855. centinferior: 0xF6DF,
  27856. centmonospace: 0xFFE0,
  27857. centoldstyle: 0xF7A2,
  27858. centsuperior: 0xF6E0,
  27859. chaarmenian: 0x0579,
  27860. chabengali: 0x099B,
  27861. chadeva: 0x091B,
  27862. chagujarati: 0x0A9B,
  27863. chagurmukhi: 0x0A1B,
  27864. chbopomofo: 0x3114,
  27865. cheabkhasiancyrillic: 0x04BD,
  27866. checkmark: 0x2713,
  27867. checyrillic: 0x0447,
  27868. chedescenderabkhasiancyrillic: 0x04BF,
  27869. chedescendercyrillic: 0x04B7,
  27870. chedieresiscyrillic: 0x04F5,
  27871. cheharmenian: 0x0573,
  27872. chekhakassiancyrillic: 0x04CC,
  27873. cheverticalstrokecyrillic: 0x04B9,
  27874. chi: 0x03C7,
  27875. chieuchacirclekorean: 0x3277,
  27876. chieuchaparenkorean: 0x3217,
  27877. chieuchcirclekorean: 0x3269,
  27878. chieuchkorean: 0x314A,
  27879. chieuchparenkorean: 0x3209,
  27880. chochangthai: 0x0E0A,
  27881. chochanthai: 0x0E08,
  27882. chochingthai: 0x0E09,
  27883. chochoethai: 0x0E0C,
  27884. chook: 0x0188,
  27885. cieucacirclekorean: 0x3276,
  27886. cieucaparenkorean: 0x3216,
  27887. cieuccirclekorean: 0x3268,
  27888. cieuckorean: 0x3148,
  27889. cieucparenkorean: 0x3208,
  27890. cieucuparenkorean: 0x321C,
  27891. circle: 0x25CB,
  27892. circlecopyrt: 0x00A9, // This glyph is missing from Adobe's original list.
  27893. circlemultiply: 0x2297,
  27894. circleot: 0x2299,
  27895. circleplus: 0x2295,
  27896. circlepostalmark: 0x3036,
  27897. circlewithlefthalfblack: 0x25D0,
  27898. circlewithrighthalfblack: 0x25D1,
  27899. circumflex: 0x02C6,
  27900. circumflexbelowcmb: 0x032D,
  27901. circumflexcmb: 0x0302,
  27902. clear: 0x2327,
  27903. clickalveolar: 0x01C2,
  27904. clickdental: 0x01C0,
  27905. clicklateral: 0x01C1,
  27906. clickretroflex: 0x01C3,
  27907. club: 0x2663,
  27908. clubsuitblack: 0x2663,
  27909. clubsuitwhite: 0x2667,
  27910. cmcubedsquare: 0x33A4,
  27911. cmonospace: 0xFF43,
  27912. cmsquaredsquare: 0x33A0,
  27913. coarmenian: 0x0581,
  27914. colon: 0x003A,
  27915. colonmonetary: 0x20A1,
  27916. colonmonospace: 0xFF1A,
  27917. colonsign: 0x20A1,
  27918. colonsmall: 0xFE55,
  27919. colontriangularhalfmod: 0x02D1,
  27920. colontriangularmod: 0x02D0,
  27921. comma: 0x002C,
  27922. commaabovecmb: 0x0313,
  27923. commaaboverightcmb: 0x0315,
  27924. commaaccent: 0xF6C3,
  27925. commaarabic: 0x060C,
  27926. commaarmenian: 0x055D,
  27927. commainferior: 0xF6E1,
  27928. commamonospace: 0xFF0C,
  27929. commareversedabovecmb: 0x0314,
  27930. commareversedmod: 0x02BD,
  27931. commasmall: 0xFE50,
  27932. commasuperior: 0xF6E2,
  27933. commaturnedabovecmb: 0x0312,
  27934. commaturnedmod: 0x02BB,
  27935. compass: 0x263C,
  27936. congruent: 0x2245,
  27937. contourintegral: 0x222E,
  27938. control: 0x2303,
  27939. controlACK: 0x0006,
  27940. controlBEL: 0x0007,
  27941. controlBS: 0x0008,
  27942. controlCAN: 0x0018,
  27943. controlCR: 0x000D,
  27944. controlDC1: 0x0011,
  27945. controlDC2: 0x0012,
  27946. controlDC3: 0x0013,
  27947. controlDC4: 0x0014,
  27948. controlDEL: 0x007F,
  27949. controlDLE: 0x0010,
  27950. controlEM: 0x0019,
  27951. controlENQ: 0x0005,
  27952. controlEOT: 0x0004,
  27953. controlESC: 0x001B,
  27954. controlETB: 0x0017,
  27955. controlETX: 0x0003,
  27956. controlFF: 0x000C,
  27957. controlFS: 0x001C,
  27958. controlGS: 0x001D,
  27959. controlHT: 0x0009,
  27960. controlLF: 0x000A,
  27961. controlNAK: 0x0015,
  27962. controlRS: 0x001E,
  27963. controlSI: 0x000F,
  27964. controlSO: 0x000E,
  27965. controlSOT: 0x0002,
  27966. controlSTX: 0x0001,
  27967. controlSUB: 0x001A,
  27968. controlSYN: 0x0016,
  27969. controlUS: 0x001F,
  27970. controlVT: 0x000B,
  27971. copyright: 0x00A9,
  27972. copyrightsans: 0xF8E9,
  27973. copyrightserif: 0xF6D9,
  27974. cornerbracketleft: 0x300C,
  27975. cornerbracketlefthalfwidth: 0xFF62,
  27976. cornerbracketleftvertical: 0xFE41,
  27977. cornerbracketright: 0x300D,
  27978. cornerbracketrighthalfwidth: 0xFF63,
  27979. cornerbracketrightvertical: 0xFE42,
  27980. corporationsquare: 0x337F,
  27981. cosquare: 0x33C7,
  27982. coverkgsquare: 0x33C6,
  27983. cparen: 0x249E,
  27984. cruzeiro: 0x20A2,
  27985. cstretched: 0x0297,
  27986. curlyand: 0x22CF,
  27987. curlyor: 0x22CE,
  27988. currency: 0x00A4,
  27989. cyrBreve: 0xF6D1,
  27990. cyrFlex: 0xF6D2,
  27991. cyrbreve: 0xF6D4,
  27992. cyrflex: 0xF6D5,
  27993. d: 0x0064,
  27994. daarmenian: 0x0564,
  27995. dabengali: 0x09A6,
  27996. dadarabic: 0x0636,
  27997. dadeva: 0x0926,
  27998. dadfinalarabic: 0xFEBE,
  27999. dadinitialarabic: 0xFEBF,
  28000. dadmedialarabic: 0xFEC0,
  28001. dagesh: 0x05BC,
  28002. dageshhebrew: 0x05BC,
  28003. dagger: 0x2020,
  28004. daggerdbl: 0x2021,
  28005. dagujarati: 0x0AA6,
  28006. dagurmukhi: 0x0A26,
  28007. dahiragana: 0x3060,
  28008. dakatakana: 0x30C0,
  28009. dalarabic: 0x062F,
  28010. dalet: 0x05D3,
  28011. daletdagesh: 0xFB33,
  28012. daletdageshhebrew: 0xFB33,
  28013. dalethebrew: 0x05D3,
  28014. dalfinalarabic: 0xFEAA,
  28015. dammaarabic: 0x064F,
  28016. dammalowarabic: 0x064F,
  28017. dammatanaltonearabic: 0x064C,
  28018. dammatanarabic: 0x064C,
  28019. danda: 0x0964,
  28020. dargahebrew: 0x05A7,
  28021. dargalefthebrew: 0x05A7,
  28022. dasiapneumatacyrilliccmb: 0x0485,
  28023. dblGrave: 0xF6D3,
  28024. dblanglebracketleft: 0x300A,
  28025. dblanglebracketleftvertical: 0xFE3D,
  28026. dblanglebracketright: 0x300B,
  28027. dblanglebracketrightvertical: 0xFE3E,
  28028. dblarchinvertedbelowcmb: 0x032B,
  28029. dblarrowleft: 0x21D4,
  28030. dblarrowright: 0x21D2,
  28031. dbldanda: 0x0965,
  28032. dblgrave: 0xF6D6,
  28033. dblgravecmb: 0x030F,
  28034. dblintegral: 0x222C,
  28035. dbllowline: 0x2017,
  28036. dbllowlinecmb: 0x0333,
  28037. dbloverlinecmb: 0x033F,
  28038. dblprimemod: 0x02BA,
  28039. dblverticalbar: 0x2016,
  28040. dblverticallineabovecmb: 0x030E,
  28041. dbopomofo: 0x3109,
  28042. dbsquare: 0x33C8,
  28043. dcaron: 0x010F,
  28044. dcedilla: 0x1E11,
  28045. dcircle: 0x24D3,
  28046. dcircumflexbelow: 0x1E13,
  28047. dcroat: 0x0111,
  28048. ddabengali: 0x09A1,
  28049. ddadeva: 0x0921,
  28050. ddagujarati: 0x0AA1,
  28051. ddagurmukhi: 0x0A21,
  28052. ddalarabic: 0x0688,
  28053. ddalfinalarabic: 0xFB89,
  28054. dddhadeva: 0x095C,
  28055. ddhabengali: 0x09A2,
  28056. ddhadeva: 0x0922,
  28057. ddhagujarati: 0x0AA2,
  28058. ddhagurmukhi: 0x0A22,
  28059. ddotaccent: 0x1E0B,
  28060. ddotbelow: 0x1E0D,
  28061. decimalseparatorarabic: 0x066B,
  28062. decimalseparatorpersian: 0x066B,
  28063. decyrillic: 0x0434,
  28064. degree: 0x00B0,
  28065. dehihebrew: 0x05AD,
  28066. dehiragana: 0x3067,
  28067. deicoptic: 0x03EF,
  28068. dekatakana: 0x30C7,
  28069. deleteleft: 0x232B,
  28070. deleteright: 0x2326,
  28071. delta: 0x03B4,
  28072. deltaturned: 0x018D,
  28073. denominatorminusonenumeratorbengali: 0x09F8,
  28074. dezh: 0x02A4,
  28075. dhabengali: 0x09A7,
  28076. dhadeva: 0x0927,
  28077. dhagujarati: 0x0AA7,
  28078. dhagurmukhi: 0x0A27,
  28079. dhook: 0x0257,
  28080. dialytikatonos: 0x0385,
  28081. dialytikatonoscmb: 0x0344,
  28082. diamond: 0x2666,
  28083. diamondsuitwhite: 0x2662,
  28084. dieresis: 0x00A8,
  28085. dieresisacute: 0xF6D7,
  28086. dieresisbelowcmb: 0x0324,
  28087. dieresiscmb: 0x0308,
  28088. dieresisgrave: 0xF6D8,
  28089. dieresistonos: 0x0385,
  28090. dihiragana: 0x3062,
  28091. dikatakana: 0x30C2,
  28092. dittomark: 0x3003,
  28093. divide: 0x00F7,
  28094. divides: 0x2223,
  28095. divisionslash: 0x2215,
  28096. djecyrillic: 0x0452,
  28097. dkshade: 0x2593,
  28098. dlinebelow: 0x1E0F,
  28099. dlsquare: 0x3397,
  28100. dmacron: 0x0111,
  28101. dmonospace: 0xFF44,
  28102. dnblock: 0x2584,
  28103. dochadathai: 0x0E0E,
  28104. dodekthai: 0x0E14,
  28105. dohiragana: 0x3069,
  28106. dokatakana: 0x30C9,
  28107. dollar: 0x0024,
  28108. dollarinferior: 0xF6E3,
  28109. dollarmonospace: 0xFF04,
  28110. dollaroldstyle: 0xF724,
  28111. dollarsmall: 0xFE69,
  28112. dollarsuperior: 0xF6E4,
  28113. dong: 0x20AB,
  28114. dorusquare: 0x3326,
  28115. dotaccent: 0x02D9,
  28116. dotaccentcmb: 0x0307,
  28117. dotbelowcmb: 0x0323,
  28118. dotbelowcomb: 0x0323,
  28119. dotkatakana: 0x30FB,
  28120. dotlessi: 0x0131,
  28121. dotlessj: 0xF6BE,
  28122. dotlessjstrokehook: 0x0284,
  28123. dotmath: 0x22C5,
  28124. dottedcircle: 0x25CC,
  28125. doubleyodpatah: 0xFB1F,
  28126. doubleyodpatahhebrew: 0xFB1F,
  28127. downtackbelowcmb: 0x031E,
  28128. downtackmod: 0x02D5,
  28129. dparen: 0x249F,
  28130. dsuperior: 0xF6EB,
  28131. dtail: 0x0256,
  28132. dtopbar: 0x018C,
  28133. duhiragana: 0x3065,
  28134. dukatakana: 0x30C5,
  28135. dz: 0x01F3,
  28136. dzaltone: 0x02A3,
  28137. dzcaron: 0x01C6,
  28138. dzcurl: 0x02A5,
  28139. dzeabkhasiancyrillic: 0x04E1,
  28140. dzecyrillic: 0x0455,
  28141. dzhecyrillic: 0x045F,
  28142. e: 0x0065,
  28143. eacute: 0x00E9,
  28144. earth: 0x2641,
  28145. ebengali: 0x098F,
  28146. ebopomofo: 0x311C,
  28147. ebreve: 0x0115,
  28148. ecandradeva: 0x090D,
  28149. ecandragujarati: 0x0A8D,
  28150. ecandravowelsigndeva: 0x0945,
  28151. ecandravowelsigngujarati: 0x0AC5,
  28152. ecaron: 0x011B,
  28153. ecedillabreve: 0x1E1D,
  28154. echarmenian: 0x0565,
  28155. echyiwnarmenian: 0x0587,
  28156. ecircle: 0x24D4,
  28157. ecircumflex: 0x00EA,
  28158. ecircumflexacute: 0x1EBF,
  28159. ecircumflexbelow: 0x1E19,
  28160. ecircumflexdotbelow: 0x1EC7,
  28161. ecircumflexgrave: 0x1EC1,
  28162. ecircumflexhookabove: 0x1EC3,
  28163. ecircumflextilde: 0x1EC5,
  28164. ecyrillic: 0x0454,
  28165. edblgrave: 0x0205,
  28166. edeva: 0x090F,
  28167. edieresis: 0x00EB,
  28168. edot: 0x0117,
  28169. edotaccent: 0x0117,
  28170. edotbelow: 0x1EB9,
  28171. eegurmukhi: 0x0A0F,
  28172. eematragurmukhi: 0x0A47,
  28173. efcyrillic: 0x0444,
  28174. egrave: 0x00E8,
  28175. egujarati: 0x0A8F,
  28176. eharmenian: 0x0567,
  28177. ehbopomofo: 0x311D,
  28178. ehiragana: 0x3048,
  28179. ehookabove: 0x1EBB,
  28180. eibopomofo: 0x311F,
  28181. eight: 0x0038,
  28182. eightarabic: 0x0668,
  28183. eightbengali: 0x09EE,
  28184. eightcircle: 0x2467,
  28185. eightcircleinversesansserif: 0x2791,
  28186. eightdeva: 0x096E,
  28187. eighteencircle: 0x2471,
  28188. eighteenparen: 0x2485,
  28189. eighteenperiod: 0x2499,
  28190. eightgujarati: 0x0AEE,
  28191. eightgurmukhi: 0x0A6E,
  28192. eighthackarabic: 0x0668,
  28193. eighthangzhou: 0x3028,
  28194. eighthnotebeamed: 0x266B,
  28195. eightideographicparen: 0x3227,
  28196. eightinferior: 0x2088,
  28197. eightmonospace: 0xFF18,
  28198. eightoldstyle: 0xF738,
  28199. eightparen: 0x247B,
  28200. eightperiod: 0x248F,
  28201. eightpersian: 0x06F8,
  28202. eightroman: 0x2177,
  28203. eightsuperior: 0x2078,
  28204. eightthai: 0x0E58,
  28205. einvertedbreve: 0x0207,
  28206. eiotifiedcyrillic: 0x0465,
  28207. ekatakana: 0x30A8,
  28208. ekatakanahalfwidth: 0xFF74,
  28209. ekonkargurmukhi: 0x0A74,
  28210. ekorean: 0x3154,
  28211. elcyrillic: 0x043B,
  28212. element: 0x2208,
  28213. elevencircle: 0x246A,
  28214. elevenparen: 0x247E,
  28215. elevenperiod: 0x2492,
  28216. elevenroman: 0x217A,
  28217. ellipsis: 0x2026,
  28218. ellipsisvertical: 0x22EE,
  28219. emacron: 0x0113,
  28220. emacronacute: 0x1E17,
  28221. emacrongrave: 0x1E15,
  28222. emcyrillic: 0x043C,
  28223. emdash: 0x2014,
  28224. emdashvertical: 0xFE31,
  28225. emonospace: 0xFF45,
  28226. emphasismarkarmenian: 0x055B,
  28227. emptyset: 0x2205,
  28228. enbopomofo: 0x3123,
  28229. encyrillic: 0x043D,
  28230. endash: 0x2013,
  28231. endashvertical: 0xFE32,
  28232. endescendercyrillic: 0x04A3,
  28233. eng: 0x014B,
  28234. engbopomofo: 0x3125,
  28235. enghecyrillic: 0x04A5,
  28236. enhookcyrillic: 0x04C8,
  28237. enspace: 0x2002,
  28238. eogonek: 0x0119,
  28239. eokorean: 0x3153,
  28240. eopen: 0x025B,
  28241. eopenclosed: 0x029A,
  28242. eopenreversed: 0x025C,
  28243. eopenreversedclosed: 0x025E,
  28244. eopenreversedhook: 0x025D,
  28245. eparen: 0x24A0,
  28246. epsilon: 0x03B5,
  28247. epsilontonos: 0x03AD,
  28248. equal: 0x003D,
  28249. equalmonospace: 0xFF1D,
  28250. equalsmall: 0xFE66,
  28251. equalsuperior: 0x207C,
  28252. equivalence: 0x2261,
  28253. erbopomofo: 0x3126,
  28254. ercyrillic: 0x0440,
  28255. ereversed: 0x0258,
  28256. ereversedcyrillic: 0x044D,
  28257. escyrillic: 0x0441,
  28258. esdescendercyrillic: 0x04AB,
  28259. esh: 0x0283,
  28260. eshcurl: 0x0286,
  28261. eshortdeva: 0x090E,
  28262. eshortvowelsigndeva: 0x0946,
  28263. eshreversedloop: 0x01AA,
  28264. eshsquatreversed: 0x0285,
  28265. esmallhiragana: 0x3047,
  28266. esmallkatakana: 0x30A7,
  28267. esmallkatakanahalfwidth: 0xFF6A,
  28268. estimated: 0x212E,
  28269. esuperior: 0xF6EC,
  28270. eta: 0x03B7,
  28271. etarmenian: 0x0568,
  28272. etatonos: 0x03AE,
  28273. eth: 0x00F0,
  28274. etilde: 0x1EBD,
  28275. etildebelow: 0x1E1B,
  28276. etnahtafoukhhebrew: 0x0591,
  28277. etnahtafoukhlefthebrew: 0x0591,
  28278. etnahtahebrew: 0x0591,
  28279. etnahtalefthebrew: 0x0591,
  28280. eturned: 0x01DD,
  28281. eukorean: 0x3161,
  28282. euro: 0x20AC,
  28283. evowelsignbengali: 0x09C7,
  28284. evowelsigndeva: 0x0947,
  28285. evowelsigngujarati: 0x0AC7,
  28286. exclam: 0x0021,
  28287. exclamarmenian: 0x055C,
  28288. exclamdbl: 0x203C,
  28289. exclamdown: 0x00A1,
  28290. exclamdownsmall: 0xF7A1,
  28291. exclammonospace: 0xFF01,
  28292. exclamsmall: 0xF721,
  28293. existential: 0x2203,
  28294. ezh: 0x0292,
  28295. ezhcaron: 0x01EF,
  28296. ezhcurl: 0x0293,
  28297. ezhreversed: 0x01B9,
  28298. ezhtail: 0x01BA,
  28299. f: 0x0066,
  28300. fadeva: 0x095E,
  28301. fagurmukhi: 0x0A5E,
  28302. fahrenheit: 0x2109,
  28303. fathaarabic: 0x064E,
  28304. fathalowarabic: 0x064E,
  28305. fathatanarabic: 0x064B,
  28306. fbopomofo: 0x3108,
  28307. fcircle: 0x24D5,
  28308. fdotaccent: 0x1E1F,
  28309. feharabic: 0x0641,
  28310. feharmenian: 0x0586,
  28311. fehfinalarabic: 0xFED2,
  28312. fehinitialarabic: 0xFED3,
  28313. fehmedialarabic: 0xFED4,
  28314. feicoptic: 0x03E5,
  28315. female: 0x2640,
  28316. ff: 0xFB00,
  28317. ffi: 0xFB03,
  28318. ffl: 0xFB04,
  28319. fi: 0xFB01,
  28320. fifteencircle: 0x246E,
  28321. fifteenparen: 0x2482,
  28322. fifteenperiod: 0x2496,
  28323. figuredash: 0x2012,
  28324. filledbox: 0x25A0,
  28325. filledrect: 0x25AC,
  28326. finalkaf: 0x05DA,
  28327. finalkafdagesh: 0xFB3A,
  28328. finalkafdageshhebrew: 0xFB3A,
  28329. finalkafhebrew: 0x05DA,
  28330. finalmem: 0x05DD,
  28331. finalmemhebrew: 0x05DD,
  28332. finalnun: 0x05DF,
  28333. finalnunhebrew: 0x05DF,
  28334. finalpe: 0x05E3,
  28335. finalpehebrew: 0x05E3,
  28336. finaltsadi: 0x05E5,
  28337. finaltsadihebrew: 0x05E5,
  28338. firsttonechinese: 0x02C9,
  28339. fisheye: 0x25C9,
  28340. fitacyrillic: 0x0473,
  28341. five: 0x0035,
  28342. fivearabic: 0x0665,
  28343. fivebengali: 0x09EB,
  28344. fivecircle: 0x2464,
  28345. fivecircleinversesansserif: 0x278E,
  28346. fivedeva: 0x096B,
  28347. fiveeighths: 0x215D,
  28348. fivegujarati: 0x0AEB,
  28349. fivegurmukhi: 0x0A6B,
  28350. fivehackarabic: 0x0665,
  28351. fivehangzhou: 0x3025,
  28352. fiveideographicparen: 0x3224,
  28353. fiveinferior: 0x2085,
  28354. fivemonospace: 0xFF15,
  28355. fiveoldstyle: 0xF735,
  28356. fiveparen: 0x2478,
  28357. fiveperiod: 0x248C,
  28358. fivepersian: 0x06F5,
  28359. fiveroman: 0x2174,
  28360. fivesuperior: 0x2075,
  28361. fivethai: 0x0E55,
  28362. fl: 0xFB02,
  28363. florin: 0x0192,
  28364. fmonospace: 0xFF46,
  28365. fmsquare: 0x3399,
  28366. fofanthai: 0x0E1F,
  28367. fofathai: 0x0E1D,
  28368. fongmanthai: 0x0E4F,
  28369. forall: 0x2200,
  28370. four: 0x0034,
  28371. fourarabic: 0x0664,
  28372. fourbengali: 0x09EA,
  28373. fourcircle: 0x2463,
  28374. fourcircleinversesansserif: 0x278D,
  28375. fourdeva: 0x096A,
  28376. fourgujarati: 0x0AEA,
  28377. fourgurmukhi: 0x0A6A,
  28378. fourhackarabic: 0x0664,
  28379. fourhangzhou: 0x3024,
  28380. fourideographicparen: 0x3223,
  28381. fourinferior: 0x2084,
  28382. fourmonospace: 0xFF14,
  28383. fournumeratorbengali: 0x09F7,
  28384. fouroldstyle: 0xF734,
  28385. fourparen: 0x2477,
  28386. fourperiod: 0x248B,
  28387. fourpersian: 0x06F4,
  28388. fourroman: 0x2173,
  28389. foursuperior: 0x2074,
  28390. fourteencircle: 0x246D,
  28391. fourteenparen: 0x2481,
  28392. fourteenperiod: 0x2495,
  28393. fourthai: 0x0E54,
  28394. fourthtonechinese: 0x02CB,
  28395. fparen: 0x24A1,
  28396. fraction: 0x2044,
  28397. franc: 0x20A3,
  28398. g: 0x0067,
  28399. gabengali: 0x0997,
  28400. gacute: 0x01F5,
  28401. gadeva: 0x0917,
  28402. gafarabic: 0x06AF,
  28403. gaffinalarabic: 0xFB93,
  28404. gafinitialarabic: 0xFB94,
  28405. gafmedialarabic: 0xFB95,
  28406. gagujarati: 0x0A97,
  28407. gagurmukhi: 0x0A17,
  28408. gahiragana: 0x304C,
  28409. gakatakana: 0x30AC,
  28410. gamma: 0x03B3,
  28411. gammalatinsmall: 0x0263,
  28412. gammasuperior: 0x02E0,
  28413. gangiacoptic: 0x03EB,
  28414. gbopomofo: 0x310D,
  28415. gbreve: 0x011F,
  28416. gcaron: 0x01E7,
  28417. gcedilla: 0x0123,
  28418. gcircle: 0x24D6,
  28419. gcircumflex: 0x011D,
  28420. gcommaaccent: 0x0123,
  28421. gdot: 0x0121,
  28422. gdotaccent: 0x0121,
  28423. gecyrillic: 0x0433,
  28424. gehiragana: 0x3052,
  28425. gekatakana: 0x30B2,
  28426. geometricallyequal: 0x2251,
  28427. gereshaccenthebrew: 0x059C,
  28428. gereshhebrew: 0x05F3,
  28429. gereshmuqdamhebrew: 0x059D,
  28430. germandbls: 0x00DF,
  28431. gershayimaccenthebrew: 0x059E,
  28432. gershayimhebrew: 0x05F4,
  28433. getamark: 0x3013,
  28434. ghabengali: 0x0998,
  28435. ghadarmenian: 0x0572,
  28436. ghadeva: 0x0918,
  28437. ghagujarati: 0x0A98,
  28438. ghagurmukhi: 0x0A18,
  28439. ghainarabic: 0x063A,
  28440. ghainfinalarabic: 0xFECE,
  28441. ghaininitialarabic: 0xFECF,
  28442. ghainmedialarabic: 0xFED0,
  28443. ghemiddlehookcyrillic: 0x0495,
  28444. ghestrokecyrillic: 0x0493,
  28445. gheupturncyrillic: 0x0491,
  28446. ghhadeva: 0x095A,
  28447. ghhagurmukhi: 0x0A5A,
  28448. ghook: 0x0260,
  28449. ghzsquare: 0x3393,
  28450. gihiragana: 0x304E,
  28451. gikatakana: 0x30AE,
  28452. gimarmenian: 0x0563,
  28453. gimel: 0x05D2,
  28454. gimeldagesh: 0xFB32,
  28455. gimeldageshhebrew: 0xFB32,
  28456. gimelhebrew: 0x05D2,
  28457. gjecyrillic: 0x0453,
  28458. glottalinvertedstroke: 0x01BE,
  28459. glottalstop: 0x0294,
  28460. glottalstopinverted: 0x0296,
  28461. glottalstopmod: 0x02C0,
  28462. glottalstopreversed: 0x0295,
  28463. glottalstopreversedmod: 0x02C1,
  28464. glottalstopreversedsuperior: 0x02E4,
  28465. glottalstopstroke: 0x02A1,
  28466. glottalstopstrokereversed: 0x02A2,
  28467. gmacron: 0x1E21,
  28468. gmonospace: 0xFF47,
  28469. gohiragana: 0x3054,
  28470. gokatakana: 0x30B4,
  28471. gparen: 0x24A2,
  28472. gpasquare: 0x33AC,
  28473. gradient: 0x2207,
  28474. grave: 0x0060,
  28475. gravebelowcmb: 0x0316,
  28476. gravecmb: 0x0300,
  28477. gravecomb: 0x0300,
  28478. gravedeva: 0x0953,
  28479. gravelowmod: 0x02CE,
  28480. gravemonospace: 0xFF40,
  28481. gravetonecmb: 0x0340,
  28482. greater: 0x003E,
  28483. greaterequal: 0x2265,
  28484. greaterequalorless: 0x22DB,
  28485. greatermonospace: 0xFF1E,
  28486. greaterorequivalent: 0x2273,
  28487. greaterorless: 0x2277,
  28488. greateroverequal: 0x2267,
  28489. greatersmall: 0xFE65,
  28490. gscript: 0x0261,
  28491. gstroke: 0x01E5,
  28492. guhiragana: 0x3050,
  28493. guillemotleft: 0x00AB,
  28494. guillemotright: 0x00BB,
  28495. guilsinglleft: 0x2039,
  28496. guilsinglright: 0x203A,
  28497. gukatakana: 0x30B0,
  28498. guramusquare: 0x3318,
  28499. gysquare: 0x33C9,
  28500. h: 0x0068,
  28501. haabkhasiancyrillic: 0x04A9,
  28502. haaltonearabic: 0x06C1,
  28503. habengali: 0x09B9,
  28504. hadescendercyrillic: 0x04B3,
  28505. hadeva: 0x0939,
  28506. hagujarati: 0x0AB9,
  28507. hagurmukhi: 0x0A39,
  28508. haharabic: 0x062D,
  28509. hahfinalarabic: 0xFEA2,
  28510. hahinitialarabic: 0xFEA3,
  28511. hahiragana: 0x306F,
  28512. hahmedialarabic: 0xFEA4,
  28513. haitusquare: 0x332A,
  28514. hakatakana: 0x30CF,
  28515. hakatakanahalfwidth: 0xFF8A,
  28516. halantgurmukhi: 0x0A4D,
  28517. hamzaarabic: 0x0621,
  28518. hamzalowarabic: 0x0621,
  28519. hangulfiller: 0x3164,
  28520. hardsigncyrillic: 0x044A,
  28521. harpoonleftbarbup: 0x21BC,
  28522. harpoonrightbarbup: 0x21C0,
  28523. hasquare: 0x33CA,
  28524. hatafpatah: 0x05B2,
  28525. hatafpatah16: 0x05B2,
  28526. hatafpatah23: 0x05B2,
  28527. hatafpatah2f: 0x05B2,
  28528. hatafpatahhebrew: 0x05B2,
  28529. hatafpatahnarrowhebrew: 0x05B2,
  28530. hatafpatahquarterhebrew: 0x05B2,
  28531. hatafpatahwidehebrew: 0x05B2,
  28532. hatafqamats: 0x05B3,
  28533. hatafqamats1b: 0x05B3,
  28534. hatafqamats28: 0x05B3,
  28535. hatafqamats34: 0x05B3,
  28536. hatafqamatshebrew: 0x05B3,
  28537. hatafqamatsnarrowhebrew: 0x05B3,
  28538. hatafqamatsquarterhebrew: 0x05B3,
  28539. hatafqamatswidehebrew: 0x05B3,
  28540. hatafsegol: 0x05B1,
  28541. hatafsegol17: 0x05B1,
  28542. hatafsegol24: 0x05B1,
  28543. hatafsegol30: 0x05B1,
  28544. hatafsegolhebrew: 0x05B1,
  28545. hatafsegolnarrowhebrew: 0x05B1,
  28546. hatafsegolquarterhebrew: 0x05B1,
  28547. hatafsegolwidehebrew: 0x05B1,
  28548. hbar: 0x0127,
  28549. hbopomofo: 0x310F,
  28550. hbrevebelow: 0x1E2B,
  28551. hcedilla: 0x1E29,
  28552. hcircle: 0x24D7,
  28553. hcircumflex: 0x0125,
  28554. hdieresis: 0x1E27,
  28555. hdotaccent: 0x1E23,
  28556. hdotbelow: 0x1E25,
  28557. he: 0x05D4,
  28558. heart: 0x2665,
  28559. heartsuitblack: 0x2665,
  28560. heartsuitwhite: 0x2661,
  28561. hedagesh: 0xFB34,
  28562. hedageshhebrew: 0xFB34,
  28563. hehaltonearabic: 0x06C1,
  28564. heharabic: 0x0647,
  28565. hehebrew: 0x05D4,
  28566. hehfinalaltonearabic: 0xFBA7,
  28567. hehfinalalttwoarabic: 0xFEEA,
  28568. hehfinalarabic: 0xFEEA,
  28569. hehhamzaabovefinalarabic: 0xFBA5,
  28570. hehhamzaaboveisolatedarabic: 0xFBA4,
  28571. hehinitialaltonearabic: 0xFBA8,
  28572. hehinitialarabic: 0xFEEB,
  28573. hehiragana: 0x3078,
  28574. hehmedialaltonearabic: 0xFBA9,
  28575. hehmedialarabic: 0xFEEC,
  28576. heiseierasquare: 0x337B,
  28577. hekatakana: 0x30D8,
  28578. hekatakanahalfwidth: 0xFF8D,
  28579. hekutaarusquare: 0x3336,
  28580. henghook: 0x0267,
  28581. herutusquare: 0x3339,
  28582. het: 0x05D7,
  28583. hethebrew: 0x05D7,
  28584. hhook: 0x0266,
  28585. hhooksuperior: 0x02B1,
  28586. hieuhacirclekorean: 0x327B,
  28587. hieuhaparenkorean: 0x321B,
  28588. hieuhcirclekorean: 0x326D,
  28589. hieuhkorean: 0x314E,
  28590. hieuhparenkorean: 0x320D,
  28591. hihiragana: 0x3072,
  28592. hikatakana: 0x30D2,
  28593. hikatakanahalfwidth: 0xFF8B,
  28594. hiriq: 0x05B4,
  28595. hiriq14: 0x05B4,
  28596. hiriq21: 0x05B4,
  28597. hiriq2d: 0x05B4,
  28598. hiriqhebrew: 0x05B4,
  28599. hiriqnarrowhebrew: 0x05B4,
  28600. hiriqquarterhebrew: 0x05B4,
  28601. hiriqwidehebrew: 0x05B4,
  28602. hlinebelow: 0x1E96,
  28603. hmonospace: 0xFF48,
  28604. hoarmenian: 0x0570,
  28605. hohipthai: 0x0E2B,
  28606. hohiragana: 0x307B,
  28607. hokatakana: 0x30DB,
  28608. hokatakanahalfwidth: 0xFF8E,
  28609. holam: 0x05B9,
  28610. holam19: 0x05B9,
  28611. holam26: 0x05B9,
  28612. holam32: 0x05B9,
  28613. holamhebrew: 0x05B9,
  28614. holamnarrowhebrew: 0x05B9,
  28615. holamquarterhebrew: 0x05B9,
  28616. holamwidehebrew: 0x05B9,
  28617. honokhukthai: 0x0E2E,
  28618. hookabovecomb: 0x0309,
  28619. hookcmb: 0x0309,
  28620. hookpalatalizedbelowcmb: 0x0321,
  28621. hookretroflexbelowcmb: 0x0322,
  28622. hoonsquare: 0x3342,
  28623. horicoptic: 0x03E9,
  28624. horizontalbar: 0x2015,
  28625. horncmb: 0x031B,
  28626. hotsprings: 0x2668,
  28627. house: 0x2302,
  28628. hparen: 0x24A3,
  28629. hsuperior: 0x02B0,
  28630. hturned: 0x0265,
  28631. huhiragana: 0x3075,
  28632. huiitosquare: 0x3333,
  28633. hukatakana: 0x30D5,
  28634. hukatakanahalfwidth: 0xFF8C,
  28635. hungarumlaut: 0x02DD,
  28636. hungarumlautcmb: 0x030B,
  28637. hv: 0x0195,
  28638. hyphen: 0x002D,
  28639. hypheninferior: 0xF6E5,
  28640. hyphenmonospace: 0xFF0D,
  28641. hyphensmall: 0xFE63,
  28642. hyphensuperior: 0xF6E6,
  28643. hyphentwo: 0x2010,
  28644. i: 0x0069,
  28645. iacute: 0x00ED,
  28646. iacyrillic: 0x044F,
  28647. ibengali: 0x0987,
  28648. ibopomofo: 0x3127,
  28649. ibreve: 0x012D,
  28650. icaron: 0x01D0,
  28651. icircle: 0x24D8,
  28652. icircumflex: 0x00EE,
  28653. icyrillic: 0x0456,
  28654. idblgrave: 0x0209,
  28655. ideographearthcircle: 0x328F,
  28656. ideographfirecircle: 0x328B,
  28657. ideographicallianceparen: 0x323F,
  28658. ideographiccallparen: 0x323A,
  28659. ideographiccentrecircle: 0x32A5,
  28660. ideographicclose: 0x3006,
  28661. ideographiccomma: 0x3001,
  28662. ideographiccommaleft: 0xFF64,
  28663. ideographiccongratulationparen: 0x3237,
  28664. ideographiccorrectcircle: 0x32A3,
  28665. ideographicearthparen: 0x322F,
  28666. ideographicenterpriseparen: 0x323D,
  28667. ideographicexcellentcircle: 0x329D,
  28668. ideographicfestivalparen: 0x3240,
  28669. ideographicfinancialcircle: 0x3296,
  28670. ideographicfinancialparen: 0x3236,
  28671. ideographicfireparen: 0x322B,
  28672. ideographichaveparen: 0x3232,
  28673. ideographichighcircle: 0x32A4,
  28674. ideographiciterationmark: 0x3005,
  28675. ideographiclaborcircle: 0x3298,
  28676. ideographiclaborparen: 0x3238,
  28677. ideographicleftcircle: 0x32A7,
  28678. ideographiclowcircle: 0x32A6,
  28679. ideographicmedicinecircle: 0x32A9,
  28680. ideographicmetalparen: 0x322E,
  28681. ideographicmoonparen: 0x322A,
  28682. ideographicnameparen: 0x3234,
  28683. ideographicperiod: 0x3002,
  28684. ideographicprintcircle: 0x329E,
  28685. ideographicreachparen: 0x3243,
  28686. ideographicrepresentparen: 0x3239,
  28687. ideographicresourceparen: 0x323E,
  28688. ideographicrightcircle: 0x32A8,
  28689. ideographicsecretcircle: 0x3299,
  28690. ideographicselfparen: 0x3242,
  28691. ideographicsocietyparen: 0x3233,
  28692. ideographicspace: 0x3000,
  28693. ideographicspecialparen: 0x3235,
  28694. ideographicstockparen: 0x3231,
  28695. ideographicstudyparen: 0x323B,
  28696. ideographicsunparen: 0x3230,
  28697. ideographicsuperviseparen: 0x323C,
  28698. ideographicwaterparen: 0x322C,
  28699. ideographicwoodparen: 0x322D,
  28700. ideographiczero: 0x3007,
  28701. ideographmetalcircle: 0x328E,
  28702. ideographmooncircle: 0x328A,
  28703. ideographnamecircle: 0x3294,
  28704. ideographsuncircle: 0x3290,
  28705. ideographwatercircle: 0x328C,
  28706. ideographwoodcircle: 0x328D,
  28707. ideva: 0x0907,
  28708. idieresis: 0x00EF,
  28709. idieresisacute: 0x1E2F,
  28710. idieresiscyrillic: 0x04E5,
  28711. idotbelow: 0x1ECB,
  28712. iebrevecyrillic: 0x04D7,
  28713. iecyrillic: 0x0435,
  28714. ieungacirclekorean: 0x3275,
  28715. ieungaparenkorean: 0x3215,
  28716. ieungcirclekorean: 0x3267,
  28717. ieungkorean: 0x3147,
  28718. ieungparenkorean: 0x3207,
  28719. igrave: 0x00EC,
  28720. igujarati: 0x0A87,
  28721. igurmukhi: 0x0A07,
  28722. ihiragana: 0x3044,
  28723. ihookabove: 0x1EC9,
  28724. iibengali: 0x0988,
  28725. iicyrillic: 0x0438,
  28726. iideva: 0x0908,
  28727. iigujarati: 0x0A88,
  28728. iigurmukhi: 0x0A08,
  28729. iimatragurmukhi: 0x0A40,
  28730. iinvertedbreve: 0x020B,
  28731. iishortcyrillic: 0x0439,
  28732. iivowelsignbengali: 0x09C0,
  28733. iivowelsigndeva: 0x0940,
  28734. iivowelsigngujarati: 0x0AC0,
  28735. ij: 0x0133,
  28736. ikatakana: 0x30A4,
  28737. ikatakanahalfwidth: 0xFF72,
  28738. ikorean: 0x3163,
  28739. ilde: 0x02DC,
  28740. iluyhebrew: 0x05AC,
  28741. imacron: 0x012B,
  28742. imacroncyrillic: 0x04E3,
  28743. imageorapproximatelyequal: 0x2253,
  28744. imatragurmukhi: 0x0A3F,
  28745. imonospace: 0xFF49,
  28746. increment: 0x2206,
  28747. infinity: 0x221E,
  28748. iniarmenian: 0x056B,
  28749. integral: 0x222B,
  28750. integralbottom: 0x2321,
  28751. integralbt: 0x2321,
  28752. integralex: 0xF8F5,
  28753. integraltop: 0x2320,
  28754. integraltp: 0x2320,
  28755. intersection: 0x2229,
  28756. intisquare: 0x3305,
  28757. invbullet: 0x25D8,
  28758. invcircle: 0x25D9,
  28759. invsmileface: 0x263B,
  28760. iocyrillic: 0x0451,
  28761. iogonek: 0x012F,
  28762. iota: 0x03B9,
  28763. iotadieresis: 0x03CA,
  28764. iotadieresistonos: 0x0390,
  28765. iotalatin: 0x0269,
  28766. iotatonos: 0x03AF,
  28767. iparen: 0x24A4,
  28768. irigurmukhi: 0x0A72,
  28769. ismallhiragana: 0x3043,
  28770. ismallkatakana: 0x30A3,
  28771. ismallkatakanahalfwidth: 0xFF68,
  28772. issharbengali: 0x09FA,
  28773. istroke: 0x0268,
  28774. isuperior: 0xF6ED,
  28775. iterationhiragana: 0x309D,
  28776. iterationkatakana: 0x30FD,
  28777. itilde: 0x0129,
  28778. itildebelow: 0x1E2D,
  28779. iubopomofo: 0x3129,
  28780. iucyrillic: 0x044E,
  28781. ivowelsignbengali: 0x09BF,
  28782. ivowelsigndeva: 0x093F,
  28783. ivowelsigngujarati: 0x0ABF,
  28784. izhitsacyrillic: 0x0475,
  28785. izhitsadblgravecyrillic: 0x0477,
  28786. j: 0x006A,
  28787. jaarmenian: 0x0571,
  28788. jabengali: 0x099C,
  28789. jadeva: 0x091C,
  28790. jagujarati: 0x0A9C,
  28791. jagurmukhi: 0x0A1C,
  28792. jbopomofo: 0x3110,
  28793. jcaron: 0x01F0,
  28794. jcircle: 0x24D9,
  28795. jcircumflex: 0x0135,
  28796. jcrossedtail: 0x029D,
  28797. jdotlessstroke: 0x025F,
  28798. jecyrillic: 0x0458,
  28799. jeemarabic: 0x062C,
  28800. jeemfinalarabic: 0xFE9E,
  28801. jeeminitialarabic: 0xFE9F,
  28802. jeemmedialarabic: 0xFEA0,
  28803. jeharabic: 0x0698,
  28804. jehfinalarabic: 0xFB8B,
  28805. jhabengali: 0x099D,
  28806. jhadeva: 0x091D,
  28807. jhagujarati: 0x0A9D,
  28808. jhagurmukhi: 0x0A1D,
  28809. jheharmenian: 0x057B,
  28810. jis: 0x3004,
  28811. jmonospace: 0xFF4A,
  28812. jparen: 0x24A5,
  28813. jsuperior: 0x02B2,
  28814. k: 0x006B,
  28815. kabashkircyrillic: 0x04A1,
  28816. kabengali: 0x0995,
  28817. kacute: 0x1E31,
  28818. kacyrillic: 0x043A,
  28819. kadescendercyrillic: 0x049B,
  28820. kadeva: 0x0915,
  28821. kaf: 0x05DB,
  28822. kafarabic: 0x0643,
  28823. kafdagesh: 0xFB3B,
  28824. kafdageshhebrew: 0xFB3B,
  28825. kaffinalarabic: 0xFEDA,
  28826. kafhebrew: 0x05DB,
  28827. kafinitialarabic: 0xFEDB,
  28828. kafmedialarabic: 0xFEDC,
  28829. kafrafehebrew: 0xFB4D,
  28830. kagujarati: 0x0A95,
  28831. kagurmukhi: 0x0A15,
  28832. kahiragana: 0x304B,
  28833. kahookcyrillic: 0x04C4,
  28834. kakatakana: 0x30AB,
  28835. kakatakanahalfwidth: 0xFF76,
  28836. kappa: 0x03BA,
  28837. kappasymbolgreek: 0x03F0,
  28838. kapyeounmieumkorean: 0x3171,
  28839. kapyeounphieuphkorean: 0x3184,
  28840. kapyeounpieupkorean: 0x3178,
  28841. kapyeounssangpieupkorean: 0x3179,
  28842. karoriisquare: 0x330D,
  28843. kashidaautoarabic: 0x0640,
  28844. kashidaautonosidebearingarabic: 0x0640,
  28845. kasmallkatakana: 0x30F5,
  28846. kasquare: 0x3384,
  28847. kasraarabic: 0x0650,
  28848. kasratanarabic: 0x064D,
  28849. kastrokecyrillic: 0x049F,
  28850. katahiraprolongmarkhalfwidth: 0xFF70,
  28851. kaverticalstrokecyrillic: 0x049D,
  28852. kbopomofo: 0x310E,
  28853. kcalsquare: 0x3389,
  28854. kcaron: 0x01E9,
  28855. kcedilla: 0x0137,
  28856. kcircle: 0x24DA,
  28857. kcommaaccent: 0x0137,
  28858. kdotbelow: 0x1E33,
  28859. keharmenian: 0x0584,
  28860. kehiragana: 0x3051,
  28861. kekatakana: 0x30B1,
  28862. kekatakanahalfwidth: 0xFF79,
  28863. kenarmenian: 0x056F,
  28864. kesmallkatakana: 0x30F6,
  28865. kgreenlandic: 0x0138,
  28866. khabengali: 0x0996,
  28867. khacyrillic: 0x0445,
  28868. khadeva: 0x0916,
  28869. khagujarati: 0x0A96,
  28870. khagurmukhi: 0x0A16,
  28871. khaharabic: 0x062E,
  28872. khahfinalarabic: 0xFEA6,
  28873. khahinitialarabic: 0xFEA7,
  28874. khahmedialarabic: 0xFEA8,
  28875. kheicoptic: 0x03E7,
  28876. khhadeva: 0x0959,
  28877. khhagurmukhi: 0x0A59,
  28878. khieukhacirclekorean: 0x3278,
  28879. khieukhaparenkorean: 0x3218,
  28880. khieukhcirclekorean: 0x326A,
  28881. khieukhkorean: 0x314B,
  28882. khieukhparenkorean: 0x320A,
  28883. khokhaithai: 0x0E02,
  28884. khokhonthai: 0x0E05,
  28885. khokhuatthai: 0x0E03,
  28886. khokhwaithai: 0x0E04,
  28887. khomutthai: 0x0E5B,
  28888. khook: 0x0199,
  28889. khorakhangthai: 0x0E06,
  28890. khzsquare: 0x3391,
  28891. kihiragana: 0x304D,
  28892. kikatakana: 0x30AD,
  28893. kikatakanahalfwidth: 0xFF77,
  28894. kiroguramusquare: 0x3315,
  28895. kiromeetorusquare: 0x3316,
  28896. kirosquare: 0x3314,
  28897. kiyeokacirclekorean: 0x326E,
  28898. kiyeokaparenkorean: 0x320E,
  28899. kiyeokcirclekorean: 0x3260,
  28900. kiyeokkorean: 0x3131,
  28901. kiyeokparenkorean: 0x3200,
  28902. kiyeoksioskorean: 0x3133,
  28903. kjecyrillic: 0x045C,
  28904. klinebelow: 0x1E35,
  28905. klsquare: 0x3398,
  28906. kmcubedsquare: 0x33A6,
  28907. kmonospace: 0xFF4B,
  28908. kmsquaredsquare: 0x33A2,
  28909. kohiragana: 0x3053,
  28910. kohmsquare: 0x33C0,
  28911. kokaithai: 0x0E01,
  28912. kokatakana: 0x30B3,
  28913. kokatakanahalfwidth: 0xFF7A,
  28914. kooposquare: 0x331E,
  28915. koppacyrillic: 0x0481,
  28916. koreanstandardsymbol: 0x327F,
  28917. koroniscmb: 0x0343,
  28918. kparen: 0x24A6,
  28919. kpasquare: 0x33AA,
  28920. ksicyrillic: 0x046F,
  28921. ktsquare: 0x33CF,
  28922. kturned: 0x029E,
  28923. kuhiragana: 0x304F,
  28924. kukatakana: 0x30AF,
  28925. kukatakanahalfwidth: 0xFF78,
  28926. kvsquare: 0x33B8,
  28927. kwsquare: 0x33BE,
  28928. l: 0x006C,
  28929. labengali: 0x09B2,
  28930. lacute: 0x013A,
  28931. ladeva: 0x0932,
  28932. lagujarati: 0x0AB2,
  28933. lagurmukhi: 0x0A32,
  28934. lakkhangyaothai: 0x0E45,
  28935. lamaleffinalarabic: 0xFEFC,
  28936. lamalefhamzaabovefinalarabic: 0xFEF8,
  28937. lamalefhamzaaboveisolatedarabic: 0xFEF7,
  28938. lamalefhamzabelowfinalarabic: 0xFEFA,
  28939. lamalefhamzabelowisolatedarabic: 0xFEF9,
  28940. lamalefisolatedarabic: 0xFEFB,
  28941. lamalefmaddaabovefinalarabic: 0xFEF6,
  28942. lamalefmaddaaboveisolatedarabic: 0xFEF5,
  28943. lamarabic: 0x0644,
  28944. lambda: 0x03BB,
  28945. lambdastroke: 0x019B,
  28946. lamed: 0x05DC,
  28947. lameddagesh: 0xFB3C,
  28948. lameddageshhebrew: 0xFB3C,
  28949. lamedhebrew: 0x05DC,
  28950. lamfinalarabic: 0xFEDE,
  28951. lamhahinitialarabic: 0xFCCA,
  28952. laminitialarabic: 0xFEDF,
  28953. lamjeeminitialarabic: 0xFCC9,
  28954. lamkhahinitialarabic: 0xFCCB,
  28955. lamlamhehisolatedarabic: 0xFDF2,
  28956. lammedialarabic: 0xFEE0,
  28957. lammeemhahinitialarabic: 0xFD88,
  28958. lammeeminitialarabic: 0xFCCC,
  28959. largecircle: 0x25EF,
  28960. lbar: 0x019A,
  28961. lbelt: 0x026C,
  28962. lbopomofo: 0x310C,
  28963. lcaron: 0x013E,
  28964. lcedilla: 0x013C,
  28965. lcircle: 0x24DB,
  28966. lcircumflexbelow: 0x1E3D,
  28967. lcommaaccent: 0x013C,
  28968. ldot: 0x0140,
  28969. ldotaccent: 0x0140,
  28970. ldotbelow: 0x1E37,
  28971. ldotbelowmacron: 0x1E39,
  28972. leftangleabovecmb: 0x031A,
  28973. lefttackbelowcmb: 0x0318,
  28974. less: 0x003C,
  28975. lessequal: 0x2264,
  28976. lessequalorgreater: 0x22DA,
  28977. lessmonospace: 0xFF1C,
  28978. lessorequivalent: 0x2272,
  28979. lessorgreater: 0x2276,
  28980. lessoverequal: 0x2266,
  28981. lesssmall: 0xFE64,
  28982. lezh: 0x026E,
  28983. lfblock: 0x258C,
  28984. lhookretroflex: 0x026D,
  28985. lira: 0x20A4,
  28986. liwnarmenian: 0x056C,
  28987. lj: 0x01C9,
  28988. ljecyrillic: 0x0459,
  28989. ll: 0xF6C0,
  28990. lladeva: 0x0933,
  28991. llagujarati: 0x0AB3,
  28992. llinebelow: 0x1E3B,
  28993. llladeva: 0x0934,
  28994. llvocalicbengali: 0x09E1,
  28995. llvocalicdeva: 0x0961,
  28996. llvocalicvowelsignbengali: 0x09E3,
  28997. llvocalicvowelsigndeva: 0x0963,
  28998. lmiddletilde: 0x026B,
  28999. lmonospace: 0xFF4C,
  29000. lmsquare: 0x33D0,
  29001. lochulathai: 0x0E2C,
  29002. logicaland: 0x2227,
  29003. logicalnot: 0x00AC,
  29004. logicalnotreversed: 0x2310,
  29005. logicalor: 0x2228,
  29006. lolingthai: 0x0E25,
  29007. longs: 0x017F,
  29008. lowlinecenterline: 0xFE4E,
  29009. lowlinecmb: 0x0332,
  29010. lowlinedashed: 0xFE4D,
  29011. lozenge: 0x25CA,
  29012. lparen: 0x24A7,
  29013. lslash: 0x0142,
  29014. lsquare: 0x2113,
  29015. lsuperior: 0xF6EE,
  29016. ltshade: 0x2591,
  29017. luthai: 0x0E26,
  29018. lvocalicbengali: 0x098C,
  29019. lvocalicdeva: 0x090C,
  29020. lvocalicvowelsignbengali: 0x09E2,
  29021. lvocalicvowelsigndeva: 0x0962,
  29022. lxsquare: 0x33D3,
  29023. m: 0x006D,
  29024. mabengali: 0x09AE,
  29025. macron: 0x00AF,
  29026. macronbelowcmb: 0x0331,
  29027. macroncmb: 0x0304,
  29028. macronlowmod: 0x02CD,
  29029. macronmonospace: 0xFFE3,
  29030. macute: 0x1E3F,
  29031. madeva: 0x092E,
  29032. magujarati: 0x0AAE,
  29033. magurmukhi: 0x0A2E,
  29034. mahapakhhebrew: 0x05A4,
  29035. mahapakhlefthebrew: 0x05A4,
  29036. mahiragana: 0x307E,
  29037. maichattawalowleftthai: 0xF895,
  29038. maichattawalowrightthai: 0xF894,
  29039. maichattawathai: 0x0E4B,
  29040. maichattawaupperleftthai: 0xF893,
  29041. maieklowleftthai: 0xF88C,
  29042. maieklowrightthai: 0xF88B,
  29043. maiekthai: 0x0E48,
  29044. maiekupperleftthai: 0xF88A,
  29045. maihanakatleftthai: 0xF884,
  29046. maihanakatthai: 0x0E31,
  29047. maitaikhuleftthai: 0xF889,
  29048. maitaikhuthai: 0x0E47,
  29049. maitholowleftthai: 0xF88F,
  29050. maitholowrightthai: 0xF88E,
  29051. maithothai: 0x0E49,
  29052. maithoupperleftthai: 0xF88D,
  29053. maitrilowleftthai: 0xF892,
  29054. maitrilowrightthai: 0xF891,
  29055. maitrithai: 0x0E4A,
  29056. maitriupperleftthai: 0xF890,
  29057. maiyamokthai: 0x0E46,
  29058. makatakana: 0x30DE,
  29059. makatakanahalfwidth: 0xFF8F,
  29060. male: 0x2642,
  29061. mansyonsquare: 0x3347,
  29062. maqafhebrew: 0x05BE,
  29063. mars: 0x2642,
  29064. masoracirclehebrew: 0x05AF,
  29065. masquare: 0x3383,
  29066. mbopomofo: 0x3107,
  29067. mbsquare: 0x33D4,
  29068. mcircle: 0x24DC,
  29069. mcubedsquare: 0x33A5,
  29070. mdotaccent: 0x1E41,
  29071. mdotbelow: 0x1E43,
  29072. meemarabic: 0x0645,
  29073. meemfinalarabic: 0xFEE2,
  29074. meeminitialarabic: 0xFEE3,
  29075. meemmedialarabic: 0xFEE4,
  29076. meemmeeminitialarabic: 0xFCD1,
  29077. meemmeemisolatedarabic: 0xFC48,
  29078. meetorusquare: 0x334D,
  29079. mehiragana: 0x3081,
  29080. meizierasquare: 0x337E,
  29081. mekatakana: 0x30E1,
  29082. mekatakanahalfwidth: 0xFF92,
  29083. mem: 0x05DE,
  29084. memdagesh: 0xFB3E,
  29085. memdageshhebrew: 0xFB3E,
  29086. memhebrew: 0x05DE,
  29087. menarmenian: 0x0574,
  29088. merkhahebrew: 0x05A5,
  29089. merkhakefulahebrew: 0x05A6,
  29090. merkhakefulalefthebrew: 0x05A6,
  29091. merkhalefthebrew: 0x05A5,
  29092. mhook: 0x0271,
  29093. mhzsquare: 0x3392,
  29094. middledotkatakanahalfwidth: 0xFF65,
  29095. middot: 0x00B7,
  29096. mieumacirclekorean: 0x3272,
  29097. mieumaparenkorean: 0x3212,
  29098. mieumcirclekorean: 0x3264,
  29099. mieumkorean: 0x3141,
  29100. mieumpansioskorean: 0x3170,
  29101. mieumparenkorean: 0x3204,
  29102. mieumpieupkorean: 0x316E,
  29103. mieumsioskorean: 0x316F,
  29104. mihiragana: 0x307F,
  29105. mikatakana: 0x30DF,
  29106. mikatakanahalfwidth: 0xFF90,
  29107. minus: 0x2212,
  29108. minusbelowcmb: 0x0320,
  29109. minuscircle: 0x2296,
  29110. minusmod: 0x02D7,
  29111. minusplus: 0x2213,
  29112. minute: 0x2032,
  29113. miribaarusquare: 0x334A,
  29114. mirisquare: 0x3349,
  29115. mlonglegturned: 0x0270,
  29116. mlsquare: 0x3396,
  29117. mmcubedsquare: 0x33A3,
  29118. mmonospace: 0xFF4D,
  29119. mmsquaredsquare: 0x339F,
  29120. mohiragana: 0x3082,
  29121. mohmsquare: 0x33C1,
  29122. mokatakana: 0x30E2,
  29123. mokatakanahalfwidth: 0xFF93,
  29124. molsquare: 0x33D6,
  29125. momathai: 0x0E21,
  29126. moverssquare: 0x33A7,
  29127. moverssquaredsquare: 0x33A8,
  29128. mparen: 0x24A8,
  29129. mpasquare: 0x33AB,
  29130. mssquare: 0x33B3,
  29131. msuperior: 0xF6EF,
  29132. mturned: 0x026F,
  29133. mu: 0x00B5,
  29134. mu1: 0x00B5,
  29135. muasquare: 0x3382,
  29136. muchgreater: 0x226B,
  29137. muchless: 0x226A,
  29138. mufsquare: 0x338C,
  29139. mugreek: 0x03BC,
  29140. mugsquare: 0x338D,
  29141. muhiragana: 0x3080,
  29142. mukatakana: 0x30E0,
  29143. mukatakanahalfwidth: 0xFF91,
  29144. mulsquare: 0x3395,
  29145. multiply: 0x00D7,
  29146. mumsquare: 0x339B,
  29147. munahhebrew: 0x05A3,
  29148. munahlefthebrew: 0x05A3,
  29149. musicalnote: 0x266A,
  29150. musicalnotedbl: 0x266B,
  29151. musicflatsign: 0x266D,
  29152. musicsharpsign: 0x266F,
  29153. mussquare: 0x33B2,
  29154. muvsquare: 0x33B6,
  29155. muwsquare: 0x33BC,
  29156. mvmegasquare: 0x33B9,
  29157. mvsquare: 0x33B7,
  29158. mwmegasquare: 0x33BF,
  29159. mwsquare: 0x33BD,
  29160. n: 0x006E,
  29161. nabengali: 0x09A8,
  29162. nabla: 0x2207,
  29163. nacute: 0x0144,
  29164. nadeva: 0x0928,
  29165. nagujarati: 0x0AA8,
  29166. nagurmukhi: 0x0A28,
  29167. nahiragana: 0x306A,
  29168. nakatakana: 0x30CA,
  29169. nakatakanahalfwidth: 0xFF85,
  29170. napostrophe: 0x0149,
  29171. nasquare: 0x3381,
  29172. nbopomofo: 0x310B,
  29173. nbspace: 0x00A0,
  29174. ncaron: 0x0148,
  29175. ncedilla: 0x0146,
  29176. ncircle: 0x24DD,
  29177. ncircumflexbelow: 0x1E4B,
  29178. ncommaaccent: 0x0146,
  29179. ndotaccent: 0x1E45,
  29180. ndotbelow: 0x1E47,
  29181. nehiragana: 0x306D,
  29182. nekatakana: 0x30CD,
  29183. nekatakanahalfwidth: 0xFF88,
  29184. newsheqelsign: 0x20AA,
  29185. nfsquare: 0x338B,
  29186. ngabengali: 0x0999,
  29187. ngadeva: 0x0919,
  29188. ngagujarati: 0x0A99,
  29189. ngagurmukhi: 0x0A19,
  29190. ngonguthai: 0x0E07,
  29191. nhiragana: 0x3093,
  29192. nhookleft: 0x0272,
  29193. nhookretroflex: 0x0273,
  29194. nieunacirclekorean: 0x326F,
  29195. nieunaparenkorean: 0x320F,
  29196. nieuncieuckorean: 0x3135,
  29197. nieuncirclekorean: 0x3261,
  29198. nieunhieuhkorean: 0x3136,
  29199. nieunkorean: 0x3134,
  29200. nieunpansioskorean: 0x3168,
  29201. nieunparenkorean: 0x3201,
  29202. nieunsioskorean: 0x3167,
  29203. nieuntikeutkorean: 0x3166,
  29204. nihiragana: 0x306B,
  29205. nikatakana: 0x30CB,
  29206. nikatakanahalfwidth: 0xFF86,
  29207. nikhahitleftthai: 0xF899,
  29208. nikhahitthai: 0x0E4D,
  29209. nine: 0x0039,
  29210. ninearabic: 0x0669,
  29211. ninebengali: 0x09EF,
  29212. ninecircle: 0x2468,
  29213. ninecircleinversesansserif: 0x2792,
  29214. ninedeva: 0x096F,
  29215. ninegujarati: 0x0AEF,
  29216. ninegurmukhi: 0x0A6F,
  29217. ninehackarabic: 0x0669,
  29218. ninehangzhou: 0x3029,
  29219. nineideographicparen: 0x3228,
  29220. nineinferior: 0x2089,
  29221. ninemonospace: 0xFF19,
  29222. nineoldstyle: 0xF739,
  29223. nineparen: 0x247C,
  29224. nineperiod: 0x2490,
  29225. ninepersian: 0x06F9,
  29226. nineroman: 0x2178,
  29227. ninesuperior: 0x2079,
  29228. nineteencircle: 0x2472,
  29229. nineteenparen: 0x2486,
  29230. nineteenperiod: 0x249A,
  29231. ninethai: 0x0E59,
  29232. nj: 0x01CC,
  29233. njecyrillic: 0x045A,
  29234. nkatakana: 0x30F3,
  29235. nkatakanahalfwidth: 0xFF9D,
  29236. nlegrightlong: 0x019E,
  29237. nlinebelow: 0x1E49,
  29238. nmonospace: 0xFF4E,
  29239. nmsquare: 0x339A,
  29240. nnabengali: 0x09A3,
  29241. nnadeva: 0x0923,
  29242. nnagujarati: 0x0AA3,
  29243. nnagurmukhi: 0x0A23,
  29244. nnnadeva: 0x0929,
  29245. nohiragana: 0x306E,
  29246. nokatakana: 0x30CE,
  29247. nokatakanahalfwidth: 0xFF89,
  29248. nonbreakingspace: 0x00A0,
  29249. nonenthai: 0x0E13,
  29250. nonuthai: 0x0E19,
  29251. noonarabic: 0x0646,
  29252. noonfinalarabic: 0xFEE6,
  29253. noonghunnaarabic: 0x06BA,
  29254. noonghunnafinalarabic: 0xFB9F,
  29255. nooninitialarabic: 0xFEE7,
  29256. noonjeeminitialarabic: 0xFCD2,
  29257. noonjeemisolatedarabic: 0xFC4B,
  29258. noonmedialarabic: 0xFEE8,
  29259. noonmeeminitialarabic: 0xFCD5,
  29260. noonmeemisolatedarabic: 0xFC4E,
  29261. noonnoonfinalarabic: 0xFC8D,
  29262. notcontains: 0x220C,
  29263. notelement: 0x2209,
  29264. notelementof: 0x2209,
  29265. notequal: 0x2260,
  29266. notgreater: 0x226F,
  29267. notgreaternorequal: 0x2271,
  29268. notgreaternorless: 0x2279,
  29269. notidentical: 0x2262,
  29270. notless: 0x226E,
  29271. notlessnorequal: 0x2270,
  29272. notparallel: 0x2226,
  29273. notprecedes: 0x2280,
  29274. notsubset: 0x2284,
  29275. notsucceeds: 0x2281,
  29276. notsuperset: 0x2285,
  29277. nowarmenian: 0x0576,
  29278. nparen: 0x24A9,
  29279. nssquare: 0x33B1,
  29280. nsuperior: 0x207F,
  29281. ntilde: 0x00F1,
  29282. nu: 0x03BD,
  29283. nuhiragana: 0x306C,
  29284. nukatakana: 0x30CC,
  29285. nukatakanahalfwidth: 0xFF87,
  29286. nuktabengali: 0x09BC,
  29287. nuktadeva: 0x093C,
  29288. nuktagujarati: 0x0ABC,
  29289. nuktagurmukhi: 0x0A3C,
  29290. numbersign: 0x0023,
  29291. numbersignmonospace: 0xFF03,
  29292. numbersignsmall: 0xFE5F,
  29293. numeralsigngreek: 0x0374,
  29294. numeralsignlowergreek: 0x0375,
  29295. numero: 0x2116,
  29296. nun: 0x05E0,
  29297. nundagesh: 0xFB40,
  29298. nundageshhebrew: 0xFB40,
  29299. nunhebrew: 0x05E0,
  29300. nvsquare: 0x33B5,
  29301. nwsquare: 0x33BB,
  29302. nyabengali: 0x099E,
  29303. nyadeva: 0x091E,
  29304. nyagujarati: 0x0A9E,
  29305. nyagurmukhi: 0x0A1E,
  29306. o: 0x006F,
  29307. oacute: 0x00F3,
  29308. oangthai: 0x0E2D,
  29309. obarred: 0x0275,
  29310. obarredcyrillic: 0x04E9,
  29311. obarreddieresiscyrillic: 0x04EB,
  29312. obengali: 0x0993,
  29313. obopomofo: 0x311B,
  29314. obreve: 0x014F,
  29315. ocandradeva: 0x0911,
  29316. ocandragujarati: 0x0A91,
  29317. ocandravowelsigndeva: 0x0949,
  29318. ocandravowelsigngujarati: 0x0AC9,
  29319. ocaron: 0x01D2,
  29320. ocircle: 0x24DE,
  29321. ocircumflex: 0x00F4,
  29322. ocircumflexacute: 0x1ED1,
  29323. ocircumflexdotbelow: 0x1ED9,
  29324. ocircumflexgrave: 0x1ED3,
  29325. ocircumflexhookabove: 0x1ED5,
  29326. ocircumflextilde: 0x1ED7,
  29327. ocyrillic: 0x043E,
  29328. odblacute: 0x0151,
  29329. odblgrave: 0x020D,
  29330. odeva: 0x0913,
  29331. odieresis: 0x00F6,
  29332. odieresiscyrillic: 0x04E7,
  29333. odotbelow: 0x1ECD,
  29334. oe: 0x0153,
  29335. oekorean: 0x315A,
  29336. ogonek: 0x02DB,
  29337. ogonekcmb: 0x0328,
  29338. ograve: 0x00F2,
  29339. ogujarati: 0x0A93,
  29340. oharmenian: 0x0585,
  29341. ohiragana: 0x304A,
  29342. ohookabove: 0x1ECF,
  29343. ohorn: 0x01A1,
  29344. ohornacute: 0x1EDB,
  29345. ohorndotbelow: 0x1EE3,
  29346. ohorngrave: 0x1EDD,
  29347. ohornhookabove: 0x1EDF,
  29348. ohorntilde: 0x1EE1,
  29349. ohungarumlaut: 0x0151,
  29350. oi: 0x01A3,
  29351. oinvertedbreve: 0x020F,
  29352. okatakana: 0x30AA,
  29353. okatakanahalfwidth: 0xFF75,
  29354. okorean: 0x3157,
  29355. olehebrew: 0x05AB,
  29356. omacron: 0x014D,
  29357. omacronacute: 0x1E53,
  29358. omacrongrave: 0x1E51,
  29359. omdeva: 0x0950,
  29360. omega: 0x03C9,
  29361. omega1: 0x03D6,
  29362. omegacyrillic: 0x0461,
  29363. omegalatinclosed: 0x0277,
  29364. omegaroundcyrillic: 0x047B,
  29365. omegatitlocyrillic: 0x047D,
  29366. omegatonos: 0x03CE,
  29367. omgujarati: 0x0AD0,
  29368. omicron: 0x03BF,
  29369. omicrontonos: 0x03CC,
  29370. omonospace: 0xFF4F,
  29371. one: 0x0031,
  29372. onearabic: 0x0661,
  29373. onebengali: 0x09E7,
  29374. onecircle: 0x2460,
  29375. onecircleinversesansserif: 0x278A,
  29376. onedeva: 0x0967,
  29377. onedotenleader: 0x2024,
  29378. oneeighth: 0x215B,
  29379. onefitted: 0xF6DC,
  29380. onegujarati: 0x0AE7,
  29381. onegurmukhi: 0x0A67,
  29382. onehackarabic: 0x0661,
  29383. onehalf: 0x00BD,
  29384. onehangzhou: 0x3021,
  29385. oneideographicparen: 0x3220,
  29386. oneinferior: 0x2081,
  29387. onemonospace: 0xFF11,
  29388. onenumeratorbengali: 0x09F4,
  29389. oneoldstyle: 0xF731,
  29390. oneparen: 0x2474,
  29391. oneperiod: 0x2488,
  29392. onepersian: 0x06F1,
  29393. onequarter: 0x00BC,
  29394. oneroman: 0x2170,
  29395. onesuperior: 0x00B9,
  29396. onethai: 0x0E51,
  29397. onethird: 0x2153,
  29398. oogonek: 0x01EB,
  29399. oogonekmacron: 0x01ED,
  29400. oogurmukhi: 0x0A13,
  29401. oomatragurmukhi: 0x0A4B,
  29402. oopen: 0x0254,
  29403. oparen: 0x24AA,
  29404. openbullet: 0x25E6,
  29405. option: 0x2325,
  29406. ordfeminine: 0x00AA,
  29407. ordmasculine: 0x00BA,
  29408. orthogonal: 0x221F,
  29409. oshortdeva: 0x0912,
  29410. oshortvowelsigndeva: 0x094A,
  29411. oslash: 0x00F8,
  29412. oslashacute: 0x01FF,
  29413. osmallhiragana: 0x3049,
  29414. osmallkatakana: 0x30A9,
  29415. osmallkatakanahalfwidth: 0xFF6B,
  29416. ostrokeacute: 0x01FF,
  29417. osuperior: 0xF6F0,
  29418. otcyrillic: 0x047F,
  29419. otilde: 0x00F5,
  29420. otildeacute: 0x1E4D,
  29421. otildedieresis: 0x1E4F,
  29422. oubopomofo: 0x3121,
  29423. overline: 0x203E,
  29424. overlinecenterline: 0xFE4A,
  29425. overlinecmb: 0x0305,
  29426. overlinedashed: 0xFE49,
  29427. overlinedblwavy: 0xFE4C,
  29428. overlinewavy: 0xFE4B,
  29429. overscore: 0x00AF,
  29430. ovowelsignbengali: 0x09CB,
  29431. ovowelsigndeva: 0x094B,
  29432. ovowelsigngujarati: 0x0ACB,
  29433. p: 0x0070,
  29434. paampssquare: 0x3380,
  29435. paasentosquare: 0x332B,
  29436. pabengali: 0x09AA,
  29437. pacute: 0x1E55,
  29438. padeva: 0x092A,
  29439. pagedown: 0x21DF,
  29440. pageup: 0x21DE,
  29441. pagujarati: 0x0AAA,
  29442. pagurmukhi: 0x0A2A,
  29443. pahiragana: 0x3071,
  29444. paiyannoithai: 0x0E2F,
  29445. pakatakana: 0x30D1,
  29446. palatalizationcyrilliccmb: 0x0484,
  29447. palochkacyrillic: 0x04C0,
  29448. pansioskorean: 0x317F,
  29449. paragraph: 0x00B6,
  29450. parallel: 0x2225,
  29451. parenleft: 0x0028,
  29452. parenleftaltonearabic: 0xFD3E,
  29453. parenleftbt: 0xF8ED,
  29454. parenleftex: 0xF8EC,
  29455. parenleftinferior: 0x208D,
  29456. parenleftmonospace: 0xFF08,
  29457. parenleftsmall: 0xFE59,
  29458. parenleftsuperior: 0x207D,
  29459. parenlefttp: 0xF8EB,
  29460. parenleftvertical: 0xFE35,
  29461. parenright: 0x0029,
  29462. parenrightaltonearabic: 0xFD3F,
  29463. parenrightbt: 0xF8F8,
  29464. parenrightex: 0xF8F7,
  29465. parenrightinferior: 0x208E,
  29466. parenrightmonospace: 0xFF09,
  29467. parenrightsmall: 0xFE5A,
  29468. parenrightsuperior: 0x207E,
  29469. parenrighttp: 0xF8F6,
  29470. parenrightvertical: 0xFE36,
  29471. partialdiff: 0x2202,
  29472. paseqhebrew: 0x05C0,
  29473. pashtahebrew: 0x0599,
  29474. pasquare: 0x33A9,
  29475. patah: 0x05B7,
  29476. patah11: 0x05B7,
  29477. patah1d: 0x05B7,
  29478. patah2a: 0x05B7,
  29479. patahhebrew: 0x05B7,
  29480. patahnarrowhebrew: 0x05B7,
  29481. patahquarterhebrew: 0x05B7,
  29482. patahwidehebrew: 0x05B7,
  29483. pazerhebrew: 0x05A1,
  29484. pbopomofo: 0x3106,
  29485. pcircle: 0x24DF,
  29486. pdotaccent: 0x1E57,
  29487. pe: 0x05E4,
  29488. pecyrillic: 0x043F,
  29489. pedagesh: 0xFB44,
  29490. pedageshhebrew: 0xFB44,
  29491. peezisquare: 0x333B,
  29492. pefinaldageshhebrew: 0xFB43,
  29493. peharabic: 0x067E,
  29494. peharmenian: 0x057A,
  29495. pehebrew: 0x05E4,
  29496. pehfinalarabic: 0xFB57,
  29497. pehinitialarabic: 0xFB58,
  29498. pehiragana: 0x307A,
  29499. pehmedialarabic: 0xFB59,
  29500. pekatakana: 0x30DA,
  29501. pemiddlehookcyrillic: 0x04A7,
  29502. perafehebrew: 0xFB4E,
  29503. percent: 0x0025,
  29504. percentarabic: 0x066A,
  29505. percentmonospace: 0xFF05,
  29506. percentsmall: 0xFE6A,
  29507. period: 0x002E,
  29508. periodarmenian: 0x0589,
  29509. periodcentered: 0x00B7,
  29510. periodhalfwidth: 0xFF61,
  29511. periodinferior: 0xF6E7,
  29512. periodmonospace: 0xFF0E,
  29513. periodsmall: 0xFE52,
  29514. periodsuperior: 0xF6E8,
  29515. perispomenigreekcmb: 0x0342,
  29516. perpendicular: 0x22A5,
  29517. perthousand: 0x2030,
  29518. peseta: 0x20A7,
  29519. pfsquare: 0x338A,
  29520. phabengali: 0x09AB,
  29521. phadeva: 0x092B,
  29522. phagujarati: 0x0AAB,
  29523. phagurmukhi: 0x0A2B,
  29524. phi: 0x03C6,
  29525. phi1: 0x03D5,
  29526. phieuphacirclekorean: 0x327A,
  29527. phieuphaparenkorean: 0x321A,
  29528. phieuphcirclekorean: 0x326C,
  29529. phieuphkorean: 0x314D,
  29530. phieuphparenkorean: 0x320C,
  29531. philatin: 0x0278,
  29532. phinthuthai: 0x0E3A,
  29533. phisymbolgreek: 0x03D5,
  29534. phook: 0x01A5,
  29535. phophanthai: 0x0E1E,
  29536. phophungthai: 0x0E1C,
  29537. phosamphaothai: 0x0E20,
  29538. pi: 0x03C0,
  29539. pieupacirclekorean: 0x3273,
  29540. pieupaparenkorean: 0x3213,
  29541. pieupcieuckorean: 0x3176,
  29542. pieupcirclekorean: 0x3265,
  29543. pieupkiyeokkorean: 0x3172,
  29544. pieupkorean: 0x3142,
  29545. pieupparenkorean: 0x3205,
  29546. pieupsioskiyeokkorean: 0x3174,
  29547. pieupsioskorean: 0x3144,
  29548. pieupsiostikeutkorean: 0x3175,
  29549. pieupthieuthkorean: 0x3177,
  29550. pieuptikeutkorean: 0x3173,
  29551. pihiragana: 0x3074,
  29552. pikatakana: 0x30D4,
  29553. pisymbolgreek: 0x03D6,
  29554. piwrarmenian: 0x0583,
  29555. plus: 0x002B,
  29556. plusbelowcmb: 0x031F,
  29557. pluscircle: 0x2295,
  29558. plusminus: 0x00B1,
  29559. plusmod: 0x02D6,
  29560. plusmonospace: 0xFF0B,
  29561. plussmall: 0xFE62,
  29562. plussuperior: 0x207A,
  29563. pmonospace: 0xFF50,
  29564. pmsquare: 0x33D8,
  29565. pohiragana: 0x307D,
  29566. pointingindexdownwhite: 0x261F,
  29567. pointingindexleftwhite: 0x261C,
  29568. pointingindexrightwhite: 0x261E,
  29569. pointingindexupwhite: 0x261D,
  29570. pokatakana: 0x30DD,
  29571. poplathai: 0x0E1B,
  29572. postalmark: 0x3012,
  29573. postalmarkface: 0x3020,
  29574. pparen: 0x24AB,
  29575. precedes: 0x227A,
  29576. prescription: 0x211E,
  29577. primemod: 0x02B9,
  29578. primereversed: 0x2035,
  29579. product: 0x220F,
  29580. projective: 0x2305,
  29581. prolongedkana: 0x30FC,
  29582. propellor: 0x2318,
  29583. propersubset: 0x2282,
  29584. propersuperset: 0x2283,
  29585. proportion: 0x2237,
  29586. proportional: 0x221D,
  29587. psi: 0x03C8,
  29588. psicyrillic: 0x0471,
  29589. psilipneumatacyrilliccmb: 0x0486,
  29590. pssquare: 0x33B0,
  29591. puhiragana: 0x3077,
  29592. pukatakana: 0x30D7,
  29593. pvsquare: 0x33B4,
  29594. pwsquare: 0x33BA,
  29595. q: 0x0071,
  29596. qadeva: 0x0958,
  29597. qadmahebrew: 0x05A8,
  29598. qafarabic: 0x0642,
  29599. qaffinalarabic: 0xFED6,
  29600. qafinitialarabic: 0xFED7,
  29601. qafmedialarabic: 0xFED8,
  29602. qamats: 0x05B8,
  29603. qamats10: 0x05B8,
  29604. qamats1a: 0x05B8,
  29605. qamats1c: 0x05B8,
  29606. qamats27: 0x05B8,
  29607. qamats29: 0x05B8,
  29608. qamats33: 0x05B8,
  29609. qamatsde: 0x05B8,
  29610. qamatshebrew: 0x05B8,
  29611. qamatsnarrowhebrew: 0x05B8,
  29612. qamatsqatanhebrew: 0x05B8,
  29613. qamatsqatannarrowhebrew: 0x05B8,
  29614. qamatsqatanquarterhebrew: 0x05B8,
  29615. qamatsqatanwidehebrew: 0x05B8,
  29616. qamatsquarterhebrew: 0x05B8,
  29617. qamatswidehebrew: 0x05B8,
  29618. qarneyparahebrew: 0x059F,
  29619. qbopomofo: 0x3111,
  29620. qcircle: 0x24E0,
  29621. qhook: 0x02A0,
  29622. qmonospace: 0xFF51,
  29623. qof: 0x05E7,
  29624. qofdagesh: 0xFB47,
  29625. qofdageshhebrew: 0xFB47,
  29626. qofhebrew: 0x05E7,
  29627. qparen: 0x24AC,
  29628. quarternote: 0x2669,
  29629. qubuts: 0x05BB,
  29630. qubuts18: 0x05BB,
  29631. qubuts25: 0x05BB,
  29632. qubuts31: 0x05BB,
  29633. qubutshebrew: 0x05BB,
  29634. qubutsnarrowhebrew: 0x05BB,
  29635. qubutsquarterhebrew: 0x05BB,
  29636. qubutswidehebrew: 0x05BB,
  29637. question: 0x003F,
  29638. questionarabic: 0x061F,
  29639. questionarmenian: 0x055E,
  29640. questiondown: 0x00BF,
  29641. questiondownsmall: 0xF7BF,
  29642. questiongreek: 0x037E,
  29643. questionmonospace: 0xFF1F,
  29644. questionsmall: 0xF73F,
  29645. quotedbl: 0x0022,
  29646. quotedblbase: 0x201E,
  29647. quotedblleft: 0x201C,
  29648. quotedblmonospace: 0xFF02,
  29649. quotedblprime: 0x301E,
  29650. quotedblprimereversed: 0x301D,
  29651. quotedblright: 0x201D,
  29652. quoteleft: 0x2018,
  29653. quoteleftreversed: 0x201B,
  29654. quotereversed: 0x201B,
  29655. quoteright: 0x2019,
  29656. quoterightn: 0x0149,
  29657. quotesinglbase: 0x201A,
  29658. quotesingle: 0x0027,
  29659. quotesinglemonospace: 0xFF07,
  29660. r: 0x0072,
  29661. raarmenian: 0x057C,
  29662. rabengali: 0x09B0,
  29663. racute: 0x0155,
  29664. radeva: 0x0930,
  29665. radical: 0x221A,
  29666. radicalex: 0xF8E5,
  29667. radoverssquare: 0x33AE,
  29668. radoverssquaredsquare: 0x33AF,
  29669. radsquare: 0x33AD,
  29670. rafe: 0x05BF,
  29671. rafehebrew: 0x05BF,
  29672. ragujarati: 0x0AB0,
  29673. ragurmukhi: 0x0A30,
  29674. rahiragana: 0x3089,
  29675. rakatakana: 0x30E9,
  29676. rakatakanahalfwidth: 0xFF97,
  29677. ralowerdiagonalbengali: 0x09F1,
  29678. ramiddlediagonalbengali: 0x09F0,
  29679. ramshorn: 0x0264,
  29680. ratio: 0x2236,
  29681. rbopomofo: 0x3116,
  29682. rcaron: 0x0159,
  29683. rcedilla: 0x0157,
  29684. rcircle: 0x24E1,
  29685. rcommaaccent: 0x0157,
  29686. rdblgrave: 0x0211,
  29687. rdotaccent: 0x1E59,
  29688. rdotbelow: 0x1E5B,
  29689. rdotbelowmacron: 0x1E5D,
  29690. referencemark: 0x203B,
  29691. reflexsubset: 0x2286,
  29692. reflexsuperset: 0x2287,
  29693. registered: 0x00AE,
  29694. registersans: 0xF8E8,
  29695. registerserif: 0xF6DA,
  29696. reharabic: 0x0631,
  29697. reharmenian: 0x0580,
  29698. rehfinalarabic: 0xFEAE,
  29699. rehiragana: 0x308C,
  29700. rekatakana: 0x30EC,
  29701. rekatakanahalfwidth: 0xFF9A,
  29702. resh: 0x05E8,
  29703. reshdageshhebrew: 0xFB48,
  29704. reshhebrew: 0x05E8,
  29705. reversedtilde: 0x223D,
  29706. reviahebrew: 0x0597,
  29707. reviamugrashhebrew: 0x0597,
  29708. revlogicalnot: 0x2310,
  29709. rfishhook: 0x027E,
  29710. rfishhookreversed: 0x027F,
  29711. rhabengali: 0x09DD,
  29712. rhadeva: 0x095D,
  29713. rho: 0x03C1,
  29714. rhook: 0x027D,
  29715. rhookturned: 0x027B,
  29716. rhookturnedsuperior: 0x02B5,
  29717. rhosymbolgreek: 0x03F1,
  29718. rhotichookmod: 0x02DE,
  29719. rieulacirclekorean: 0x3271,
  29720. rieulaparenkorean: 0x3211,
  29721. rieulcirclekorean: 0x3263,
  29722. rieulhieuhkorean: 0x3140,
  29723. rieulkiyeokkorean: 0x313A,
  29724. rieulkiyeoksioskorean: 0x3169,
  29725. rieulkorean: 0x3139,
  29726. rieulmieumkorean: 0x313B,
  29727. rieulpansioskorean: 0x316C,
  29728. rieulparenkorean: 0x3203,
  29729. rieulphieuphkorean: 0x313F,
  29730. rieulpieupkorean: 0x313C,
  29731. rieulpieupsioskorean: 0x316B,
  29732. rieulsioskorean: 0x313D,
  29733. rieulthieuthkorean: 0x313E,
  29734. rieultikeutkorean: 0x316A,
  29735. rieulyeorinhieuhkorean: 0x316D,
  29736. rightangle: 0x221F,
  29737. righttackbelowcmb: 0x0319,
  29738. righttriangle: 0x22BF,
  29739. rihiragana: 0x308A,
  29740. rikatakana: 0x30EA,
  29741. rikatakanahalfwidth: 0xFF98,
  29742. ring: 0x02DA,
  29743. ringbelowcmb: 0x0325,
  29744. ringcmb: 0x030A,
  29745. ringhalfleft: 0x02BF,
  29746. ringhalfleftarmenian: 0x0559,
  29747. ringhalfleftbelowcmb: 0x031C,
  29748. ringhalfleftcentered: 0x02D3,
  29749. ringhalfright: 0x02BE,
  29750. ringhalfrightbelowcmb: 0x0339,
  29751. ringhalfrightcentered: 0x02D2,
  29752. rinvertedbreve: 0x0213,
  29753. rittorusquare: 0x3351,
  29754. rlinebelow: 0x1E5F,
  29755. rlongleg: 0x027C,
  29756. rlonglegturned: 0x027A,
  29757. rmonospace: 0xFF52,
  29758. rohiragana: 0x308D,
  29759. rokatakana: 0x30ED,
  29760. rokatakanahalfwidth: 0xFF9B,
  29761. roruathai: 0x0E23,
  29762. rparen: 0x24AD,
  29763. rrabengali: 0x09DC,
  29764. rradeva: 0x0931,
  29765. rragurmukhi: 0x0A5C,
  29766. rreharabic: 0x0691,
  29767. rrehfinalarabic: 0xFB8D,
  29768. rrvocalicbengali: 0x09E0,
  29769. rrvocalicdeva: 0x0960,
  29770. rrvocalicgujarati: 0x0AE0,
  29771. rrvocalicvowelsignbengali: 0x09C4,
  29772. rrvocalicvowelsigndeva: 0x0944,
  29773. rrvocalicvowelsigngujarati: 0x0AC4,
  29774. rsuperior: 0xF6F1,
  29775. rtblock: 0x2590,
  29776. rturned: 0x0279,
  29777. rturnedsuperior: 0x02B4,
  29778. ruhiragana: 0x308B,
  29779. rukatakana: 0x30EB,
  29780. rukatakanahalfwidth: 0xFF99,
  29781. rupeemarkbengali: 0x09F2,
  29782. rupeesignbengali: 0x09F3,
  29783. rupiah: 0xF6DD,
  29784. ruthai: 0x0E24,
  29785. rvocalicbengali: 0x098B,
  29786. rvocalicdeva: 0x090B,
  29787. rvocalicgujarati: 0x0A8B,
  29788. rvocalicvowelsignbengali: 0x09C3,
  29789. rvocalicvowelsigndeva: 0x0943,
  29790. rvocalicvowelsigngujarati: 0x0AC3,
  29791. s: 0x0073,
  29792. sabengali: 0x09B8,
  29793. sacute: 0x015B,
  29794. sacutedotaccent: 0x1E65,
  29795. sadarabic: 0x0635,
  29796. sadeva: 0x0938,
  29797. sadfinalarabic: 0xFEBA,
  29798. sadinitialarabic: 0xFEBB,
  29799. sadmedialarabic: 0xFEBC,
  29800. sagujarati: 0x0AB8,
  29801. sagurmukhi: 0x0A38,
  29802. sahiragana: 0x3055,
  29803. sakatakana: 0x30B5,
  29804. sakatakanahalfwidth: 0xFF7B,
  29805. sallallahoualayhewasallamarabic: 0xFDFA,
  29806. samekh: 0x05E1,
  29807. samekhdagesh: 0xFB41,
  29808. samekhdageshhebrew: 0xFB41,
  29809. samekhhebrew: 0x05E1,
  29810. saraaathai: 0x0E32,
  29811. saraaethai: 0x0E41,
  29812. saraaimaimalaithai: 0x0E44,
  29813. saraaimaimuanthai: 0x0E43,
  29814. saraamthai: 0x0E33,
  29815. saraathai: 0x0E30,
  29816. saraethai: 0x0E40,
  29817. saraiileftthai: 0xF886,
  29818. saraiithai: 0x0E35,
  29819. saraileftthai: 0xF885,
  29820. saraithai: 0x0E34,
  29821. saraothai: 0x0E42,
  29822. saraueeleftthai: 0xF888,
  29823. saraueethai: 0x0E37,
  29824. saraueleftthai: 0xF887,
  29825. sarauethai: 0x0E36,
  29826. sarauthai: 0x0E38,
  29827. sarauuthai: 0x0E39,
  29828. sbopomofo: 0x3119,
  29829. scaron: 0x0161,
  29830. scarondotaccent: 0x1E67,
  29831. scedilla: 0x015F,
  29832. schwa: 0x0259,
  29833. schwacyrillic: 0x04D9,
  29834. schwadieresiscyrillic: 0x04DB,
  29835. schwahook: 0x025A,
  29836. scircle: 0x24E2,
  29837. scircumflex: 0x015D,
  29838. scommaaccent: 0x0219,
  29839. sdotaccent: 0x1E61,
  29840. sdotbelow: 0x1E63,
  29841. sdotbelowdotaccent: 0x1E69,
  29842. seagullbelowcmb: 0x033C,
  29843. second: 0x2033,
  29844. secondtonechinese: 0x02CA,
  29845. section: 0x00A7,
  29846. seenarabic: 0x0633,
  29847. seenfinalarabic: 0xFEB2,
  29848. seeninitialarabic: 0xFEB3,
  29849. seenmedialarabic: 0xFEB4,
  29850. segol: 0x05B6,
  29851. segol13: 0x05B6,
  29852. segol1f: 0x05B6,
  29853. segol2c: 0x05B6,
  29854. segolhebrew: 0x05B6,
  29855. segolnarrowhebrew: 0x05B6,
  29856. segolquarterhebrew: 0x05B6,
  29857. segoltahebrew: 0x0592,
  29858. segolwidehebrew: 0x05B6,
  29859. seharmenian: 0x057D,
  29860. sehiragana: 0x305B,
  29861. sekatakana: 0x30BB,
  29862. sekatakanahalfwidth: 0xFF7E,
  29863. semicolon: 0x003B,
  29864. semicolonarabic: 0x061B,
  29865. semicolonmonospace: 0xFF1B,
  29866. semicolonsmall: 0xFE54,
  29867. semivoicedmarkkana: 0x309C,
  29868. semivoicedmarkkanahalfwidth: 0xFF9F,
  29869. sentisquare: 0x3322,
  29870. sentosquare: 0x3323,
  29871. seven: 0x0037,
  29872. sevenarabic: 0x0667,
  29873. sevenbengali: 0x09ED,
  29874. sevencircle: 0x2466,
  29875. sevencircleinversesansserif: 0x2790,
  29876. sevendeva: 0x096D,
  29877. seveneighths: 0x215E,
  29878. sevengujarati: 0x0AED,
  29879. sevengurmukhi: 0x0A6D,
  29880. sevenhackarabic: 0x0667,
  29881. sevenhangzhou: 0x3027,
  29882. sevenideographicparen: 0x3226,
  29883. seveninferior: 0x2087,
  29884. sevenmonospace: 0xFF17,
  29885. sevenoldstyle: 0xF737,
  29886. sevenparen: 0x247A,
  29887. sevenperiod: 0x248E,
  29888. sevenpersian: 0x06F7,
  29889. sevenroman: 0x2176,
  29890. sevensuperior: 0x2077,
  29891. seventeencircle: 0x2470,
  29892. seventeenparen: 0x2484,
  29893. seventeenperiod: 0x2498,
  29894. seventhai: 0x0E57,
  29895. sfthyphen: 0x00AD,
  29896. shaarmenian: 0x0577,
  29897. shabengali: 0x09B6,
  29898. shacyrillic: 0x0448,
  29899. shaddaarabic: 0x0651,
  29900. shaddadammaarabic: 0xFC61,
  29901. shaddadammatanarabic: 0xFC5E,
  29902. shaddafathaarabic: 0xFC60,
  29903. shaddakasraarabic: 0xFC62,
  29904. shaddakasratanarabic: 0xFC5F,
  29905. shade: 0x2592,
  29906. shadedark: 0x2593,
  29907. shadelight: 0x2591,
  29908. shademedium: 0x2592,
  29909. shadeva: 0x0936,
  29910. shagujarati: 0x0AB6,
  29911. shagurmukhi: 0x0A36,
  29912. shalshelethebrew: 0x0593,
  29913. shbopomofo: 0x3115,
  29914. shchacyrillic: 0x0449,
  29915. sheenarabic: 0x0634,
  29916. sheenfinalarabic: 0xFEB6,
  29917. sheeninitialarabic: 0xFEB7,
  29918. sheenmedialarabic: 0xFEB8,
  29919. sheicoptic: 0x03E3,
  29920. sheqel: 0x20AA,
  29921. sheqelhebrew: 0x20AA,
  29922. sheva: 0x05B0,
  29923. sheva115: 0x05B0,
  29924. sheva15: 0x05B0,
  29925. sheva22: 0x05B0,
  29926. sheva2e: 0x05B0,
  29927. shevahebrew: 0x05B0,
  29928. shevanarrowhebrew: 0x05B0,
  29929. shevaquarterhebrew: 0x05B0,
  29930. shevawidehebrew: 0x05B0,
  29931. shhacyrillic: 0x04BB,
  29932. shimacoptic: 0x03ED,
  29933. shin: 0x05E9,
  29934. shindagesh: 0xFB49,
  29935. shindageshhebrew: 0xFB49,
  29936. shindageshshindot: 0xFB2C,
  29937. shindageshshindothebrew: 0xFB2C,
  29938. shindageshsindot: 0xFB2D,
  29939. shindageshsindothebrew: 0xFB2D,
  29940. shindothebrew: 0x05C1,
  29941. shinhebrew: 0x05E9,
  29942. shinshindot: 0xFB2A,
  29943. shinshindothebrew: 0xFB2A,
  29944. shinsindot: 0xFB2B,
  29945. shinsindothebrew: 0xFB2B,
  29946. shook: 0x0282,
  29947. sigma: 0x03C3,
  29948. sigma1: 0x03C2,
  29949. sigmafinal: 0x03C2,
  29950. sigmalunatesymbolgreek: 0x03F2,
  29951. sihiragana: 0x3057,
  29952. sikatakana: 0x30B7,
  29953. sikatakanahalfwidth: 0xFF7C,
  29954. siluqhebrew: 0x05BD,
  29955. siluqlefthebrew: 0x05BD,
  29956. similar: 0x223C,
  29957. sindothebrew: 0x05C2,
  29958. siosacirclekorean: 0x3274,
  29959. siosaparenkorean: 0x3214,
  29960. sioscieuckorean: 0x317E,
  29961. sioscirclekorean: 0x3266,
  29962. sioskiyeokkorean: 0x317A,
  29963. sioskorean: 0x3145,
  29964. siosnieunkorean: 0x317B,
  29965. siosparenkorean: 0x3206,
  29966. siospieupkorean: 0x317D,
  29967. siostikeutkorean: 0x317C,
  29968. six: 0x0036,
  29969. sixarabic: 0x0666,
  29970. sixbengali: 0x09EC,
  29971. sixcircle: 0x2465,
  29972. sixcircleinversesansserif: 0x278F,
  29973. sixdeva: 0x096C,
  29974. sixgujarati: 0x0AEC,
  29975. sixgurmukhi: 0x0A6C,
  29976. sixhackarabic: 0x0666,
  29977. sixhangzhou: 0x3026,
  29978. sixideographicparen: 0x3225,
  29979. sixinferior: 0x2086,
  29980. sixmonospace: 0xFF16,
  29981. sixoldstyle: 0xF736,
  29982. sixparen: 0x2479,
  29983. sixperiod: 0x248D,
  29984. sixpersian: 0x06F6,
  29985. sixroman: 0x2175,
  29986. sixsuperior: 0x2076,
  29987. sixteencircle: 0x246F,
  29988. sixteencurrencydenominatorbengali: 0x09F9,
  29989. sixteenparen: 0x2483,
  29990. sixteenperiod: 0x2497,
  29991. sixthai: 0x0E56,
  29992. slash: 0x002F,
  29993. slashmonospace: 0xFF0F,
  29994. slong: 0x017F,
  29995. slongdotaccent: 0x1E9B,
  29996. smileface: 0x263A,
  29997. smonospace: 0xFF53,
  29998. sofpasuqhebrew: 0x05C3,
  29999. softhyphen: 0x00AD,
  30000. softsigncyrillic: 0x044C,
  30001. sohiragana: 0x305D,
  30002. sokatakana: 0x30BD,
  30003. sokatakanahalfwidth: 0xFF7F,
  30004. soliduslongoverlaycmb: 0x0338,
  30005. solidusshortoverlaycmb: 0x0337,
  30006. sorusithai: 0x0E29,
  30007. sosalathai: 0x0E28,
  30008. sosothai: 0x0E0B,
  30009. sosuathai: 0x0E2A,
  30010. space: 0x0020,
  30011. spacehackarabic: 0x0020,
  30012. spade: 0x2660,
  30013. spadesuitblack: 0x2660,
  30014. spadesuitwhite: 0x2664,
  30015. sparen: 0x24AE,
  30016. squarebelowcmb: 0x033B,
  30017. squarecc: 0x33C4,
  30018. squarecm: 0x339D,
  30019. squarediagonalcrosshatchfill: 0x25A9,
  30020. squarehorizontalfill: 0x25A4,
  30021. squarekg: 0x338F,
  30022. squarekm: 0x339E,
  30023. squarekmcapital: 0x33CE,
  30024. squareln: 0x33D1,
  30025. squarelog: 0x33D2,
  30026. squaremg: 0x338E,
  30027. squaremil: 0x33D5,
  30028. squaremm: 0x339C,
  30029. squaremsquared: 0x33A1,
  30030. squareorthogonalcrosshatchfill: 0x25A6,
  30031. squareupperlefttolowerrightfill: 0x25A7,
  30032. squareupperrighttolowerleftfill: 0x25A8,
  30033. squareverticalfill: 0x25A5,
  30034. squarewhitewithsmallblack: 0x25A3,
  30035. srsquare: 0x33DB,
  30036. ssabengali: 0x09B7,
  30037. ssadeva: 0x0937,
  30038. ssagujarati: 0x0AB7,
  30039. ssangcieuckorean: 0x3149,
  30040. ssanghieuhkorean: 0x3185,
  30041. ssangieungkorean: 0x3180,
  30042. ssangkiyeokkorean: 0x3132,
  30043. ssangnieunkorean: 0x3165,
  30044. ssangpieupkorean: 0x3143,
  30045. ssangsioskorean: 0x3146,
  30046. ssangtikeutkorean: 0x3138,
  30047. ssuperior: 0xF6F2,
  30048. sterling: 0x00A3,
  30049. sterlingmonospace: 0xFFE1,
  30050. strokelongoverlaycmb: 0x0336,
  30051. strokeshortoverlaycmb: 0x0335,
  30052. subset: 0x2282,
  30053. subsetnotequal: 0x228A,
  30054. subsetorequal: 0x2286,
  30055. succeeds: 0x227B,
  30056. suchthat: 0x220B,
  30057. suhiragana: 0x3059,
  30058. sukatakana: 0x30B9,
  30059. sukatakanahalfwidth: 0xFF7D,
  30060. sukunarabic: 0x0652,
  30061. summation: 0x2211,
  30062. sun: 0x263C,
  30063. superset: 0x2283,
  30064. supersetnotequal: 0x228B,
  30065. supersetorequal: 0x2287,
  30066. svsquare: 0x33DC,
  30067. syouwaerasquare: 0x337C,
  30068. t: 0x0074,
  30069. tabengali: 0x09A4,
  30070. tackdown: 0x22A4,
  30071. tackleft: 0x22A3,
  30072. tadeva: 0x0924,
  30073. tagujarati: 0x0AA4,
  30074. tagurmukhi: 0x0A24,
  30075. taharabic: 0x0637,
  30076. tahfinalarabic: 0xFEC2,
  30077. tahinitialarabic: 0xFEC3,
  30078. tahiragana: 0x305F,
  30079. tahmedialarabic: 0xFEC4,
  30080. taisyouerasquare: 0x337D,
  30081. takatakana: 0x30BF,
  30082. takatakanahalfwidth: 0xFF80,
  30083. tatweelarabic: 0x0640,
  30084. tau: 0x03C4,
  30085. tav: 0x05EA,
  30086. tavdages: 0xFB4A,
  30087. tavdagesh: 0xFB4A,
  30088. tavdageshhebrew: 0xFB4A,
  30089. tavhebrew: 0x05EA,
  30090. tbar: 0x0167,
  30091. tbopomofo: 0x310A,
  30092. tcaron: 0x0165,
  30093. tccurl: 0x02A8,
  30094. tcedilla: 0x0163,
  30095. tcheharabic: 0x0686,
  30096. tchehfinalarabic: 0xFB7B,
  30097. tchehinitialarabic: 0xFB7C,
  30098. tchehmedialarabic: 0xFB7D,
  30099. tcircle: 0x24E3,
  30100. tcircumflexbelow: 0x1E71,
  30101. tcommaaccent: 0x0163,
  30102. tdieresis: 0x1E97,
  30103. tdotaccent: 0x1E6B,
  30104. tdotbelow: 0x1E6D,
  30105. tecyrillic: 0x0442,
  30106. tedescendercyrillic: 0x04AD,
  30107. teharabic: 0x062A,
  30108. tehfinalarabic: 0xFE96,
  30109. tehhahinitialarabic: 0xFCA2,
  30110. tehhahisolatedarabic: 0xFC0C,
  30111. tehinitialarabic: 0xFE97,
  30112. tehiragana: 0x3066,
  30113. tehjeeminitialarabic: 0xFCA1,
  30114. tehjeemisolatedarabic: 0xFC0B,
  30115. tehmarbutaarabic: 0x0629,
  30116. tehmarbutafinalarabic: 0xFE94,
  30117. tehmedialarabic: 0xFE98,
  30118. tehmeeminitialarabic: 0xFCA4,
  30119. tehmeemisolatedarabic: 0xFC0E,
  30120. tehnoonfinalarabic: 0xFC73,
  30121. tekatakana: 0x30C6,
  30122. tekatakanahalfwidth: 0xFF83,
  30123. telephone: 0x2121,
  30124. telephoneblack: 0x260E,
  30125. telishagedolahebrew: 0x05A0,
  30126. telishaqetanahebrew: 0x05A9,
  30127. tencircle: 0x2469,
  30128. tenideographicparen: 0x3229,
  30129. tenparen: 0x247D,
  30130. tenperiod: 0x2491,
  30131. tenroman: 0x2179,
  30132. tesh: 0x02A7,
  30133. tet: 0x05D8,
  30134. tetdagesh: 0xFB38,
  30135. tetdageshhebrew: 0xFB38,
  30136. tethebrew: 0x05D8,
  30137. tetsecyrillic: 0x04B5,
  30138. tevirhebrew: 0x059B,
  30139. tevirlefthebrew: 0x059B,
  30140. thabengali: 0x09A5,
  30141. thadeva: 0x0925,
  30142. thagujarati: 0x0AA5,
  30143. thagurmukhi: 0x0A25,
  30144. thalarabic: 0x0630,
  30145. thalfinalarabic: 0xFEAC,
  30146. thanthakhatlowleftthai: 0xF898,
  30147. thanthakhatlowrightthai: 0xF897,
  30148. thanthakhatthai: 0x0E4C,
  30149. thanthakhatupperleftthai: 0xF896,
  30150. theharabic: 0x062B,
  30151. thehfinalarabic: 0xFE9A,
  30152. thehinitialarabic: 0xFE9B,
  30153. thehmedialarabic: 0xFE9C,
  30154. thereexists: 0x2203,
  30155. therefore: 0x2234,
  30156. theta: 0x03B8,
  30157. theta1: 0x03D1,
  30158. thetasymbolgreek: 0x03D1,
  30159. thieuthacirclekorean: 0x3279,
  30160. thieuthaparenkorean: 0x3219,
  30161. thieuthcirclekorean: 0x326B,
  30162. thieuthkorean: 0x314C,
  30163. thieuthparenkorean: 0x320B,
  30164. thirteencircle: 0x246C,
  30165. thirteenparen: 0x2480,
  30166. thirteenperiod: 0x2494,
  30167. thonangmonthothai: 0x0E11,
  30168. thook: 0x01AD,
  30169. thophuthaothai: 0x0E12,
  30170. thorn: 0x00FE,
  30171. thothahanthai: 0x0E17,
  30172. thothanthai: 0x0E10,
  30173. thothongthai: 0x0E18,
  30174. thothungthai: 0x0E16,
  30175. thousandcyrillic: 0x0482,
  30176. thousandsseparatorarabic: 0x066C,
  30177. thousandsseparatorpersian: 0x066C,
  30178. three: 0x0033,
  30179. threearabic: 0x0663,
  30180. threebengali: 0x09E9,
  30181. threecircle: 0x2462,
  30182. threecircleinversesansserif: 0x278C,
  30183. threedeva: 0x0969,
  30184. threeeighths: 0x215C,
  30185. threegujarati: 0x0AE9,
  30186. threegurmukhi: 0x0A69,
  30187. threehackarabic: 0x0663,
  30188. threehangzhou: 0x3023,
  30189. threeideographicparen: 0x3222,
  30190. threeinferior: 0x2083,
  30191. threemonospace: 0xFF13,
  30192. threenumeratorbengali: 0x09F6,
  30193. threeoldstyle: 0xF733,
  30194. threeparen: 0x2476,
  30195. threeperiod: 0x248A,
  30196. threepersian: 0x06F3,
  30197. threequarters: 0x00BE,
  30198. threequartersemdash: 0xF6DE,
  30199. threeroman: 0x2172,
  30200. threesuperior: 0x00B3,
  30201. threethai: 0x0E53,
  30202. thzsquare: 0x3394,
  30203. tihiragana: 0x3061,
  30204. tikatakana: 0x30C1,
  30205. tikatakanahalfwidth: 0xFF81,
  30206. tikeutacirclekorean: 0x3270,
  30207. tikeutaparenkorean: 0x3210,
  30208. tikeutcirclekorean: 0x3262,
  30209. tikeutkorean: 0x3137,
  30210. tikeutparenkorean: 0x3202,
  30211. tilde: 0x02DC,
  30212. tildebelowcmb: 0x0330,
  30213. tildecmb: 0x0303,
  30214. tildecomb: 0x0303,
  30215. tildedoublecmb: 0x0360,
  30216. tildeoperator: 0x223C,
  30217. tildeoverlaycmb: 0x0334,
  30218. tildeverticalcmb: 0x033E,
  30219. timescircle: 0x2297,
  30220. tipehahebrew: 0x0596,
  30221. tipehalefthebrew: 0x0596,
  30222. tippigurmukhi: 0x0A70,
  30223. titlocyrilliccmb: 0x0483,
  30224. tiwnarmenian: 0x057F,
  30225. tlinebelow: 0x1E6F,
  30226. tmonospace: 0xFF54,
  30227. toarmenian: 0x0569,
  30228. tohiragana: 0x3068,
  30229. tokatakana: 0x30C8,
  30230. tokatakanahalfwidth: 0xFF84,
  30231. tonebarextrahighmod: 0x02E5,
  30232. tonebarextralowmod: 0x02E9,
  30233. tonebarhighmod: 0x02E6,
  30234. tonebarlowmod: 0x02E8,
  30235. tonebarmidmod: 0x02E7,
  30236. tonefive: 0x01BD,
  30237. tonesix: 0x0185,
  30238. tonetwo: 0x01A8,
  30239. tonos: 0x0384,
  30240. tonsquare: 0x3327,
  30241. topatakthai: 0x0E0F,
  30242. tortoiseshellbracketleft: 0x3014,
  30243. tortoiseshellbracketleftsmall: 0xFE5D,
  30244. tortoiseshellbracketleftvertical: 0xFE39,
  30245. tortoiseshellbracketright: 0x3015,
  30246. tortoiseshellbracketrightsmall: 0xFE5E,
  30247. tortoiseshellbracketrightvertical: 0xFE3A,
  30248. totaothai: 0x0E15,
  30249. tpalatalhook: 0x01AB,
  30250. tparen: 0x24AF,
  30251. trademark: 0x2122,
  30252. trademarksans: 0xF8EA,
  30253. trademarkserif: 0xF6DB,
  30254. tretroflexhook: 0x0288,
  30255. triagdn: 0x25BC,
  30256. triaglf: 0x25C4,
  30257. triagrt: 0x25BA,
  30258. triagup: 0x25B2,
  30259. ts: 0x02A6,
  30260. tsadi: 0x05E6,
  30261. tsadidagesh: 0xFB46,
  30262. tsadidageshhebrew: 0xFB46,
  30263. tsadihebrew: 0x05E6,
  30264. tsecyrillic: 0x0446,
  30265. tsere: 0x05B5,
  30266. tsere12: 0x05B5,
  30267. tsere1e: 0x05B5,
  30268. tsere2b: 0x05B5,
  30269. tserehebrew: 0x05B5,
  30270. tserenarrowhebrew: 0x05B5,
  30271. tserequarterhebrew: 0x05B5,
  30272. tserewidehebrew: 0x05B5,
  30273. tshecyrillic: 0x045B,
  30274. tsuperior: 0xF6F3,
  30275. ttabengali: 0x099F,
  30276. ttadeva: 0x091F,
  30277. ttagujarati: 0x0A9F,
  30278. ttagurmukhi: 0x0A1F,
  30279. tteharabic: 0x0679,
  30280. ttehfinalarabic: 0xFB67,
  30281. ttehinitialarabic: 0xFB68,
  30282. ttehmedialarabic: 0xFB69,
  30283. tthabengali: 0x09A0,
  30284. tthadeva: 0x0920,
  30285. tthagujarati: 0x0AA0,
  30286. tthagurmukhi: 0x0A20,
  30287. tturned: 0x0287,
  30288. tuhiragana: 0x3064,
  30289. tukatakana: 0x30C4,
  30290. tukatakanahalfwidth: 0xFF82,
  30291. tusmallhiragana: 0x3063,
  30292. tusmallkatakana: 0x30C3,
  30293. tusmallkatakanahalfwidth: 0xFF6F,
  30294. twelvecircle: 0x246B,
  30295. twelveparen: 0x247F,
  30296. twelveperiod: 0x2493,
  30297. twelveroman: 0x217B,
  30298. twentycircle: 0x2473,
  30299. twentyhangzhou: 0x5344,
  30300. twentyparen: 0x2487,
  30301. twentyperiod: 0x249B,
  30302. two: 0x0032,
  30303. twoarabic: 0x0662,
  30304. twobengali: 0x09E8,
  30305. twocircle: 0x2461,
  30306. twocircleinversesansserif: 0x278B,
  30307. twodeva: 0x0968,
  30308. twodotenleader: 0x2025,
  30309. twodotleader: 0x2025,
  30310. twodotleadervertical: 0xFE30,
  30311. twogujarati: 0x0AE8,
  30312. twogurmukhi: 0x0A68,
  30313. twohackarabic: 0x0662,
  30314. twohangzhou: 0x3022,
  30315. twoideographicparen: 0x3221,
  30316. twoinferior: 0x2082,
  30317. twomonospace: 0xFF12,
  30318. twonumeratorbengali: 0x09F5,
  30319. twooldstyle: 0xF732,
  30320. twoparen: 0x2475,
  30321. twoperiod: 0x2489,
  30322. twopersian: 0x06F2,
  30323. tworoman: 0x2171,
  30324. twostroke: 0x01BB,
  30325. twosuperior: 0x00B2,
  30326. twothai: 0x0E52,
  30327. twothirds: 0x2154,
  30328. u: 0x0075,
  30329. uacute: 0x00FA,
  30330. ubar: 0x0289,
  30331. ubengali: 0x0989,
  30332. ubopomofo: 0x3128,
  30333. ubreve: 0x016D,
  30334. ucaron: 0x01D4,
  30335. ucircle: 0x24E4,
  30336. ucircumflex: 0x00FB,
  30337. ucircumflexbelow: 0x1E77,
  30338. ucyrillic: 0x0443,
  30339. udattadeva: 0x0951,
  30340. udblacute: 0x0171,
  30341. udblgrave: 0x0215,
  30342. udeva: 0x0909,
  30343. udieresis: 0x00FC,
  30344. udieresisacute: 0x01D8,
  30345. udieresisbelow: 0x1E73,
  30346. udieresiscaron: 0x01DA,
  30347. udieresiscyrillic: 0x04F1,
  30348. udieresisgrave: 0x01DC,
  30349. udieresismacron: 0x01D6,
  30350. udotbelow: 0x1EE5,
  30351. ugrave: 0x00F9,
  30352. ugujarati: 0x0A89,
  30353. ugurmukhi: 0x0A09,
  30354. uhiragana: 0x3046,
  30355. uhookabove: 0x1EE7,
  30356. uhorn: 0x01B0,
  30357. uhornacute: 0x1EE9,
  30358. uhorndotbelow: 0x1EF1,
  30359. uhorngrave: 0x1EEB,
  30360. uhornhookabove: 0x1EED,
  30361. uhorntilde: 0x1EEF,
  30362. uhungarumlaut: 0x0171,
  30363. uhungarumlautcyrillic: 0x04F3,
  30364. uinvertedbreve: 0x0217,
  30365. ukatakana: 0x30A6,
  30366. ukatakanahalfwidth: 0xFF73,
  30367. ukcyrillic: 0x0479,
  30368. ukorean: 0x315C,
  30369. umacron: 0x016B,
  30370. umacroncyrillic: 0x04EF,
  30371. umacrondieresis: 0x1E7B,
  30372. umatragurmukhi: 0x0A41,
  30373. umonospace: 0xFF55,
  30374. underscore: 0x005F,
  30375. underscoredbl: 0x2017,
  30376. underscoremonospace: 0xFF3F,
  30377. underscorevertical: 0xFE33,
  30378. underscorewavy: 0xFE4F,
  30379. union: 0x222A,
  30380. universal: 0x2200,
  30381. uogonek: 0x0173,
  30382. uparen: 0x24B0,
  30383. upblock: 0x2580,
  30384. upperdothebrew: 0x05C4,
  30385. upsilon: 0x03C5,
  30386. upsilondieresis: 0x03CB,
  30387. upsilondieresistonos: 0x03B0,
  30388. upsilonlatin: 0x028A,
  30389. upsilontonos: 0x03CD,
  30390. uptackbelowcmb: 0x031D,
  30391. uptackmod: 0x02D4,
  30392. uragurmukhi: 0x0A73,
  30393. uring: 0x016F,
  30394. ushortcyrillic: 0x045E,
  30395. usmallhiragana: 0x3045,
  30396. usmallkatakana: 0x30A5,
  30397. usmallkatakanahalfwidth: 0xFF69,
  30398. ustraightcyrillic: 0x04AF,
  30399. ustraightstrokecyrillic: 0x04B1,
  30400. utilde: 0x0169,
  30401. utildeacute: 0x1E79,
  30402. utildebelow: 0x1E75,
  30403. uubengali: 0x098A,
  30404. uudeva: 0x090A,
  30405. uugujarati: 0x0A8A,
  30406. uugurmukhi: 0x0A0A,
  30407. uumatragurmukhi: 0x0A42,
  30408. uuvowelsignbengali: 0x09C2,
  30409. uuvowelsigndeva: 0x0942,
  30410. uuvowelsigngujarati: 0x0AC2,
  30411. uvowelsignbengali: 0x09C1,
  30412. uvowelsigndeva: 0x0941,
  30413. uvowelsigngujarati: 0x0AC1,
  30414. v: 0x0076,
  30415. vadeva: 0x0935,
  30416. vagujarati: 0x0AB5,
  30417. vagurmukhi: 0x0A35,
  30418. vakatakana: 0x30F7,
  30419. vav: 0x05D5,
  30420. vavdagesh: 0xFB35,
  30421. vavdagesh65: 0xFB35,
  30422. vavdageshhebrew: 0xFB35,
  30423. vavhebrew: 0x05D5,
  30424. vavholam: 0xFB4B,
  30425. vavholamhebrew: 0xFB4B,
  30426. vavvavhebrew: 0x05F0,
  30427. vavyodhebrew: 0x05F1,
  30428. vcircle: 0x24E5,
  30429. vdotbelow: 0x1E7F,
  30430. vecyrillic: 0x0432,
  30431. veharabic: 0x06A4,
  30432. vehfinalarabic: 0xFB6B,
  30433. vehinitialarabic: 0xFB6C,
  30434. vehmedialarabic: 0xFB6D,
  30435. vekatakana: 0x30F9,
  30436. venus: 0x2640,
  30437. verticalbar: 0x007C,
  30438. verticallineabovecmb: 0x030D,
  30439. verticallinebelowcmb: 0x0329,
  30440. verticallinelowmod: 0x02CC,
  30441. verticallinemod: 0x02C8,
  30442. vewarmenian: 0x057E,
  30443. vhook: 0x028B,
  30444. vikatakana: 0x30F8,
  30445. viramabengali: 0x09CD,
  30446. viramadeva: 0x094D,
  30447. viramagujarati: 0x0ACD,
  30448. visargabengali: 0x0983,
  30449. visargadeva: 0x0903,
  30450. visargagujarati: 0x0A83,
  30451. vmonospace: 0xFF56,
  30452. voarmenian: 0x0578,
  30453. voicediterationhiragana: 0x309E,
  30454. voicediterationkatakana: 0x30FE,
  30455. voicedmarkkana: 0x309B,
  30456. voicedmarkkanahalfwidth: 0xFF9E,
  30457. vokatakana: 0x30FA,
  30458. vparen: 0x24B1,
  30459. vtilde: 0x1E7D,
  30460. vturned: 0x028C,
  30461. vuhiragana: 0x3094,
  30462. vukatakana: 0x30F4,
  30463. w: 0x0077,
  30464. wacute: 0x1E83,
  30465. waekorean: 0x3159,
  30466. wahiragana: 0x308F,
  30467. wakatakana: 0x30EF,
  30468. wakatakanahalfwidth: 0xFF9C,
  30469. wakorean: 0x3158,
  30470. wasmallhiragana: 0x308E,
  30471. wasmallkatakana: 0x30EE,
  30472. wattosquare: 0x3357,
  30473. wavedash: 0x301C,
  30474. wavyunderscorevertical: 0xFE34,
  30475. wawarabic: 0x0648,
  30476. wawfinalarabic: 0xFEEE,
  30477. wawhamzaabovearabic: 0x0624,
  30478. wawhamzaabovefinalarabic: 0xFE86,
  30479. wbsquare: 0x33DD,
  30480. wcircle: 0x24E6,
  30481. wcircumflex: 0x0175,
  30482. wdieresis: 0x1E85,
  30483. wdotaccent: 0x1E87,
  30484. wdotbelow: 0x1E89,
  30485. wehiragana: 0x3091,
  30486. weierstrass: 0x2118,
  30487. wekatakana: 0x30F1,
  30488. wekorean: 0x315E,
  30489. weokorean: 0x315D,
  30490. wgrave: 0x1E81,
  30491. whitebullet: 0x25E6,
  30492. whitecircle: 0x25CB,
  30493. whitecircleinverse: 0x25D9,
  30494. whitecornerbracketleft: 0x300E,
  30495. whitecornerbracketleftvertical: 0xFE43,
  30496. whitecornerbracketright: 0x300F,
  30497. whitecornerbracketrightvertical: 0xFE44,
  30498. whitediamond: 0x25C7,
  30499. whitediamondcontainingblacksmalldiamond: 0x25C8,
  30500. whitedownpointingsmalltriangle: 0x25BF,
  30501. whitedownpointingtriangle: 0x25BD,
  30502. whiteleftpointingsmalltriangle: 0x25C3,
  30503. whiteleftpointingtriangle: 0x25C1,
  30504. whitelenticularbracketleft: 0x3016,
  30505. whitelenticularbracketright: 0x3017,
  30506. whiterightpointingsmalltriangle: 0x25B9,
  30507. whiterightpointingtriangle: 0x25B7,
  30508. whitesmallsquare: 0x25AB,
  30509. whitesmilingface: 0x263A,
  30510. whitesquare: 0x25A1,
  30511. whitestar: 0x2606,
  30512. whitetelephone: 0x260F,
  30513. whitetortoiseshellbracketleft: 0x3018,
  30514. whitetortoiseshellbracketright: 0x3019,
  30515. whiteuppointingsmalltriangle: 0x25B5,
  30516. whiteuppointingtriangle: 0x25B3,
  30517. wihiragana: 0x3090,
  30518. wikatakana: 0x30F0,
  30519. wikorean: 0x315F,
  30520. wmonospace: 0xFF57,
  30521. wohiragana: 0x3092,
  30522. wokatakana: 0x30F2,
  30523. wokatakanahalfwidth: 0xFF66,
  30524. won: 0x20A9,
  30525. wonmonospace: 0xFFE6,
  30526. wowaenthai: 0x0E27,
  30527. wparen: 0x24B2,
  30528. wring: 0x1E98,
  30529. wsuperior: 0x02B7,
  30530. wturned: 0x028D,
  30531. wynn: 0x01BF,
  30532. x: 0x0078,
  30533. xabovecmb: 0x033D,
  30534. xbopomofo: 0x3112,
  30535. xcircle: 0x24E7,
  30536. xdieresis: 0x1E8D,
  30537. xdotaccent: 0x1E8B,
  30538. xeharmenian: 0x056D,
  30539. xi: 0x03BE,
  30540. xmonospace: 0xFF58,
  30541. xparen: 0x24B3,
  30542. xsuperior: 0x02E3,
  30543. y: 0x0079,
  30544. yaadosquare: 0x334E,
  30545. yabengali: 0x09AF,
  30546. yacute: 0x00FD,
  30547. yadeva: 0x092F,
  30548. yaekorean: 0x3152,
  30549. yagujarati: 0x0AAF,
  30550. yagurmukhi: 0x0A2F,
  30551. yahiragana: 0x3084,
  30552. yakatakana: 0x30E4,
  30553. yakatakanahalfwidth: 0xFF94,
  30554. yakorean: 0x3151,
  30555. yamakkanthai: 0x0E4E,
  30556. yasmallhiragana: 0x3083,
  30557. yasmallkatakana: 0x30E3,
  30558. yasmallkatakanahalfwidth: 0xFF6C,
  30559. yatcyrillic: 0x0463,
  30560. ycircle: 0x24E8,
  30561. ycircumflex: 0x0177,
  30562. ydieresis: 0x00FF,
  30563. ydotaccent: 0x1E8F,
  30564. ydotbelow: 0x1EF5,
  30565. yeharabic: 0x064A,
  30566. yehbarreearabic: 0x06D2,
  30567. yehbarreefinalarabic: 0xFBAF,
  30568. yehfinalarabic: 0xFEF2,
  30569. yehhamzaabovearabic: 0x0626,
  30570. yehhamzaabovefinalarabic: 0xFE8A,
  30571. yehhamzaaboveinitialarabic: 0xFE8B,
  30572. yehhamzaabovemedialarabic: 0xFE8C,
  30573. yehinitialarabic: 0xFEF3,
  30574. yehmedialarabic: 0xFEF4,
  30575. yehmeeminitialarabic: 0xFCDD,
  30576. yehmeemisolatedarabic: 0xFC58,
  30577. yehnoonfinalarabic: 0xFC94,
  30578. yehthreedotsbelowarabic: 0x06D1,
  30579. yekorean: 0x3156,
  30580. yen: 0x00A5,
  30581. yenmonospace: 0xFFE5,
  30582. yeokorean: 0x3155,
  30583. yeorinhieuhkorean: 0x3186,
  30584. yerahbenyomohebrew: 0x05AA,
  30585. yerahbenyomolefthebrew: 0x05AA,
  30586. yericyrillic: 0x044B,
  30587. yerudieresiscyrillic: 0x04F9,
  30588. yesieungkorean: 0x3181,
  30589. yesieungpansioskorean: 0x3183,
  30590. yesieungsioskorean: 0x3182,
  30591. yetivhebrew: 0x059A,
  30592. ygrave: 0x1EF3,
  30593. yhook: 0x01B4,
  30594. yhookabove: 0x1EF7,
  30595. yiarmenian: 0x0575,
  30596. yicyrillic: 0x0457,
  30597. yikorean: 0x3162,
  30598. yinyang: 0x262F,
  30599. yiwnarmenian: 0x0582,
  30600. ymonospace: 0xFF59,
  30601. yod: 0x05D9,
  30602. yoddagesh: 0xFB39,
  30603. yoddageshhebrew: 0xFB39,
  30604. yodhebrew: 0x05D9,
  30605. yodyodhebrew: 0x05F2,
  30606. yodyodpatahhebrew: 0xFB1F,
  30607. yohiragana: 0x3088,
  30608. yoikorean: 0x3189,
  30609. yokatakana: 0x30E8,
  30610. yokatakanahalfwidth: 0xFF96,
  30611. yokorean: 0x315B,
  30612. yosmallhiragana: 0x3087,
  30613. yosmallkatakana: 0x30E7,
  30614. yosmallkatakanahalfwidth: 0xFF6E,
  30615. yotgreek: 0x03F3,
  30616. yoyaekorean: 0x3188,
  30617. yoyakorean: 0x3187,
  30618. yoyakthai: 0x0E22,
  30619. yoyingthai: 0x0E0D,
  30620. yparen: 0x24B4,
  30621. ypogegrammeni: 0x037A,
  30622. ypogegrammenigreekcmb: 0x0345,
  30623. yr: 0x01A6,
  30624. yring: 0x1E99,
  30625. ysuperior: 0x02B8,
  30626. ytilde: 0x1EF9,
  30627. yturned: 0x028E,
  30628. yuhiragana: 0x3086,
  30629. yuikorean: 0x318C,
  30630. yukatakana: 0x30E6,
  30631. yukatakanahalfwidth: 0xFF95,
  30632. yukorean: 0x3160,
  30633. yusbigcyrillic: 0x046B,
  30634. yusbigiotifiedcyrillic: 0x046D,
  30635. yuslittlecyrillic: 0x0467,
  30636. yuslittleiotifiedcyrillic: 0x0469,
  30637. yusmallhiragana: 0x3085,
  30638. yusmallkatakana: 0x30E5,
  30639. yusmallkatakanahalfwidth: 0xFF6D,
  30640. yuyekorean: 0x318B,
  30641. yuyeokorean: 0x318A,
  30642. yyabengali: 0x09DF,
  30643. yyadeva: 0x095F,
  30644. z: 0x007A,
  30645. zaarmenian: 0x0566,
  30646. zacute: 0x017A,
  30647. zadeva: 0x095B,
  30648. zagurmukhi: 0x0A5B,
  30649. zaharabic: 0x0638,
  30650. zahfinalarabic: 0xFEC6,
  30651. zahinitialarabic: 0xFEC7,
  30652. zahiragana: 0x3056,
  30653. zahmedialarabic: 0xFEC8,
  30654. zainarabic: 0x0632,
  30655. zainfinalarabic: 0xFEB0,
  30656. zakatakana: 0x30B6,
  30657. zaqefgadolhebrew: 0x0595,
  30658. zaqefqatanhebrew: 0x0594,
  30659. zarqahebrew: 0x0598,
  30660. zayin: 0x05D6,
  30661. zayindagesh: 0xFB36,
  30662. zayindageshhebrew: 0xFB36,
  30663. zayinhebrew: 0x05D6,
  30664. zbopomofo: 0x3117,
  30665. zcaron: 0x017E,
  30666. zcircle: 0x24E9,
  30667. zcircumflex: 0x1E91,
  30668. zcurl: 0x0291,
  30669. zdot: 0x017C,
  30670. zdotaccent: 0x017C,
  30671. zdotbelow: 0x1E93,
  30672. zecyrillic: 0x0437,
  30673. zedescendercyrillic: 0x0499,
  30674. zedieresiscyrillic: 0x04DF,
  30675. zehiragana: 0x305C,
  30676. zekatakana: 0x30BC,
  30677. zero: 0x0030,
  30678. zeroarabic: 0x0660,
  30679. zerobengali: 0x09E6,
  30680. zerodeva: 0x0966,
  30681. zerogujarati: 0x0AE6,
  30682. zerogurmukhi: 0x0A66,
  30683. zerohackarabic: 0x0660,
  30684. zeroinferior: 0x2080,
  30685. zeromonospace: 0xFF10,
  30686. zerooldstyle: 0xF730,
  30687. zeropersian: 0x06F0,
  30688. zerosuperior: 0x2070,
  30689. zerothai: 0x0E50,
  30690. zerowidthjoiner: 0xFEFF,
  30691. zerowidthnonjoiner: 0x200C,
  30692. zerowidthspace: 0x200B,
  30693. zeta: 0x03B6,
  30694. zhbopomofo: 0x3113,
  30695. zhearmenian: 0x056A,
  30696. zhebrevecyrillic: 0x04C2,
  30697. zhecyrillic: 0x0436,
  30698. zhedescendercyrillic: 0x0497,
  30699. zhedieresiscyrillic: 0x04DD,
  30700. zihiragana: 0x3058,
  30701. zikatakana: 0x30B8,
  30702. zinorhebrew: 0x05AE,
  30703. zlinebelow: 0x1E95,
  30704. zmonospace: 0xFF5A,
  30705. zohiragana: 0x305E,
  30706. zokatakana: 0x30BE,
  30707. zparen: 0x24B5,
  30708. zretroflexhook: 0x0290,
  30709. zstroke: 0x01B6,
  30710. zuhiragana: 0x305A,
  30711. zukatakana: 0x30BA,
  30712. '.notdef': 0x0000
  30713. };
  30714. var DingbatsGlyphsUnicode = {
  30715. space: 0x0020,
  30716. a1: 0x2701,
  30717. a2: 0x2702,
  30718. a202: 0x2703,
  30719. a3: 0x2704,
  30720. a4: 0x260E,
  30721. a5: 0x2706,
  30722. a119: 0x2707,
  30723. a118: 0x2708,
  30724. a117: 0x2709,
  30725. a11: 0x261B,
  30726. a12: 0x261E,
  30727. a13: 0x270C,
  30728. a14: 0x270D,
  30729. a15: 0x270E,
  30730. a16: 0x270F,
  30731. a105: 0x2710,
  30732. a17: 0x2711,
  30733. a18: 0x2712,
  30734. a19: 0x2713,
  30735. a20: 0x2714,
  30736. a21: 0x2715,
  30737. a22: 0x2716,
  30738. a23: 0x2717,
  30739. a24: 0x2718,
  30740. a25: 0x2719,
  30741. a26: 0x271A,
  30742. a27: 0x271B,
  30743. a28: 0x271C,
  30744. a6: 0x271D,
  30745. a7: 0x271E,
  30746. a8: 0x271F,
  30747. a9: 0x2720,
  30748. a10: 0x2721,
  30749. a29: 0x2722,
  30750. a30: 0x2723,
  30751. a31: 0x2724,
  30752. a32: 0x2725,
  30753. a33: 0x2726,
  30754. a34: 0x2727,
  30755. a35: 0x2605,
  30756. a36: 0x2729,
  30757. a37: 0x272A,
  30758. a38: 0x272B,
  30759. a39: 0x272C,
  30760. a40: 0x272D,
  30761. a41: 0x272E,
  30762. a42: 0x272F,
  30763. a43: 0x2730,
  30764. a44: 0x2731,
  30765. a45: 0x2732,
  30766. a46: 0x2733,
  30767. a47: 0x2734,
  30768. a48: 0x2735,
  30769. a49: 0x2736,
  30770. a50: 0x2737,
  30771. a51: 0x2738,
  30772. a52: 0x2739,
  30773. a53: 0x273A,
  30774. a54: 0x273B,
  30775. a55: 0x273C,
  30776. a56: 0x273D,
  30777. a57: 0x273E,
  30778. a58: 0x273F,
  30779. a59: 0x2740,
  30780. a60: 0x2741,
  30781. a61: 0x2742,
  30782. a62: 0x2743,
  30783. a63: 0x2744,
  30784. a64: 0x2745,
  30785. a65: 0x2746,
  30786. a66: 0x2747,
  30787. a67: 0x2748,
  30788. a68: 0x2749,
  30789. a69: 0x274A,
  30790. a70: 0x274B,
  30791. a71: 0x25CF,
  30792. a72: 0x274D,
  30793. a73: 0x25A0,
  30794. a74: 0x274F,
  30795. a203: 0x2750,
  30796. a75: 0x2751,
  30797. a204: 0x2752,
  30798. a76: 0x25B2,
  30799. a77: 0x25BC,
  30800. a78: 0x25C6,
  30801. a79: 0x2756,
  30802. a81: 0x25D7,
  30803. a82: 0x2758,
  30804. a83: 0x2759,
  30805. a84: 0x275A,
  30806. a97: 0x275B,
  30807. a98: 0x275C,
  30808. a99: 0x275D,
  30809. a100: 0x275E,
  30810. a101: 0x2761,
  30811. a102: 0x2762,
  30812. a103: 0x2763,
  30813. a104: 0x2764,
  30814. a106: 0x2765,
  30815. a107: 0x2766,
  30816. a108: 0x2767,
  30817. a112: 0x2663,
  30818. a111: 0x2666,
  30819. a110: 0x2665,
  30820. a109: 0x2660,
  30821. a120: 0x2460,
  30822. a121: 0x2461,
  30823. a122: 0x2462,
  30824. a123: 0x2463,
  30825. a124: 0x2464,
  30826. a125: 0x2465,
  30827. a126: 0x2466,
  30828. a127: 0x2467,
  30829. a128: 0x2468,
  30830. a129: 0x2469,
  30831. a130: 0x2776,
  30832. a131: 0x2777,
  30833. a132: 0x2778,
  30834. a133: 0x2779,
  30835. a134: 0x277A,
  30836. a135: 0x277B,
  30837. a136: 0x277C,
  30838. a137: 0x277D,
  30839. a138: 0x277E,
  30840. a139: 0x277F,
  30841. a140: 0x2780,
  30842. a141: 0x2781,
  30843. a142: 0x2782,
  30844. a143: 0x2783,
  30845. a144: 0x2784,
  30846. a145: 0x2785,
  30847. a146: 0x2786,
  30848. a147: 0x2787,
  30849. a148: 0x2788,
  30850. a149: 0x2789,
  30851. a150: 0x278A,
  30852. a151: 0x278B,
  30853. a152: 0x278C,
  30854. a153: 0x278D,
  30855. a154: 0x278E,
  30856. a155: 0x278F,
  30857. a156: 0x2790,
  30858. a157: 0x2791,
  30859. a158: 0x2792,
  30860. a159: 0x2793,
  30861. a160: 0x2794,
  30862. a161: 0x2192,
  30863. a163: 0x2194,
  30864. a164: 0x2195,
  30865. a196: 0x2798,
  30866. a165: 0x2799,
  30867. a192: 0x279A,
  30868. a166: 0x279B,
  30869. a167: 0x279C,
  30870. a168: 0x279D,
  30871. a169: 0x279E,
  30872. a170: 0x279F,
  30873. a171: 0x27A0,
  30874. a172: 0x27A1,
  30875. a173: 0x27A2,
  30876. a162: 0x27A3,
  30877. a174: 0x27A4,
  30878. a175: 0x27A5,
  30879. a176: 0x27A6,
  30880. a177: 0x27A7,
  30881. a178: 0x27A8,
  30882. a179: 0x27A9,
  30883. a193: 0x27AA,
  30884. a180: 0x27AB,
  30885. a199: 0x27AC,
  30886. a181: 0x27AD,
  30887. a200: 0x27AE,
  30888. a182: 0x27AF,
  30889. a201: 0x27B1,
  30890. a183: 0x27B2,
  30891. a184: 0x27B3,
  30892. a197: 0x27B4,
  30893. a185: 0x27B5,
  30894. a194: 0x27B6,
  30895. a198: 0x27B7,
  30896. a186: 0x27B8,
  30897. a195: 0x27B9,
  30898. a187: 0x27BA,
  30899. a188: 0x27BB,
  30900. a189: 0x27BC,
  30901. a190: 0x27BD,
  30902. a191: 0x27BE,
  30903. a89: 0x2768, // 0xF8D7
  30904. a90: 0x2769, // 0xF8D8
  30905. a93: 0x276A, // 0xF8D9
  30906. a94: 0x276B, // 0xF8DA
  30907. a91: 0x276C, // 0xF8DB
  30908. a92: 0x276D, // 0xF8DC
  30909. a205: 0x276E, // 0xF8DD
  30910. a85: 0x276F, // 0xF8DE
  30911. a206: 0x2770, // 0xF8DF
  30912. a86: 0x2771, // 0xF8E0
  30913. a87: 0x2772, // 0xF8E1
  30914. a88: 0x2773, // 0xF8E2
  30915. a95: 0x2774, // 0xF8E3
  30916. a96: 0x2775, // 0xF8E4
  30917. '.notdef': 0x0000
  30918. };
  30919. var PDFImage = (function PDFImageClosure() {
  30920. /**
  30921. * Decode the image in the main thread if it supported. Resovles the promise
  30922. * when the image data is ready.
  30923. */
  30924. function handleImageData(handler, xref, res, image) {
  30925. if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {
  30926. // For natively supported jpegs send them to the main thread for decoding.
  30927. var dict = image.dict;
  30928. var colorSpace = dict.get('ColorSpace', 'CS');
  30929. colorSpace = ColorSpace.parse(colorSpace, xref, res);
  30930. var numComps = colorSpace.numComps;
  30931. var decodePromise = handler.sendWithPromise('JpegDecode',
  30932. [image.getIR(), numComps]);
  30933. return decodePromise.then(function (message) {
  30934. var data = message.data;
  30935. return new Stream(data, 0, data.length, image.dict);
  30936. });
  30937. } else {
  30938. return Promise.resolve(image);
  30939. }
  30940. }
  30941. /**
  30942. * Decode and clamp a value. The formula is different from the spec because we
  30943. * don't decode to float range [0,1], we decode it in the [0,max] range.
  30944. */
  30945. function decodeAndClamp(value, addend, coefficient, max) {
  30946. value = addend + value * coefficient;
  30947. // Clamp the value to the range
  30948. return (value < 0 ? 0 : (value > max ? max : value));
  30949. }
  30950. function PDFImage(xref, res, image, inline, smask, mask, isMask) {
  30951. this.image = image;
  30952. var dict = image.dict;
  30953. if (dict.has('Filter')) {
  30954. var filter = dict.get('Filter').name;
  30955. if (filter === 'JPXDecode') {
  30956. var jpxImage = new JpxImage();
  30957. jpxImage.parseImageProperties(image.stream);
  30958. image.stream.reset();
  30959. image.bitsPerComponent = jpxImage.bitsPerComponent;
  30960. image.numComps = jpxImage.componentsCount;
  30961. } else if (filter === 'JBIG2Decode') {
  30962. image.bitsPerComponent = 1;
  30963. image.numComps = 1;
  30964. }
  30965. }
  30966. // TODO cache rendered images?
  30967. this.width = dict.get('Width', 'W');
  30968. this.height = dict.get('Height', 'H');
  30969. if (this.width < 1 || this.height < 1) {
  30970. error('Invalid image width: ' + this.width + ' or height: ' +
  30971. this.height);
  30972. }
  30973. this.interpolate = dict.get('Interpolate', 'I') || false;
  30974. this.imageMask = dict.get('ImageMask', 'IM') || false;
  30975. this.matte = dict.get('Matte') || false;
  30976. var bitsPerComponent = image.bitsPerComponent;
  30977. if (!bitsPerComponent) {
  30978. bitsPerComponent = dict.get('BitsPerComponent', 'BPC');
  30979. if (!bitsPerComponent) {
  30980. if (this.imageMask) {
  30981. bitsPerComponent = 1;
  30982. } else {
  30983. error('Bits per component missing in image: ' + this.imageMask);
  30984. }
  30985. }
  30986. }
  30987. this.bpc = bitsPerComponent;
  30988. if (!this.imageMask) {
  30989. var colorSpace = dict.get('ColorSpace', 'CS');
  30990. if (!colorSpace) {
  30991. info('JPX images (which do not require color spaces)');
  30992. switch (image.numComps) {
  30993. case 1:
  30994. colorSpace = Name.get('DeviceGray');
  30995. break;
  30996. case 3:
  30997. colorSpace = Name.get('DeviceRGB');
  30998. break;
  30999. case 4:
  31000. colorSpace = Name.get('DeviceCMYK');
  31001. break;
  31002. default:
  31003. error('JPX images with ' + this.numComps +
  31004. ' color components not supported.');
  31005. }
  31006. }
  31007. this.colorSpace = ColorSpace.parse(colorSpace, xref, res);
  31008. this.numComps = this.colorSpace.numComps;
  31009. }
  31010. this.decode = dict.get('Decode', 'D');
  31011. this.needsDecode = false;
  31012. if (this.decode &&
  31013. ((this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode)) ||
  31014. (isMask && !ColorSpace.isDefaultDecode(this.decode, 1)))) {
  31015. this.needsDecode = true;
  31016. // Do some preprocessing to avoid more math.
  31017. var max = (1 << bitsPerComponent) - 1;
  31018. this.decodeCoefficients = [];
  31019. this.decodeAddends = [];
  31020. for (var i = 0, j = 0; i < this.decode.length; i += 2, ++j) {
  31021. var dmin = this.decode[i];
  31022. var dmax = this.decode[i + 1];
  31023. this.decodeCoefficients[j] = dmax - dmin;
  31024. this.decodeAddends[j] = max * dmin;
  31025. }
  31026. }
  31027. if (smask) {
  31028. this.smask = new PDFImage(xref, res, smask, false);
  31029. } else if (mask) {
  31030. if (isStream(mask)) {
  31031. this.mask = new PDFImage(xref, res, mask, false, null, null, true);
  31032. } else {
  31033. // Color key mask (just an array).
  31034. this.mask = mask;
  31035. }
  31036. }
  31037. }
  31038. /**
  31039. * Handles processing of image data and returns the Promise that is resolved
  31040. * with a PDFImage when the image is ready to be used.
  31041. */
  31042. PDFImage.buildImage = function PDFImage_buildImage(handler, xref,
  31043. res, image, inline) {
  31044. var imagePromise = handleImageData(handler, xref, res, image);
  31045. var smaskPromise;
  31046. var maskPromise;
  31047. var smask = image.dict.get('SMask');
  31048. var mask = image.dict.get('Mask');
  31049. if (smask) {
  31050. smaskPromise = handleImageData(handler, xref, res, smask);
  31051. maskPromise = Promise.resolve(null);
  31052. } else {
  31053. smaskPromise = Promise.resolve(null);
  31054. if (mask) {
  31055. if (isStream(mask)) {
  31056. maskPromise = handleImageData(handler, xref, res, mask);
  31057. } else if (isArray(mask)) {
  31058. maskPromise = Promise.resolve(mask);
  31059. } else {
  31060. warn('Unsupported mask format.');
  31061. maskPromise = Promise.resolve(null);
  31062. }
  31063. } else {
  31064. maskPromise = Promise.resolve(null);
  31065. }
  31066. }
  31067. return Promise.all([imagePromise, smaskPromise, maskPromise]).then(
  31068. function(results) {
  31069. var imageData = results[0];
  31070. var smaskData = results[1];
  31071. var maskData = results[2];
  31072. return new PDFImage(xref, res, imageData, inline, smaskData, maskData);
  31073. });
  31074. };
  31075. /**
  31076. * Resize an image using the nearest neighbor algorithm. Currently only
  31077. * supports one and three component images.
  31078. * @param {TypedArray} pixels The original image with one component.
  31079. * @param {Number} bpc Number of bits per component.
  31080. * @param {Number} components Number of color components, 1 or 3 is supported.
  31081. * @param {Number} w1 Original width.
  31082. * @param {Number} h1 Original height.
  31083. * @param {Number} w2 New width.
  31084. * @param {Number} h2 New height.
  31085. * @param {TypedArray} dest (Optional) The destination buffer.
  31086. * @param {Number} alpha01 (Optional) Size reserved for the alpha channel.
  31087. * @return {TypedArray} Resized image data.
  31088. */
  31089. PDFImage.resize = function PDFImage_resize(pixels, bpc, components,
  31090. w1, h1, w2, h2, dest, alpha01) {
  31091. if (components !== 1 && components !== 3) {
  31092. error('Unsupported component count for resizing.');
  31093. }
  31094. var length = w2 * h2 * components;
  31095. var temp = dest ? dest : (bpc <= 8 ? new Uint8Array(length) :
  31096. (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));
  31097. var xRatio = w1 / w2;
  31098. var yRatio = h1 / h2;
  31099. var i, j, py, newIndex = 0, oldIndex;
  31100. var xScaled = new Uint16Array(w2);
  31101. var w1Scanline = w1 * components;
  31102. if (alpha01 !== 1) {
  31103. alpha01 = 0;
  31104. }
  31105. for (j = 0; j < w2; j++) {
  31106. xScaled[j] = Math.floor(j * xRatio) * components;
  31107. }
  31108. if (components === 1) {
  31109. for (i = 0; i < h2; i++) {
  31110. py = Math.floor(i * yRatio) * w1Scanline;
  31111. for (j = 0; j < w2; j++) {
  31112. oldIndex = py + xScaled[j];
  31113. temp[newIndex++] = pixels[oldIndex];
  31114. }
  31115. }
  31116. } else if (components === 3) {
  31117. for (i = 0; i < h2; i++) {
  31118. py = Math.floor(i * yRatio) * w1Scanline;
  31119. for (j = 0; j < w2; j++) {
  31120. oldIndex = py + xScaled[j];
  31121. temp[newIndex++] = pixels[oldIndex++];
  31122. temp[newIndex++] = pixels[oldIndex++];
  31123. temp[newIndex++] = pixels[oldIndex++];
  31124. newIndex += alpha01;
  31125. }
  31126. }
  31127. }
  31128. return temp;
  31129. };
  31130. PDFImage.createMask =
  31131. function PDFImage_createMask(imgArray, width, height,
  31132. imageIsFromDecodeStream, inverseDecode) {
  31133. // |imgArray| might not contain full data for every pixel of the mask, so
  31134. // we need to distinguish between |computedLength| and |actualLength|.
  31135. // In particular, if inverseDecode is true, then the array we return must
  31136. // have a length of |computedLength|.
  31137. var computedLength = ((width + 7) >> 3) * height;
  31138. var actualLength = imgArray.byteLength;
  31139. var haveFullData = computedLength === actualLength;
  31140. var data, i;
  31141. if (imageIsFromDecodeStream && (!inverseDecode || haveFullData)) {
  31142. // imgArray came from a DecodeStream and its data is in an appropriate
  31143. // form, so we can just transfer it.
  31144. data = imgArray;
  31145. } else if (!inverseDecode) {
  31146. data = new Uint8Array(actualLength);
  31147. data.set(imgArray);
  31148. } else {
  31149. data = new Uint8Array(computedLength);
  31150. data.set(imgArray);
  31151. for (i = actualLength; i < computedLength; i++) {
  31152. data[i] = 0xff;
  31153. }
  31154. }
  31155. // If necessary, invert the original mask data (but not any extra we might
  31156. // have added above). It's safe to modify the array -- whether it's the
  31157. // original or a copy, we're about to transfer it anyway, so nothing else
  31158. // in this thread can be relying on its contents.
  31159. if (inverseDecode) {
  31160. for (i = 0; i < actualLength; i++) {
  31161. data[i] = ~data[i];
  31162. }
  31163. }
  31164. return {data: data, width: width, height: height};
  31165. };
  31166. PDFImage.prototype = {
  31167. get drawWidth() {
  31168. return Math.max(this.width,
  31169. this.smask && this.smask.width || 0,
  31170. this.mask && this.mask.width || 0);
  31171. },
  31172. get drawHeight() {
  31173. return Math.max(this.height,
  31174. this.smask && this.smask.height || 0,
  31175. this.mask && this.mask.height || 0);
  31176. },
  31177. decodeBuffer: function PDFImage_decodeBuffer(buffer) {
  31178. var bpc = this.bpc;
  31179. var numComps = this.numComps;
  31180. var decodeAddends = this.decodeAddends;
  31181. var decodeCoefficients = this.decodeCoefficients;
  31182. var max = (1 << bpc) - 1;
  31183. var i, ii;
  31184. if (bpc === 1) {
  31185. // If the buffer needed decode that means it just needs to be inverted.
  31186. for (i = 0, ii = buffer.length; i < ii; i++) {
  31187. buffer[i] = +!(buffer[i]);
  31188. }
  31189. return;
  31190. }
  31191. var index = 0;
  31192. for (i = 0, ii = this.width * this.height; i < ii; i++) {
  31193. for (var j = 0; j < numComps; j++) {
  31194. buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j],
  31195. decodeCoefficients[j], max);
  31196. index++;
  31197. }
  31198. }
  31199. },
  31200. getComponents: function PDFImage_getComponents(buffer) {
  31201. var bpc = this.bpc;
  31202. // This image doesn't require any extra work.
  31203. if (bpc === 8) {
  31204. return buffer;
  31205. }
  31206. var width = this.width;
  31207. var height = this.height;
  31208. var numComps = this.numComps;
  31209. var length = width * height * numComps;
  31210. var bufferPos = 0;
  31211. var output = (bpc <= 8 ? new Uint8Array(length) :
  31212. (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));
  31213. var rowComps = width * numComps;
  31214. var max = (1 << bpc) - 1;
  31215. var i = 0, ii, buf;
  31216. if (bpc === 1) {
  31217. // Optimization for reading 1 bpc images.
  31218. var mask, loop1End, loop2End;
  31219. for (var j = 0; j < height; j++) {
  31220. loop1End = i + (rowComps & ~7);
  31221. loop2End = i + rowComps;
  31222. // unroll loop for all full bytes
  31223. while (i < loop1End) {
  31224. buf = buffer[bufferPos++];
  31225. output[i] = (buf >> 7) & 1;
  31226. output[i + 1] = (buf >> 6) & 1;
  31227. output[i + 2] = (buf >> 5) & 1;
  31228. output[i + 3] = (buf >> 4) & 1;
  31229. output[i + 4] = (buf >> 3) & 1;
  31230. output[i + 5] = (buf >> 2) & 1;
  31231. output[i + 6] = (buf >> 1) & 1;
  31232. output[i + 7] = buf & 1;
  31233. i += 8;
  31234. }
  31235. // handle remaing bits
  31236. if (i < loop2End) {
  31237. buf = buffer[bufferPos++];
  31238. mask = 128;
  31239. while (i < loop2End) {
  31240. output[i++] = +!!(buf & mask);
  31241. mask >>= 1;
  31242. }
  31243. }
  31244. }
  31245. } else {
  31246. // The general case that handles all other bpc values.
  31247. var bits = 0;
  31248. buf = 0;
  31249. for (i = 0, ii = length; i < ii; ++i) {
  31250. if (i % rowComps === 0) {
  31251. buf = 0;
  31252. bits = 0;
  31253. }
  31254. while (bits < bpc) {
  31255. buf = (buf << 8) | buffer[bufferPos++];
  31256. bits += 8;
  31257. }
  31258. var remainingBits = bits - bpc;
  31259. var value = buf >> remainingBits;
  31260. output[i] = (value < 0 ? 0 : (value > max ? max : value));
  31261. buf = buf & ((1 << remainingBits) - 1);
  31262. bits = remainingBits;
  31263. }
  31264. }
  31265. return output;
  31266. },
  31267. fillOpacity: function PDFImage_fillOpacity(rgbaBuf, width, height,
  31268. actualHeight, image) {
  31269. var smask = this.smask;
  31270. var mask = this.mask;
  31271. var alphaBuf, sw, sh, i, ii, j;
  31272. if (smask) {
  31273. sw = smask.width;
  31274. sh = smask.height;
  31275. alphaBuf = new Uint8Array(sw * sh);
  31276. smask.fillGrayBuffer(alphaBuf);
  31277. if (sw !== width || sh !== height) {
  31278. alphaBuf = PDFImage.resize(alphaBuf, smask.bpc, 1, sw, sh, width,
  31279. height);
  31280. }
  31281. } else if (mask) {
  31282. if (mask instanceof PDFImage) {
  31283. sw = mask.width;
  31284. sh = mask.height;
  31285. alphaBuf = new Uint8Array(sw * sh);
  31286. mask.numComps = 1;
  31287. mask.fillGrayBuffer(alphaBuf);
  31288. // Need to invert values in rgbaBuf
  31289. for (i = 0, ii = sw * sh; i < ii; ++i) {
  31290. alphaBuf[i] = 255 - alphaBuf[i];
  31291. }
  31292. if (sw !== width || sh !== height) {
  31293. alphaBuf = PDFImage.resize(alphaBuf, mask.bpc, 1, sw, sh, width,
  31294. height);
  31295. }
  31296. } else if (isArray(mask)) {
  31297. // Color key mask: if any of the compontents are outside the range
  31298. // then they should be painted.
  31299. alphaBuf = new Uint8Array(width * height);
  31300. var numComps = this.numComps;
  31301. for (i = 0, ii = width * height; i < ii; ++i) {
  31302. var opacity = 0;
  31303. var imageOffset = i * numComps;
  31304. for (j = 0; j < numComps; ++j) {
  31305. var color = image[imageOffset + j];
  31306. var maskOffset = j * 2;
  31307. if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
  31308. opacity = 255;
  31309. break;
  31310. }
  31311. }
  31312. alphaBuf[i] = opacity;
  31313. }
  31314. } else {
  31315. error('Unknown mask format.');
  31316. }
  31317. }
  31318. if (alphaBuf) {
  31319. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  31320. rgbaBuf[j] = alphaBuf[i];
  31321. }
  31322. } else {
  31323. // No mask.
  31324. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  31325. rgbaBuf[j] = 255;
  31326. }
  31327. }
  31328. },
  31329. undoPreblend: function PDFImage_undoPreblend(buffer, width, height) {
  31330. var matte = this.smask && this.smask.matte;
  31331. if (!matte) {
  31332. return;
  31333. }
  31334. var matteRgb = this.colorSpace.getRgb(matte, 0);
  31335. var matteR = matteRgb[0];
  31336. var matteG = matteRgb[1];
  31337. var matteB = matteRgb[2];
  31338. var length = width * height * 4;
  31339. var r, g, b;
  31340. for (var i = 0; i < length; i += 4) {
  31341. var alpha = buffer[i + 3];
  31342. if (alpha === 0) {
  31343. // according formula we have to get Infinity in all components
  31344. // making it white (typical paper color) should be okay
  31345. buffer[i] = 255;
  31346. buffer[i + 1] = 255;
  31347. buffer[i + 2] = 255;
  31348. continue;
  31349. }
  31350. var k = 255 / alpha;
  31351. r = (buffer[i] - matteR) * k + matteR;
  31352. g = (buffer[i + 1] - matteG) * k + matteG;
  31353. b = (buffer[i + 2] - matteB) * k + matteB;
  31354. buffer[i] = r <= 0 ? 0 : r >= 255 ? 255 : r | 0;
  31355. buffer[i + 1] = g <= 0 ? 0 : g >= 255 ? 255 : g | 0;
  31356. buffer[i + 2] = b <= 0 ? 0 : b >= 255 ? 255 : b | 0;
  31357. }
  31358. },
  31359. createImageData: function PDFImage_createImageData(forceRGBA) {
  31360. var drawWidth = this.drawWidth;
  31361. var drawHeight = this.drawHeight;
  31362. var imgData = { // other fields are filled in below
  31363. width: drawWidth,
  31364. height: drawHeight
  31365. };
  31366. var numComps = this.numComps;
  31367. var originalWidth = this.width;
  31368. var originalHeight = this.height;
  31369. var bpc = this.bpc;
  31370. // Rows start at byte boundary.
  31371. var rowBytes = (originalWidth * numComps * bpc + 7) >> 3;
  31372. var imgArray;
  31373. if (!forceRGBA) {
  31374. // If it is a 1-bit-per-pixel grayscale (i.e. black-and-white) image
  31375. // without any complications, we pass a same-sized copy to the main
  31376. // thread rather than expanding by 32x to RGBA form. This saves *lots*
  31377. // of memory for many scanned documents. It's also much faster.
  31378. //
  31379. // Similarly, if it is a 24-bit-per pixel RGB image without any
  31380. // complications, we avoid expanding by 1.333x to RGBA form.
  31381. var kind;
  31382. if (this.colorSpace.name === 'DeviceGray' && bpc === 1) {
  31383. kind = ImageKind.GRAYSCALE_1BPP;
  31384. } else if (this.colorSpace.name === 'DeviceRGB' && bpc === 8 &&
  31385. !this.needsDecode) {
  31386. kind = ImageKind.RGB_24BPP;
  31387. }
  31388. if (kind && !this.smask && !this.mask &&
  31389. drawWidth === originalWidth && drawHeight === originalHeight) {
  31390. imgData.kind = kind;
  31391. imgArray = this.getImageBytes(originalHeight * rowBytes);
  31392. // If imgArray came from a DecodeStream, we're safe to transfer it
  31393. // (and thus neuter it) because it will constitute the entire
  31394. // DecodeStream's data. But if it came from a Stream, we need to
  31395. // copy it because it'll only be a portion of the Stream's data, and
  31396. // the rest will be read later on.
  31397. if (this.image instanceof DecodeStream) {
  31398. imgData.data = imgArray;
  31399. } else {
  31400. var newArray = new Uint8Array(imgArray.length);
  31401. newArray.set(imgArray);
  31402. imgData.data = newArray;
  31403. }
  31404. if (this.needsDecode) {
  31405. // Invert the buffer (which must be grayscale if we reached here).
  31406. assert(kind === ImageKind.GRAYSCALE_1BPP);
  31407. var buffer = imgData.data;
  31408. for (var i = 0, ii = buffer.length; i < ii; i++) {
  31409. buffer[i] ^= 0xff;
  31410. }
  31411. }
  31412. return imgData;
  31413. }
  31414. if (this.image instanceof JpegStream && !this.smask && !this.mask &&
  31415. (this.colorSpace.name === 'DeviceGray' ||
  31416. this.colorSpace.name === 'DeviceRGB' ||
  31417. this.colorSpace.name === 'DeviceCMYK')) {
  31418. imgData.kind = ImageKind.RGB_24BPP;
  31419. imgData.data = this.getImageBytes(originalHeight * rowBytes,
  31420. drawWidth, drawHeight, true);
  31421. return imgData;
  31422. }
  31423. }
  31424. imgArray = this.getImageBytes(originalHeight * rowBytes);
  31425. // imgArray can be incomplete (e.g. after CCITT fax encoding).
  31426. var actualHeight = 0 | (imgArray.length / rowBytes *
  31427. drawHeight / originalHeight);
  31428. var comps = this.getComponents(imgArray);
  31429. // If opacity data is present, use RGBA_32BPP form. Otherwise, use the
  31430. // more compact RGB_24BPP form if allowable.
  31431. var alpha01, maybeUndoPreblend;
  31432. if (!forceRGBA && !this.smask && !this.mask) {
  31433. imgData.kind = ImageKind.RGB_24BPP;
  31434. imgData.data = new Uint8Array(drawWidth * drawHeight * 3);
  31435. alpha01 = 0;
  31436. maybeUndoPreblend = false;
  31437. } else {
  31438. imgData.kind = ImageKind.RGBA_32BPP;
  31439. imgData.data = new Uint8Array(drawWidth * drawHeight * 4);
  31440. alpha01 = 1;
  31441. maybeUndoPreblend = true;
  31442. // Color key masking (opacity) must be performed before decoding.
  31443. this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight,
  31444. comps);
  31445. }
  31446. if (this.needsDecode) {
  31447. this.decodeBuffer(comps);
  31448. }
  31449. this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight,
  31450. drawWidth, drawHeight, actualHeight, bpc, comps,
  31451. alpha01);
  31452. if (maybeUndoPreblend) {
  31453. this.undoPreblend(imgData.data, drawWidth, actualHeight);
  31454. }
  31455. return imgData;
  31456. },
  31457. fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) {
  31458. var numComps = this.numComps;
  31459. if (numComps !== 1) {
  31460. error('Reading gray scale from a color image: ' + numComps);
  31461. }
  31462. var width = this.width;
  31463. var height = this.height;
  31464. var bpc = this.bpc;
  31465. // rows start at byte boundary
  31466. var rowBytes = (width * numComps * bpc + 7) >> 3;
  31467. var imgArray = this.getImageBytes(height * rowBytes);
  31468. var comps = this.getComponents(imgArray);
  31469. var i, length;
  31470. if (bpc === 1) {
  31471. // inline decoding (= inversion) for 1 bpc images
  31472. length = width * height;
  31473. if (this.needsDecode) {
  31474. // invert and scale to {0, 255}
  31475. for (i = 0; i < length; ++i) {
  31476. buffer[i] = (comps[i] - 1) & 255;
  31477. }
  31478. } else {
  31479. // scale to {0, 255}
  31480. for (i = 0; i < length; ++i) {
  31481. buffer[i] = (-comps[i]) & 255;
  31482. }
  31483. }
  31484. return;
  31485. }
  31486. if (this.needsDecode) {
  31487. this.decodeBuffer(comps);
  31488. }
  31489. length = width * height;
  31490. // we aren't using a colorspace so we need to scale the value
  31491. var scale = 255 / ((1 << bpc) - 1);
  31492. for (i = 0; i < length; ++i) {
  31493. buffer[i] = (scale * comps[i]) | 0;
  31494. }
  31495. },
  31496. getImageBytes: function PDFImage_getImageBytes(length,
  31497. drawWidth, drawHeight,
  31498. forceRGB) {
  31499. this.image.reset();
  31500. this.image.drawWidth = drawWidth || this.width;
  31501. this.image.drawHeight = drawHeight || this.height;
  31502. this.image.forceRGB = !!forceRGB;
  31503. return this.image.getBytes(length);
  31504. }
  31505. };
  31506. return PDFImage;
  31507. })();
  31508. // The Metrics object contains glyph widths (in glyph space units).
  31509. // As per PDF spec, for most fonts (Type 3 being an exception) a glyph
  31510. // space unit corresponds to 1/1000th of text space unit.
  31511. var Metrics = {
  31512. 'Courier': 600,
  31513. 'Courier-Bold': 600,
  31514. 'Courier-BoldOblique': 600,
  31515. 'Courier-Oblique': 600,
  31516. 'Helvetica' : {
  31517. 'space': 278,
  31518. 'exclam': 278,
  31519. 'quotedbl': 355,
  31520. 'numbersign': 556,
  31521. 'dollar': 556,
  31522. 'percent': 889,
  31523. 'ampersand': 667,
  31524. 'quoteright': 222,
  31525. 'parenleft': 333,
  31526. 'parenright': 333,
  31527. 'asterisk': 389,
  31528. 'plus': 584,
  31529. 'comma': 278,
  31530. 'hyphen': 333,
  31531. 'period': 278,
  31532. 'slash': 278,
  31533. 'zero': 556,
  31534. 'one': 556,
  31535. 'two': 556,
  31536. 'three': 556,
  31537. 'four': 556,
  31538. 'five': 556,
  31539. 'six': 556,
  31540. 'seven': 556,
  31541. 'eight': 556,
  31542. 'nine': 556,
  31543. 'colon': 278,
  31544. 'semicolon': 278,
  31545. 'less': 584,
  31546. 'equal': 584,
  31547. 'greater': 584,
  31548. 'question': 556,
  31549. 'at': 1015,
  31550. 'A': 667,
  31551. 'B': 667,
  31552. 'C': 722,
  31553. 'D': 722,
  31554. 'E': 667,
  31555. 'F': 611,
  31556. 'G': 778,
  31557. 'H': 722,
  31558. 'I': 278,
  31559. 'J': 500,
  31560. 'K': 667,
  31561. 'L': 556,
  31562. 'M': 833,
  31563. 'N': 722,
  31564. 'O': 778,
  31565. 'P': 667,
  31566. 'Q': 778,
  31567. 'R': 722,
  31568. 'S': 667,
  31569. 'T': 611,
  31570. 'U': 722,
  31571. 'V': 667,
  31572. 'W': 944,
  31573. 'X': 667,
  31574. 'Y': 667,
  31575. 'Z': 611,
  31576. 'bracketleft': 278,
  31577. 'backslash': 278,
  31578. 'bracketright': 278,
  31579. 'asciicircum': 469,
  31580. 'underscore': 556,
  31581. 'quoteleft': 222,
  31582. 'a': 556,
  31583. 'b': 556,
  31584. 'c': 500,
  31585. 'd': 556,
  31586. 'e': 556,
  31587. 'f': 278,
  31588. 'g': 556,
  31589. 'h': 556,
  31590. 'i': 222,
  31591. 'j': 222,
  31592. 'k': 500,
  31593. 'l': 222,
  31594. 'm': 833,
  31595. 'n': 556,
  31596. 'o': 556,
  31597. 'p': 556,
  31598. 'q': 556,
  31599. 'r': 333,
  31600. 's': 500,
  31601. 't': 278,
  31602. 'u': 556,
  31603. 'v': 500,
  31604. 'w': 722,
  31605. 'x': 500,
  31606. 'y': 500,
  31607. 'z': 500,
  31608. 'braceleft': 334,
  31609. 'bar': 260,
  31610. 'braceright': 334,
  31611. 'asciitilde': 584,
  31612. 'exclamdown': 333,
  31613. 'cent': 556,
  31614. 'sterling': 556,
  31615. 'fraction': 167,
  31616. 'yen': 556,
  31617. 'florin': 556,
  31618. 'section': 556,
  31619. 'currency': 556,
  31620. 'quotesingle': 191,
  31621. 'quotedblleft': 333,
  31622. 'guillemotleft': 556,
  31623. 'guilsinglleft': 333,
  31624. 'guilsinglright': 333,
  31625. 'fi': 500,
  31626. 'fl': 500,
  31627. 'endash': 556,
  31628. 'dagger': 556,
  31629. 'daggerdbl': 556,
  31630. 'periodcentered': 278,
  31631. 'paragraph': 537,
  31632. 'bullet': 350,
  31633. 'quotesinglbase': 222,
  31634. 'quotedblbase': 333,
  31635. 'quotedblright': 333,
  31636. 'guillemotright': 556,
  31637. 'ellipsis': 1000,
  31638. 'perthousand': 1000,
  31639. 'questiondown': 611,
  31640. 'grave': 333,
  31641. 'acute': 333,
  31642. 'circumflex': 333,
  31643. 'tilde': 333,
  31644. 'macron': 333,
  31645. 'breve': 333,
  31646. 'dotaccent': 333,
  31647. 'dieresis': 333,
  31648. 'ring': 333,
  31649. 'cedilla': 333,
  31650. 'hungarumlaut': 333,
  31651. 'ogonek': 333,
  31652. 'caron': 333,
  31653. 'emdash': 1000,
  31654. 'AE': 1000,
  31655. 'ordfeminine': 370,
  31656. 'Lslash': 556,
  31657. 'Oslash': 778,
  31658. 'OE': 1000,
  31659. 'ordmasculine': 365,
  31660. 'ae': 889,
  31661. 'dotlessi': 278,
  31662. 'lslash': 222,
  31663. 'oslash': 611,
  31664. 'oe': 944,
  31665. 'germandbls': 611,
  31666. 'Idieresis': 278,
  31667. 'eacute': 556,
  31668. 'abreve': 556,
  31669. 'uhungarumlaut': 556,
  31670. 'ecaron': 556,
  31671. 'Ydieresis': 667,
  31672. 'divide': 584,
  31673. 'Yacute': 667,
  31674. 'Acircumflex': 667,
  31675. 'aacute': 556,
  31676. 'Ucircumflex': 722,
  31677. 'yacute': 500,
  31678. 'scommaaccent': 500,
  31679. 'ecircumflex': 556,
  31680. 'Uring': 722,
  31681. 'Udieresis': 722,
  31682. 'aogonek': 556,
  31683. 'Uacute': 722,
  31684. 'uogonek': 556,
  31685. 'Edieresis': 667,
  31686. 'Dcroat': 722,
  31687. 'commaaccent': 250,
  31688. 'copyright': 737,
  31689. 'Emacron': 667,
  31690. 'ccaron': 500,
  31691. 'aring': 556,
  31692. 'Ncommaaccent': 722,
  31693. 'lacute': 222,
  31694. 'agrave': 556,
  31695. 'Tcommaaccent': 611,
  31696. 'Cacute': 722,
  31697. 'atilde': 556,
  31698. 'Edotaccent': 667,
  31699. 'scaron': 500,
  31700. 'scedilla': 500,
  31701. 'iacute': 278,
  31702. 'lozenge': 471,
  31703. 'Rcaron': 722,
  31704. 'Gcommaaccent': 778,
  31705. 'ucircumflex': 556,
  31706. 'acircumflex': 556,
  31707. 'Amacron': 667,
  31708. 'rcaron': 333,
  31709. 'ccedilla': 500,
  31710. 'Zdotaccent': 611,
  31711. 'Thorn': 667,
  31712. 'Omacron': 778,
  31713. 'Racute': 722,
  31714. 'Sacute': 667,
  31715. 'dcaron': 643,
  31716. 'Umacron': 722,
  31717. 'uring': 556,
  31718. 'threesuperior': 333,
  31719. 'Ograve': 778,
  31720. 'Agrave': 667,
  31721. 'Abreve': 667,
  31722. 'multiply': 584,
  31723. 'uacute': 556,
  31724. 'Tcaron': 611,
  31725. 'partialdiff': 476,
  31726. 'ydieresis': 500,
  31727. 'Nacute': 722,
  31728. 'icircumflex': 278,
  31729. 'Ecircumflex': 667,
  31730. 'adieresis': 556,
  31731. 'edieresis': 556,
  31732. 'cacute': 500,
  31733. 'nacute': 556,
  31734. 'umacron': 556,
  31735. 'Ncaron': 722,
  31736. 'Iacute': 278,
  31737. 'plusminus': 584,
  31738. 'brokenbar': 260,
  31739. 'registered': 737,
  31740. 'Gbreve': 778,
  31741. 'Idotaccent': 278,
  31742. 'summation': 600,
  31743. 'Egrave': 667,
  31744. 'racute': 333,
  31745. 'omacron': 556,
  31746. 'Zacute': 611,
  31747. 'Zcaron': 611,
  31748. 'greaterequal': 549,
  31749. 'Eth': 722,
  31750. 'Ccedilla': 722,
  31751. 'lcommaaccent': 222,
  31752. 'tcaron': 317,
  31753. 'eogonek': 556,
  31754. 'Uogonek': 722,
  31755. 'Aacute': 667,
  31756. 'Adieresis': 667,
  31757. 'egrave': 556,
  31758. 'zacute': 500,
  31759. 'iogonek': 222,
  31760. 'Oacute': 778,
  31761. 'oacute': 556,
  31762. 'amacron': 556,
  31763. 'sacute': 500,
  31764. 'idieresis': 278,
  31765. 'Ocircumflex': 778,
  31766. 'Ugrave': 722,
  31767. 'Delta': 612,
  31768. 'thorn': 556,
  31769. 'twosuperior': 333,
  31770. 'Odieresis': 778,
  31771. 'mu': 556,
  31772. 'igrave': 278,
  31773. 'ohungarumlaut': 556,
  31774. 'Eogonek': 667,
  31775. 'dcroat': 556,
  31776. 'threequarters': 834,
  31777. 'Scedilla': 667,
  31778. 'lcaron': 299,
  31779. 'Kcommaaccent': 667,
  31780. 'Lacute': 556,
  31781. 'trademark': 1000,
  31782. 'edotaccent': 556,
  31783. 'Igrave': 278,
  31784. 'Imacron': 278,
  31785. 'Lcaron': 556,
  31786. 'onehalf': 834,
  31787. 'lessequal': 549,
  31788. 'ocircumflex': 556,
  31789. 'ntilde': 556,
  31790. 'Uhungarumlaut': 722,
  31791. 'Eacute': 667,
  31792. 'emacron': 556,
  31793. 'gbreve': 556,
  31794. 'onequarter': 834,
  31795. 'Scaron': 667,
  31796. 'Scommaaccent': 667,
  31797. 'Ohungarumlaut': 778,
  31798. 'degree': 400,
  31799. 'ograve': 556,
  31800. 'Ccaron': 722,
  31801. 'ugrave': 556,
  31802. 'radical': 453,
  31803. 'Dcaron': 722,
  31804. 'rcommaaccent': 333,
  31805. 'Ntilde': 722,
  31806. 'otilde': 556,
  31807. 'Rcommaaccent': 722,
  31808. 'Lcommaaccent': 556,
  31809. 'Atilde': 667,
  31810. 'Aogonek': 667,
  31811. 'Aring': 667,
  31812. 'Otilde': 778,
  31813. 'zdotaccent': 500,
  31814. 'Ecaron': 667,
  31815. 'Iogonek': 278,
  31816. 'kcommaaccent': 500,
  31817. 'minus': 584,
  31818. 'Icircumflex': 278,
  31819. 'ncaron': 556,
  31820. 'tcommaaccent': 278,
  31821. 'logicalnot': 584,
  31822. 'odieresis': 556,
  31823. 'udieresis': 556,
  31824. 'notequal': 549,
  31825. 'gcommaaccent': 556,
  31826. 'eth': 556,
  31827. 'zcaron': 500,
  31828. 'ncommaaccent': 556,
  31829. 'onesuperior': 333,
  31830. 'imacron': 278,
  31831. 'Euro': 556
  31832. },
  31833. 'Helvetica-Bold': {
  31834. 'space': 278,
  31835. 'exclam': 333,
  31836. 'quotedbl': 474,
  31837. 'numbersign': 556,
  31838. 'dollar': 556,
  31839. 'percent': 889,
  31840. 'ampersand': 722,
  31841. 'quoteright': 278,
  31842. 'parenleft': 333,
  31843. 'parenright': 333,
  31844. 'asterisk': 389,
  31845. 'plus': 584,
  31846. 'comma': 278,
  31847. 'hyphen': 333,
  31848. 'period': 278,
  31849. 'slash': 278,
  31850. 'zero': 556,
  31851. 'one': 556,
  31852. 'two': 556,
  31853. 'three': 556,
  31854. 'four': 556,
  31855. 'five': 556,
  31856. 'six': 556,
  31857. 'seven': 556,
  31858. 'eight': 556,
  31859. 'nine': 556,
  31860. 'colon': 333,
  31861. 'semicolon': 333,
  31862. 'less': 584,
  31863. 'equal': 584,
  31864. 'greater': 584,
  31865. 'question': 611,
  31866. 'at': 975,
  31867. 'A': 722,
  31868. 'B': 722,
  31869. 'C': 722,
  31870. 'D': 722,
  31871. 'E': 667,
  31872. 'F': 611,
  31873. 'G': 778,
  31874. 'H': 722,
  31875. 'I': 278,
  31876. 'J': 556,
  31877. 'K': 722,
  31878. 'L': 611,
  31879. 'M': 833,
  31880. 'N': 722,
  31881. 'O': 778,
  31882. 'P': 667,
  31883. 'Q': 778,
  31884. 'R': 722,
  31885. 'S': 667,
  31886. 'T': 611,
  31887. 'U': 722,
  31888. 'V': 667,
  31889. 'W': 944,
  31890. 'X': 667,
  31891. 'Y': 667,
  31892. 'Z': 611,
  31893. 'bracketleft': 333,
  31894. 'backslash': 278,
  31895. 'bracketright': 333,
  31896. 'asciicircum': 584,
  31897. 'underscore': 556,
  31898. 'quoteleft': 278,
  31899. 'a': 556,
  31900. 'b': 611,
  31901. 'c': 556,
  31902. 'd': 611,
  31903. 'e': 556,
  31904. 'f': 333,
  31905. 'g': 611,
  31906. 'h': 611,
  31907. 'i': 278,
  31908. 'j': 278,
  31909. 'k': 556,
  31910. 'l': 278,
  31911. 'm': 889,
  31912. 'n': 611,
  31913. 'o': 611,
  31914. 'p': 611,
  31915. 'q': 611,
  31916. 'r': 389,
  31917. 's': 556,
  31918. 't': 333,
  31919. 'u': 611,
  31920. 'v': 556,
  31921. 'w': 778,
  31922. 'x': 556,
  31923. 'y': 556,
  31924. 'z': 500,
  31925. 'braceleft': 389,
  31926. 'bar': 280,
  31927. 'braceright': 389,
  31928. 'asciitilde': 584,
  31929. 'exclamdown': 333,
  31930. 'cent': 556,
  31931. 'sterling': 556,
  31932. 'fraction': 167,
  31933. 'yen': 556,
  31934. 'florin': 556,
  31935. 'section': 556,
  31936. 'currency': 556,
  31937. 'quotesingle': 238,
  31938. 'quotedblleft': 500,
  31939. 'guillemotleft': 556,
  31940. 'guilsinglleft': 333,
  31941. 'guilsinglright': 333,
  31942. 'fi': 611,
  31943. 'fl': 611,
  31944. 'endash': 556,
  31945. 'dagger': 556,
  31946. 'daggerdbl': 556,
  31947. 'periodcentered': 278,
  31948. 'paragraph': 556,
  31949. 'bullet': 350,
  31950. 'quotesinglbase': 278,
  31951. 'quotedblbase': 500,
  31952. 'quotedblright': 500,
  31953. 'guillemotright': 556,
  31954. 'ellipsis': 1000,
  31955. 'perthousand': 1000,
  31956. 'questiondown': 611,
  31957. 'grave': 333,
  31958. 'acute': 333,
  31959. 'circumflex': 333,
  31960. 'tilde': 333,
  31961. 'macron': 333,
  31962. 'breve': 333,
  31963. 'dotaccent': 333,
  31964. 'dieresis': 333,
  31965. 'ring': 333,
  31966. 'cedilla': 333,
  31967. 'hungarumlaut': 333,
  31968. 'ogonek': 333,
  31969. 'caron': 333,
  31970. 'emdash': 1000,
  31971. 'AE': 1000,
  31972. 'ordfeminine': 370,
  31973. 'Lslash': 611,
  31974. 'Oslash': 778,
  31975. 'OE': 1000,
  31976. 'ordmasculine': 365,
  31977. 'ae': 889,
  31978. 'dotlessi': 278,
  31979. 'lslash': 278,
  31980. 'oslash': 611,
  31981. 'oe': 944,
  31982. 'germandbls': 611,
  31983. 'Idieresis': 278,
  31984. 'eacute': 556,
  31985. 'abreve': 556,
  31986. 'uhungarumlaut': 611,
  31987. 'ecaron': 556,
  31988. 'Ydieresis': 667,
  31989. 'divide': 584,
  31990. 'Yacute': 667,
  31991. 'Acircumflex': 722,
  31992. 'aacute': 556,
  31993. 'Ucircumflex': 722,
  31994. 'yacute': 556,
  31995. 'scommaaccent': 556,
  31996. 'ecircumflex': 556,
  31997. 'Uring': 722,
  31998. 'Udieresis': 722,
  31999. 'aogonek': 556,
  32000. 'Uacute': 722,
  32001. 'uogonek': 611,
  32002. 'Edieresis': 667,
  32003. 'Dcroat': 722,
  32004. 'commaaccent': 250,
  32005. 'copyright': 737,
  32006. 'Emacron': 667,
  32007. 'ccaron': 556,
  32008. 'aring': 556,
  32009. 'Ncommaaccent': 722,
  32010. 'lacute': 278,
  32011. 'agrave': 556,
  32012. 'Tcommaaccent': 611,
  32013. 'Cacute': 722,
  32014. 'atilde': 556,
  32015. 'Edotaccent': 667,
  32016. 'scaron': 556,
  32017. 'scedilla': 556,
  32018. 'iacute': 278,
  32019. 'lozenge': 494,
  32020. 'Rcaron': 722,
  32021. 'Gcommaaccent': 778,
  32022. 'ucircumflex': 611,
  32023. 'acircumflex': 556,
  32024. 'Amacron': 722,
  32025. 'rcaron': 389,
  32026. 'ccedilla': 556,
  32027. 'Zdotaccent': 611,
  32028. 'Thorn': 667,
  32029. 'Omacron': 778,
  32030. 'Racute': 722,
  32031. 'Sacute': 667,
  32032. 'dcaron': 743,
  32033. 'Umacron': 722,
  32034. 'uring': 611,
  32035. 'threesuperior': 333,
  32036. 'Ograve': 778,
  32037. 'Agrave': 722,
  32038. 'Abreve': 722,
  32039. 'multiply': 584,
  32040. 'uacute': 611,
  32041. 'Tcaron': 611,
  32042. 'partialdiff': 494,
  32043. 'ydieresis': 556,
  32044. 'Nacute': 722,
  32045. 'icircumflex': 278,
  32046. 'Ecircumflex': 667,
  32047. 'adieresis': 556,
  32048. 'edieresis': 556,
  32049. 'cacute': 556,
  32050. 'nacute': 611,
  32051. 'umacron': 611,
  32052. 'Ncaron': 722,
  32053. 'Iacute': 278,
  32054. 'plusminus': 584,
  32055. 'brokenbar': 280,
  32056. 'registered': 737,
  32057. 'Gbreve': 778,
  32058. 'Idotaccent': 278,
  32059. 'summation': 600,
  32060. 'Egrave': 667,
  32061. 'racute': 389,
  32062. 'omacron': 611,
  32063. 'Zacute': 611,
  32064. 'Zcaron': 611,
  32065. 'greaterequal': 549,
  32066. 'Eth': 722,
  32067. 'Ccedilla': 722,
  32068. 'lcommaaccent': 278,
  32069. 'tcaron': 389,
  32070. 'eogonek': 556,
  32071. 'Uogonek': 722,
  32072. 'Aacute': 722,
  32073. 'Adieresis': 722,
  32074. 'egrave': 556,
  32075. 'zacute': 500,
  32076. 'iogonek': 278,
  32077. 'Oacute': 778,
  32078. 'oacute': 611,
  32079. 'amacron': 556,
  32080. 'sacute': 556,
  32081. 'idieresis': 278,
  32082. 'Ocircumflex': 778,
  32083. 'Ugrave': 722,
  32084. 'Delta': 612,
  32085. 'thorn': 611,
  32086. 'twosuperior': 333,
  32087. 'Odieresis': 778,
  32088. 'mu': 611,
  32089. 'igrave': 278,
  32090. 'ohungarumlaut': 611,
  32091. 'Eogonek': 667,
  32092. 'dcroat': 611,
  32093. 'threequarters': 834,
  32094. 'Scedilla': 667,
  32095. 'lcaron': 400,
  32096. 'Kcommaaccent': 722,
  32097. 'Lacute': 611,
  32098. 'trademark': 1000,
  32099. 'edotaccent': 556,
  32100. 'Igrave': 278,
  32101. 'Imacron': 278,
  32102. 'Lcaron': 611,
  32103. 'onehalf': 834,
  32104. 'lessequal': 549,
  32105. 'ocircumflex': 611,
  32106. 'ntilde': 611,
  32107. 'Uhungarumlaut': 722,
  32108. 'Eacute': 667,
  32109. 'emacron': 556,
  32110. 'gbreve': 611,
  32111. 'onequarter': 834,
  32112. 'Scaron': 667,
  32113. 'Scommaaccent': 667,
  32114. 'Ohungarumlaut': 778,
  32115. 'degree': 400,
  32116. 'ograve': 611,
  32117. 'Ccaron': 722,
  32118. 'ugrave': 611,
  32119. 'radical': 549,
  32120. 'Dcaron': 722,
  32121. 'rcommaaccent': 389,
  32122. 'Ntilde': 722,
  32123. 'otilde': 611,
  32124. 'Rcommaaccent': 722,
  32125. 'Lcommaaccent': 611,
  32126. 'Atilde': 722,
  32127. 'Aogonek': 722,
  32128. 'Aring': 722,
  32129. 'Otilde': 778,
  32130. 'zdotaccent': 500,
  32131. 'Ecaron': 667,
  32132. 'Iogonek': 278,
  32133. 'kcommaaccent': 556,
  32134. 'minus': 584,
  32135. 'Icircumflex': 278,
  32136. 'ncaron': 611,
  32137. 'tcommaaccent': 333,
  32138. 'logicalnot': 584,
  32139. 'odieresis': 611,
  32140. 'udieresis': 611,
  32141. 'notequal': 549,
  32142. 'gcommaaccent': 611,
  32143. 'eth': 611,
  32144. 'zcaron': 500,
  32145. 'ncommaaccent': 611,
  32146. 'onesuperior': 333,
  32147. 'imacron': 278,
  32148. 'Euro': 556
  32149. },
  32150. 'Helvetica-BoldOblique': {
  32151. 'space': 278,
  32152. 'exclam': 333,
  32153. 'quotedbl': 474,
  32154. 'numbersign': 556,
  32155. 'dollar': 556,
  32156. 'percent': 889,
  32157. 'ampersand': 722,
  32158. 'quoteright': 278,
  32159. 'parenleft': 333,
  32160. 'parenright': 333,
  32161. 'asterisk': 389,
  32162. 'plus': 584,
  32163. 'comma': 278,
  32164. 'hyphen': 333,
  32165. 'period': 278,
  32166. 'slash': 278,
  32167. 'zero': 556,
  32168. 'one': 556,
  32169. 'two': 556,
  32170. 'three': 556,
  32171. 'four': 556,
  32172. 'five': 556,
  32173. 'six': 556,
  32174. 'seven': 556,
  32175. 'eight': 556,
  32176. 'nine': 556,
  32177. 'colon': 333,
  32178. 'semicolon': 333,
  32179. 'less': 584,
  32180. 'equal': 584,
  32181. 'greater': 584,
  32182. 'question': 611,
  32183. 'at': 975,
  32184. 'A': 722,
  32185. 'B': 722,
  32186. 'C': 722,
  32187. 'D': 722,
  32188. 'E': 667,
  32189. 'F': 611,
  32190. 'G': 778,
  32191. 'H': 722,
  32192. 'I': 278,
  32193. 'J': 556,
  32194. 'K': 722,
  32195. 'L': 611,
  32196. 'M': 833,
  32197. 'N': 722,
  32198. 'O': 778,
  32199. 'P': 667,
  32200. 'Q': 778,
  32201. 'R': 722,
  32202. 'S': 667,
  32203. 'T': 611,
  32204. 'U': 722,
  32205. 'V': 667,
  32206. 'W': 944,
  32207. 'X': 667,
  32208. 'Y': 667,
  32209. 'Z': 611,
  32210. 'bracketleft': 333,
  32211. 'backslash': 278,
  32212. 'bracketright': 333,
  32213. 'asciicircum': 584,
  32214. 'underscore': 556,
  32215. 'quoteleft': 278,
  32216. 'a': 556,
  32217. 'b': 611,
  32218. 'c': 556,
  32219. 'd': 611,
  32220. 'e': 556,
  32221. 'f': 333,
  32222. 'g': 611,
  32223. 'h': 611,
  32224. 'i': 278,
  32225. 'j': 278,
  32226. 'k': 556,
  32227. 'l': 278,
  32228. 'm': 889,
  32229. 'n': 611,
  32230. 'o': 611,
  32231. 'p': 611,
  32232. 'q': 611,
  32233. 'r': 389,
  32234. 's': 556,
  32235. 't': 333,
  32236. 'u': 611,
  32237. 'v': 556,
  32238. 'w': 778,
  32239. 'x': 556,
  32240. 'y': 556,
  32241. 'z': 500,
  32242. 'braceleft': 389,
  32243. 'bar': 280,
  32244. 'braceright': 389,
  32245. 'asciitilde': 584,
  32246. 'exclamdown': 333,
  32247. 'cent': 556,
  32248. 'sterling': 556,
  32249. 'fraction': 167,
  32250. 'yen': 556,
  32251. 'florin': 556,
  32252. 'section': 556,
  32253. 'currency': 556,
  32254. 'quotesingle': 238,
  32255. 'quotedblleft': 500,
  32256. 'guillemotleft': 556,
  32257. 'guilsinglleft': 333,
  32258. 'guilsinglright': 333,
  32259. 'fi': 611,
  32260. 'fl': 611,
  32261. 'endash': 556,
  32262. 'dagger': 556,
  32263. 'daggerdbl': 556,
  32264. 'periodcentered': 278,
  32265. 'paragraph': 556,
  32266. 'bullet': 350,
  32267. 'quotesinglbase': 278,
  32268. 'quotedblbase': 500,
  32269. 'quotedblright': 500,
  32270. 'guillemotright': 556,
  32271. 'ellipsis': 1000,
  32272. 'perthousand': 1000,
  32273. 'questiondown': 611,
  32274. 'grave': 333,
  32275. 'acute': 333,
  32276. 'circumflex': 333,
  32277. 'tilde': 333,
  32278. 'macron': 333,
  32279. 'breve': 333,
  32280. 'dotaccent': 333,
  32281. 'dieresis': 333,
  32282. 'ring': 333,
  32283. 'cedilla': 333,
  32284. 'hungarumlaut': 333,
  32285. 'ogonek': 333,
  32286. 'caron': 333,
  32287. 'emdash': 1000,
  32288. 'AE': 1000,
  32289. 'ordfeminine': 370,
  32290. 'Lslash': 611,
  32291. 'Oslash': 778,
  32292. 'OE': 1000,
  32293. 'ordmasculine': 365,
  32294. 'ae': 889,
  32295. 'dotlessi': 278,
  32296. 'lslash': 278,
  32297. 'oslash': 611,
  32298. 'oe': 944,
  32299. 'germandbls': 611,
  32300. 'Idieresis': 278,
  32301. 'eacute': 556,
  32302. 'abreve': 556,
  32303. 'uhungarumlaut': 611,
  32304. 'ecaron': 556,
  32305. 'Ydieresis': 667,
  32306. 'divide': 584,
  32307. 'Yacute': 667,
  32308. 'Acircumflex': 722,
  32309. 'aacute': 556,
  32310. 'Ucircumflex': 722,
  32311. 'yacute': 556,
  32312. 'scommaaccent': 556,
  32313. 'ecircumflex': 556,
  32314. 'Uring': 722,
  32315. 'Udieresis': 722,
  32316. 'aogonek': 556,
  32317. 'Uacute': 722,
  32318. 'uogonek': 611,
  32319. 'Edieresis': 667,
  32320. 'Dcroat': 722,
  32321. 'commaaccent': 250,
  32322. 'copyright': 737,
  32323. 'Emacron': 667,
  32324. 'ccaron': 556,
  32325. 'aring': 556,
  32326. 'Ncommaaccent': 722,
  32327. 'lacute': 278,
  32328. 'agrave': 556,
  32329. 'Tcommaaccent': 611,
  32330. 'Cacute': 722,
  32331. 'atilde': 556,
  32332. 'Edotaccent': 667,
  32333. 'scaron': 556,
  32334. 'scedilla': 556,
  32335. 'iacute': 278,
  32336. 'lozenge': 494,
  32337. 'Rcaron': 722,
  32338. 'Gcommaaccent': 778,
  32339. 'ucircumflex': 611,
  32340. 'acircumflex': 556,
  32341. 'Amacron': 722,
  32342. 'rcaron': 389,
  32343. 'ccedilla': 556,
  32344. 'Zdotaccent': 611,
  32345. 'Thorn': 667,
  32346. 'Omacron': 778,
  32347. 'Racute': 722,
  32348. 'Sacute': 667,
  32349. 'dcaron': 743,
  32350. 'Umacron': 722,
  32351. 'uring': 611,
  32352. 'threesuperior': 333,
  32353. 'Ograve': 778,
  32354. 'Agrave': 722,
  32355. 'Abreve': 722,
  32356. 'multiply': 584,
  32357. 'uacute': 611,
  32358. 'Tcaron': 611,
  32359. 'partialdiff': 494,
  32360. 'ydieresis': 556,
  32361. 'Nacute': 722,
  32362. 'icircumflex': 278,
  32363. 'Ecircumflex': 667,
  32364. 'adieresis': 556,
  32365. 'edieresis': 556,
  32366. 'cacute': 556,
  32367. 'nacute': 611,
  32368. 'umacron': 611,
  32369. 'Ncaron': 722,
  32370. 'Iacute': 278,
  32371. 'plusminus': 584,
  32372. 'brokenbar': 280,
  32373. 'registered': 737,
  32374. 'Gbreve': 778,
  32375. 'Idotaccent': 278,
  32376. 'summation': 600,
  32377. 'Egrave': 667,
  32378. 'racute': 389,
  32379. 'omacron': 611,
  32380. 'Zacute': 611,
  32381. 'Zcaron': 611,
  32382. 'greaterequal': 549,
  32383. 'Eth': 722,
  32384. 'Ccedilla': 722,
  32385. 'lcommaaccent': 278,
  32386. 'tcaron': 389,
  32387. 'eogonek': 556,
  32388. 'Uogonek': 722,
  32389. 'Aacute': 722,
  32390. 'Adieresis': 722,
  32391. 'egrave': 556,
  32392. 'zacute': 500,
  32393. 'iogonek': 278,
  32394. 'Oacute': 778,
  32395. 'oacute': 611,
  32396. 'amacron': 556,
  32397. 'sacute': 556,
  32398. 'idieresis': 278,
  32399. 'Ocircumflex': 778,
  32400. 'Ugrave': 722,
  32401. 'Delta': 612,
  32402. 'thorn': 611,
  32403. 'twosuperior': 333,
  32404. 'Odieresis': 778,
  32405. 'mu': 611,
  32406. 'igrave': 278,
  32407. 'ohungarumlaut': 611,
  32408. 'Eogonek': 667,
  32409. 'dcroat': 611,
  32410. 'threequarters': 834,
  32411. 'Scedilla': 667,
  32412. 'lcaron': 400,
  32413. 'Kcommaaccent': 722,
  32414. 'Lacute': 611,
  32415. 'trademark': 1000,
  32416. 'edotaccent': 556,
  32417. 'Igrave': 278,
  32418. 'Imacron': 278,
  32419. 'Lcaron': 611,
  32420. 'onehalf': 834,
  32421. 'lessequal': 549,
  32422. 'ocircumflex': 611,
  32423. 'ntilde': 611,
  32424. 'Uhungarumlaut': 722,
  32425. 'Eacute': 667,
  32426. 'emacron': 556,
  32427. 'gbreve': 611,
  32428. 'onequarter': 834,
  32429. 'Scaron': 667,
  32430. 'Scommaaccent': 667,
  32431. 'Ohungarumlaut': 778,
  32432. 'degree': 400,
  32433. 'ograve': 611,
  32434. 'Ccaron': 722,
  32435. 'ugrave': 611,
  32436. 'radical': 549,
  32437. 'Dcaron': 722,
  32438. 'rcommaaccent': 389,
  32439. 'Ntilde': 722,
  32440. 'otilde': 611,
  32441. 'Rcommaaccent': 722,
  32442. 'Lcommaaccent': 611,
  32443. 'Atilde': 722,
  32444. 'Aogonek': 722,
  32445. 'Aring': 722,
  32446. 'Otilde': 778,
  32447. 'zdotaccent': 500,
  32448. 'Ecaron': 667,
  32449. 'Iogonek': 278,
  32450. 'kcommaaccent': 556,
  32451. 'minus': 584,
  32452. 'Icircumflex': 278,
  32453. 'ncaron': 611,
  32454. 'tcommaaccent': 333,
  32455. 'logicalnot': 584,
  32456. 'odieresis': 611,
  32457. 'udieresis': 611,
  32458. 'notequal': 549,
  32459. 'gcommaaccent': 611,
  32460. 'eth': 611,
  32461. 'zcaron': 500,
  32462. 'ncommaaccent': 611,
  32463. 'onesuperior': 333,
  32464. 'imacron': 278,
  32465. 'Euro': 556
  32466. },
  32467. 'Helvetica-Oblique' : {
  32468. 'space': 278,
  32469. 'exclam': 278,
  32470. 'quotedbl': 355,
  32471. 'numbersign': 556,
  32472. 'dollar': 556,
  32473. 'percent': 889,
  32474. 'ampersand': 667,
  32475. 'quoteright': 222,
  32476. 'parenleft': 333,
  32477. 'parenright': 333,
  32478. 'asterisk': 389,
  32479. 'plus': 584,
  32480. 'comma': 278,
  32481. 'hyphen': 333,
  32482. 'period': 278,
  32483. 'slash': 278,
  32484. 'zero': 556,
  32485. 'one': 556,
  32486. 'two': 556,
  32487. 'three': 556,
  32488. 'four': 556,
  32489. 'five': 556,
  32490. 'six': 556,
  32491. 'seven': 556,
  32492. 'eight': 556,
  32493. 'nine': 556,
  32494. 'colon': 278,
  32495. 'semicolon': 278,
  32496. 'less': 584,
  32497. 'equal': 584,
  32498. 'greater': 584,
  32499. 'question': 556,
  32500. 'at': 1015,
  32501. 'A': 667,
  32502. 'B': 667,
  32503. 'C': 722,
  32504. 'D': 722,
  32505. 'E': 667,
  32506. 'F': 611,
  32507. 'G': 778,
  32508. 'H': 722,
  32509. 'I': 278,
  32510. 'J': 500,
  32511. 'K': 667,
  32512. 'L': 556,
  32513. 'M': 833,
  32514. 'N': 722,
  32515. 'O': 778,
  32516. 'P': 667,
  32517. 'Q': 778,
  32518. 'R': 722,
  32519. 'S': 667,
  32520. 'T': 611,
  32521. 'U': 722,
  32522. 'V': 667,
  32523. 'W': 944,
  32524. 'X': 667,
  32525. 'Y': 667,
  32526. 'Z': 611,
  32527. 'bracketleft': 278,
  32528. 'backslash': 278,
  32529. 'bracketright': 278,
  32530. 'asciicircum': 469,
  32531. 'underscore': 556,
  32532. 'quoteleft': 222,
  32533. 'a': 556,
  32534. 'b': 556,
  32535. 'c': 500,
  32536. 'd': 556,
  32537. 'e': 556,
  32538. 'f': 278,
  32539. 'g': 556,
  32540. 'h': 556,
  32541. 'i': 222,
  32542. 'j': 222,
  32543. 'k': 500,
  32544. 'l': 222,
  32545. 'm': 833,
  32546. 'n': 556,
  32547. 'o': 556,
  32548. 'p': 556,
  32549. 'q': 556,
  32550. 'r': 333,
  32551. 's': 500,
  32552. 't': 278,
  32553. 'u': 556,
  32554. 'v': 500,
  32555. 'w': 722,
  32556. 'x': 500,
  32557. 'y': 500,
  32558. 'z': 500,
  32559. 'braceleft': 334,
  32560. 'bar': 260,
  32561. 'braceright': 334,
  32562. 'asciitilde': 584,
  32563. 'exclamdown': 333,
  32564. 'cent': 556,
  32565. 'sterling': 556,
  32566. 'fraction': 167,
  32567. 'yen': 556,
  32568. 'florin': 556,
  32569. 'section': 556,
  32570. 'currency': 556,
  32571. 'quotesingle': 191,
  32572. 'quotedblleft': 333,
  32573. 'guillemotleft': 556,
  32574. 'guilsinglleft': 333,
  32575. 'guilsinglright': 333,
  32576. 'fi': 500,
  32577. 'fl': 500,
  32578. 'endash': 556,
  32579. 'dagger': 556,
  32580. 'daggerdbl': 556,
  32581. 'periodcentered': 278,
  32582. 'paragraph': 537,
  32583. 'bullet': 350,
  32584. 'quotesinglbase': 222,
  32585. 'quotedblbase': 333,
  32586. 'quotedblright': 333,
  32587. 'guillemotright': 556,
  32588. 'ellipsis': 1000,
  32589. 'perthousand': 1000,
  32590. 'questiondown': 611,
  32591. 'grave': 333,
  32592. 'acute': 333,
  32593. 'circumflex': 333,
  32594. 'tilde': 333,
  32595. 'macron': 333,
  32596. 'breve': 333,
  32597. 'dotaccent': 333,
  32598. 'dieresis': 333,
  32599. 'ring': 333,
  32600. 'cedilla': 333,
  32601. 'hungarumlaut': 333,
  32602. 'ogonek': 333,
  32603. 'caron': 333,
  32604. 'emdash': 1000,
  32605. 'AE': 1000,
  32606. 'ordfeminine': 370,
  32607. 'Lslash': 556,
  32608. 'Oslash': 778,
  32609. 'OE': 1000,
  32610. 'ordmasculine': 365,
  32611. 'ae': 889,
  32612. 'dotlessi': 278,
  32613. 'lslash': 222,
  32614. 'oslash': 611,
  32615. 'oe': 944,
  32616. 'germandbls': 611,
  32617. 'Idieresis': 278,
  32618. 'eacute': 556,
  32619. 'abreve': 556,
  32620. 'uhungarumlaut': 556,
  32621. 'ecaron': 556,
  32622. 'Ydieresis': 667,
  32623. 'divide': 584,
  32624. 'Yacute': 667,
  32625. 'Acircumflex': 667,
  32626. 'aacute': 556,
  32627. 'Ucircumflex': 722,
  32628. 'yacute': 500,
  32629. 'scommaaccent': 500,
  32630. 'ecircumflex': 556,
  32631. 'Uring': 722,
  32632. 'Udieresis': 722,
  32633. 'aogonek': 556,
  32634. 'Uacute': 722,
  32635. 'uogonek': 556,
  32636. 'Edieresis': 667,
  32637. 'Dcroat': 722,
  32638. 'commaaccent': 250,
  32639. 'copyright': 737,
  32640. 'Emacron': 667,
  32641. 'ccaron': 500,
  32642. 'aring': 556,
  32643. 'Ncommaaccent': 722,
  32644. 'lacute': 222,
  32645. 'agrave': 556,
  32646. 'Tcommaaccent': 611,
  32647. 'Cacute': 722,
  32648. 'atilde': 556,
  32649. 'Edotaccent': 667,
  32650. 'scaron': 500,
  32651. 'scedilla': 500,
  32652. 'iacute': 278,
  32653. 'lozenge': 471,
  32654. 'Rcaron': 722,
  32655. 'Gcommaaccent': 778,
  32656. 'ucircumflex': 556,
  32657. 'acircumflex': 556,
  32658. 'Amacron': 667,
  32659. 'rcaron': 333,
  32660. 'ccedilla': 500,
  32661. 'Zdotaccent': 611,
  32662. 'Thorn': 667,
  32663. 'Omacron': 778,
  32664. 'Racute': 722,
  32665. 'Sacute': 667,
  32666. 'dcaron': 643,
  32667. 'Umacron': 722,
  32668. 'uring': 556,
  32669. 'threesuperior': 333,
  32670. 'Ograve': 778,
  32671. 'Agrave': 667,
  32672. 'Abreve': 667,
  32673. 'multiply': 584,
  32674. 'uacute': 556,
  32675. 'Tcaron': 611,
  32676. 'partialdiff': 476,
  32677. 'ydieresis': 500,
  32678. 'Nacute': 722,
  32679. 'icircumflex': 278,
  32680. 'Ecircumflex': 667,
  32681. 'adieresis': 556,
  32682. 'edieresis': 556,
  32683. 'cacute': 500,
  32684. 'nacute': 556,
  32685. 'umacron': 556,
  32686. 'Ncaron': 722,
  32687. 'Iacute': 278,
  32688. 'plusminus': 584,
  32689. 'brokenbar': 260,
  32690. 'registered': 737,
  32691. 'Gbreve': 778,
  32692. 'Idotaccent': 278,
  32693. 'summation': 600,
  32694. 'Egrave': 667,
  32695. 'racute': 333,
  32696. 'omacron': 556,
  32697. 'Zacute': 611,
  32698. 'Zcaron': 611,
  32699. 'greaterequal': 549,
  32700. 'Eth': 722,
  32701. 'Ccedilla': 722,
  32702. 'lcommaaccent': 222,
  32703. 'tcaron': 317,
  32704. 'eogonek': 556,
  32705. 'Uogonek': 722,
  32706. 'Aacute': 667,
  32707. 'Adieresis': 667,
  32708. 'egrave': 556,
  32709. 'zacute': 500,
  32710. 'iogonek': 222,
  32711. 'Oacute': 778,
  32712. 'oacute': 556,
  32713. 'amacron': 556,
  32714. 'sacute': 500,
  32715. 'idieresis': 278,
  32716. 'Ocircumflex': 778,
  32717. 'Ugrave': 722,
  32718. 'Delta': 612,
  32719. 'thorn': 556,
  32720. 'twosuperior': 333,
  32721. 'Odieresis': 778,
  32722. 'mu': 556,
  32723. 'igrave': 278,
  32724. 'ohungarumlaut': 556,
  32725. 'Eogonek': 667,
  32726. 'dcroat': 556,
  32727. 'threequarters': 834,
  32728. 'Scedilla': 667,
  32729. 'lcaron': 299,
  32730. 'Kcommaaccent': 667,
  32731. 'Lacute': 556,
  32732. 'trademark': 1000,
  32733. 'edotaccent': 556,
  32734. 'Igrave': 278,
  32735. 'Imacron': 278,
  32736. 'Lcaron': 556,
  32737. 'onehalf': 834,
  32738. 'lessequal': 549,
  32739. 'ocircumflex': 556,
  32740. 'ntilde': 556,
  32741. 'Uhungarumlaut': 722,
  32742. 'Eacute': 667,
  32743. 'emacron': 556,
  32744. 'gbreve': 556,
  32745. 'onequarter': 834,
  32746. 'Scaron': 667,
  32747. 'Scommaaccent': 667,
  32748. 'Ohungarumlaut': 778,
  32749. 'degree': 400,
  32750. 'ograve': 556,
  32751. 'Ccaron': 722,
  32752. 'ugrave': 556,
  32753. 'radical': 453,
  32754. 'Dcaron': 722,
  32755. 'rcommaaccent': 333,
  32756. 'Ntilde': 722,
  32757. 'otilde': 556,
  32758. 'Rcommaaccent': 722,
  32759. 'Lcommaaccent': 556,
  32760. 'Atilde': 667,
  32761. 'Aogonek': 667,
  32762. 'Aring': 667,
  32763. 'Otilde': 778,
  32764. 'zdotaccent': 500,
  32765. 'Ecaron': 667,
  32766. 'Iogonek': 278,
  32767. 'kcommaaccent': 500,
  32768. 'minus': 584,
  32769. 'Icircumflex': 278,
  32770. 'ncaron': 556,
  32771. 'tcommaaccent': 278,
  32772. 'logicalnot': 584,
  32773. 'odieresis': 556,
  32774. 'udieresis': 556,
  32775. 'notequal': 549,
  32776. 'gcommaaccent': 556,
  32777. 'eth': 556,
  32778. 'zcaron': 500,
  32779. 'ncommaaccent': 556,
  32780. 'onesuperior': 333,
  32781. 'imacron': 278,
  32782. 'Euro': 556
  32783. },
  32784. 'Symbol': {
  32785. 'space': 250,
  32786. 'exclam': 333,
  32787. 'universal': 713,
  32788. 'numbersign': 500,
  32789. 'existential': 549,
  32790. 'percent': 833,
  32791. 'ampersand': 778,
  32792. 'suchthat': 439,
  32793. 'parenleft': 333,
  32794. 'parenright': 333,
  32795. 'asteriskmath': 500,
  32796. 'plus': 549,
  32797. 'comma': 250,
  32798. 'minus': 549,
  32799. 'period': 250,
  32800. 'slash': 278,
  32801. 'zero': 500,
  32802. 'one': 500,
  32803. 'two': 500,
  32804. 'three': 500,
  32805. 'four': 500,
  32806. 'five': 500,
  32807. 'six': 500,
  32808. 'seven': 500,
  32809. 'eight': 500,
  32810. 'nine': 500,
  32811. 'colon': 278,
  32812. 'semicolon': 278,
  32813. 'less': 549,
  32814. 'equal': 549,
  32815. 'greater': 549,
  32816. 'question': 444,
  32817. 'congruent': 549,
  32818. 'Alpha': 722,
  32819. 'Beta': 667,
  32820. 'Chi': 722,
  32821. 'Delta': 612,
  32822. 'Epsilon': 611,
  32823. 'Phi': 763,
  32824. 'Gamma': 603,
  32825. 'Eta': 722,
  32826. 'Iota': 333,
  32827. 'theta1': 631,
  32828. 'Kappa': 722,
  32829. 'Lambda': 686,
  32830. 'Mu': 889,
  32831. 'Nu': 722,
  32832. 'Omicron': 722,
  32833. 'Pi': 768,
  32834. 'Theta': 741,
  32835. 'Rho': 556,
  32836. 'Sigma': 592,
  32837. 'Tau': 611,
  32838. 'Upsilon': 690,
  32839. 'sigma1': 439,
  32840. 'Omega': 768,
  32841. 'Xi': 645,
  32842. 'Psi': 795,
  32843. 'Zeta': 611,
  32844. 'bracketleft': 333,
  32845. 'therefore': 863,
  32846. 'bracketright': 333,
  32847. 'perpendicular': 658,
  32848. 'underscore': 500,
  32849. 'radicalex': 500,
  32850. 'alpha': 631,
  32851. 'beta': 549,
  32852. 'chi': 549,
  32853. 'delta': 494,
  32854. 'epsilon': 439,
  32855. 'phi': 521,
  32856. 'gamma': 411,
  32857. 'eta': 603,
  32858. 'iota': 329,
  32859. 'phi1': 603,
  32860. 'kappa': 549,
  32861. 'lambda': 549,
  32862. 'mu': 576,
  32863. 'nu': 521,
  32864. 'omicron': 549,
  32865. 'pi': 549,
  32866. 'theta': 521,
  32867. 'rho': 549,
  32868. 'sigma': 603,
  32869. 'tau': 439,
  32870. 'upsilon': 576,
  32871. 'omega1': 713,
  32872. 'omega': 686,
  32873. 'xi': 493,
  32874. 'psi': 686,
  32875. 'zeta': 494,
  32876. 'braceleft': 480,
  32877. 'bar': 200,
  32878. 'braceright': 480,
  32879. 'similar': 549,
  32880. 'Euro': 750,
  32881. 'Upsilon1': 620,
  32882. 'minute': 247,
  32883. 'lessequal': 549,
  32884. 'fraction': 167,
  32885. 'infinity': 713,
  32886. 'florin': 500,
  32887. 'club': 753,
  32888. 'diamond': 753,
  32889. 'heart': 753,
  32890. 'spade': 753,
  32891. 'arrowboth': 1042,
  32892. 'arrowleft': 987,
  32893. 'arrowup': 603,
  32894. 'arrowright': 987,
  32895. 'arrowdown': 603,
  32896. 'degree': 400,
  32897. 'plusminus': 549,
  32898. 'second': 411,
  32899. 'greaterequal': 549,
  32900. 'multiply': 549,
  32901. 'proportional': 713,
  32902. 'partialdiff': 494,
  32903. 'bullet': 460,
  32904. 'divide': 549,
  32905. 'notequal': 549,
  32906. 'equivalence': 549,
  32907. 'approxequal': 549,
  32908. 'ellipsis': 1000,
  32909. 'arrowvertex': 603,
  32910. 'arrowhorizex': 1000,
  32911. 'carriagereturn': 658,
  32912. 'aleph': 823,
  32913. 'Ifraktur': 686,
  32914. 'Rfraktur': 795,
  32915. 'weierstrass': 987,
  32916. 'circlemultiply': 768,
  32917. 'circleplus': 768,
  32918. 'emptyset': 823,
  32919. 'intersection': 768,
  32920. 'union': 768,
  32921. 'propersuperset': 713,
  32922. 'reflexsuperset': 713,
  32923. 'notsubset': 713,
  32924. 'propersubset': 713,
  32925. 'reflexsubset': 713,
  32926. 'element': 713,
  32927. 'notelement': 713,
  32928. 'angle': 768,
  32929. 'gradient': 713,
  32930. 'registerserif': 790,
  32931. 'copyrightserif': 790,
  32932. 'trademarkserif': 890,
  32933. 'product': 823,
  32934. 'radical': 549,
  32935. 'dotmath': 250,
  32936. 'logicalnot': 713,
  32937. 'logicaland': 603,
  32938. 'logicalor': 603,
  32939. 'arrowdblboth': 1042,
  32940. 'arrowdblleft': 987,
  32941. 'arrowdblup': 603,
  32942. 'arrowdblright': 987,
  32943. 'arrowdbldown': 603,
  32944. 'lozenge': 494,
  32945. 'angleleft': 329,
  32946. 'registersans': 790,
  32947. 'copyrightsans': 790,
  32948. 'trademarksans': 786,
  32949. 'summation': 713,
  32950. 'parenlefttp': 384,
  32951. 'parenleftex': 384,
  32952. 'parenleftbt': 384,
  32953. 'bracketlefttp': 384,
  32954. 'bracketleftex': 384,
  32955. 'bracketleftbt': 384,
  32956. 'bracelefttp': 494,
  32957. 'braceleftmid': 494,
  32958. 'braceleftbt': 494,
  32959. 'braceex': 494,
  32960. 'angleright': 329,
  32961. 'integral': 274,
  32962. 'integraltp': 686,
  32963. 'integralex': 686,
  32964. 'integralbt': 686,
  32965. 'parenrighttp': 384,
  32966. 'parenrightex': 384,
  32967. 'parenrightbt': 384,
  32968. 'bracketrighttp': 384,
  32969. 'bracketrightex': 384,
  32970. 'bracketrightbt': 384,
  32971. 'bracerighttp': 494,
  32972. 'bracerightmid': 494,
  32973. 'bracerightbt': 494,
  32974. 'apple': 790
  32975. },
  32976. 'Times-Roman': {
  32977. 'space': 250,
  32978. 'exclam': 333,
  32979. 'quotedbl': 408,
  32980. 'numbersign': 500,
  32981. 'dollar': 500,
  32982. 'percent': 833,
  32983. 'ampersand': 778,
  32984. 'quoteright': 333,
  32985. 'parenleft': 333,
  32986. 'parenright': 333,
  32987. 'asterisk': 500,
  32988. 'plus': 564,
  32989. 'comma': 250,
  32990. 'hyphen': 333,
  32991. 'period': 250,
  32992. 'slash': 278,
  32993. 'zero': 500,
  32994. 'one': 500,
  32995. 'two': 500,
  32996. 'three': 500,
  32997. 'four': 500,
  32998. 'five': 500,
  32999. 'six': 500,
  33000. 'seven': 500,
  33001. 'eight': 500,
  33002. 'nine': 500,
  33003. 'colon': 278,
  33004. 'semicolon': 278,
  33005. 'less': 564,
  33006. 'equal': 564,
  33007. 'greater': 564,
  33008. 'question': 444,
  33009. 'at': 921,
  33010. 'A': 722,
  33011. 'B': 667,
  33012. 'C': 667,
  33013. 'D': 722,
  33014. 'E': 611,
  33015. 'F': 556,
  33016. 'G': 722,
  33017. 'H': 722,
  33018. 'I': 333,
  33019. 'J': 389,
  33020. 'K': 722,
  33021. 'L': 611,
  33022. 'M': 889,
  33023. 'N': 722,
  33024. 'O': 722,
  33025. 'P': 556,
  33026. 'Q': 722,
  33027. 'R': 667,
  33028. 'S': 556,
  33029. 'T': 611,
  33030. 'U': 722,
  33031. 'V': 722,
  33032. 'W': 944,
  33033. 'X': 722,
  33034. 'Y': 722,
  33035. 'Z': 611,
  33036. 'bracketleft': 333,
  33037. 'backslash': 278,
  33038. 'bracketright': 333,
  33039. 'asciicircum': 469,
  33040. 'underscore': 500,
  33041. 'quoteleft': 333,
  33042. 'a': 444,
  33043. 'b': 500,
  33044. 'c': 444,
  33045. 'd': 500,
  33046. 'e': 444,
  33047. 'f': 333,
  33048. 'g': 500,
  33049. 'h': 500,
  33050. 'i': 278,
  33051. 'j': 278,
  33052. 'k': 500,
  33053. 'l': 278,
  33054. 'm': 778,
  33055. 'n': 500,
  33056. 'o': 500,
  33057. 'p': 500,
  33058. 'q': 500,
  33059. 'r': 333,
  33060. 's': 389,
  33061. 't': 278,
  33062. 'u': 500,
  33063. 'v': 500,
  33064. 'w': 722,
  33065. 'x': 500,
  33066. 'y': 500,
  33067. 'z': 444,
  33068. 'braceleft': 480,
  33069. 'bar': 200,
  33070. 'braceright': 480,
  33071. 'asciitilde': 541,
  33072. 'exclamdown': 333,
  33073. 'cent': 500,
  33074. 'sterling': 500,
  33075. 'fraction': 167,
  33076. 'yen': 500,
  33077. 'florin': 500,
  33078. 'section': 500,
  33079. 'currency': 500,
  33080. 'quotesingle': 180,
  33081. 'quotedblleft': 444,
  33082. 'guillemotleft': 500,
  33083. 'guilsinglleft': 333,
  33084. 'guilsinglright': 333,
  33085. 'fi': 556,
  33086. 'fl': 556,
  33087. 'endash': 500,
  33088. 'dagger': 500,
  33089. 'daggerdbl': 500,
  33090. 'periodcentered': 250,
  33091. 'paragraph': 453,
  33092. 'bullet': 350,
  33093. 'quotesinglbase': 333,
  33094. 'quotedblbase': 444,
  33095. 'quotedblright': 444,
  33096. 'guillemotright': 500,
  33097. 'ellipsis': 1000,
  33098. 'perthousand': 1000,
  33099. 'questiondown': 444,
  33100. 'grave': 333,
  33101. 'acute': 333,
  33102. 'circumflex': 333,
  33103. 'tilde': 333,
  33104. 'macron': 333,
  33105. 'breve': 333,
  33106. 'dotaccent': 333,
  33107. 'dieresis': 333,
  33108. 'ring': 333,
  33109. 'cedilla': 333,
  33110. 'hungarumlaut': 333,
  33111. 'ogonek': 333,
  33112. 'caron': 333,
  33113. 'emdash': 1000,
  33114. 'AE': 889,
  33115. 'ordfeminine': 276,
  33116. 'Lslash': 611,
  33117. 'Oslash': 722,
  33118. 'OE': 889,
  33119. 'ordmasculine': 310,
  33120. 'ae': 667,
  33121. 'dotlessi': 278,
  33122. 'lslash': 278,
  33123. 'oslash': 500,
  33124. 'oe': 722,
  33125. 'germandbls': 500,
  33126. 'Idieresis': 333,
  33127. 'eacute': 444,
  33128. 'abreve': 444,
  33129. 'uhungarumlaut': 500,
  33130. 'ecaron': 444,
  33131. 'Ydieresis': 722,
  33132. 'divide': 564,
  33133. 'Yacute': 722,
  33134. 'Acircumflex': 722,
  33135. 'aacute': 444,
  33136. 'Ucircumflex': 722,
  33137. 'yacute': 500,
  33138. 'scommaaccent': 389,
  33139. 'ecircumflex': 444,
  33140. 'Uring': 722,
  33141. 'Udieresis': 722,
  33142. 'aogonek': 444,
  33143. 'Uacute': 722,
  33144. 'uogonek': 500,
  33145. 'Edieresis': 611,
  33146. 'Dcroat': 722,
  33147. 'commaaccent': 250,
  33148. 'copyright': 760,
  33149. 'Emacron': 611,
  33150. 'ccaron': 444,
  33151. 'aring': 444,
  33152. 'Ncommaaccent': 722,
  33153. 'lacute': 278,
  33154. 'agrave': 444,
  33155. 'Tcommaaccent': 611,
  33156. 'Cacute': 667,
  33157. 'atilde': 444,
  33158. 'Edotaccent': 611,
  33159. 'scaron': 389,
  33160. 'scedilla': 389,
  33161. 'iacute': 278,
  33162. 'lozenge': 471,
  33163. 'Rcaron': 667,
  33164. 'Gcommaaccent': 722,
  33165. 'ucircumflex': 500,
  33166. 'acircumflex': 444,
  33167. 'Amacron': 722,
  33168. 'rcaron': 333,
  33169. 'ccedilla': 444,
  33170. 'Zdotaccent': 611,
  33171. 'Thorn': 556,
  33172. 'Omacron': 722,
  33173. 'Racute': 667,
  33174. 'Sacute': 556,
  33175. 'dcaron': 588,
  33176. 'Umacron': 722,
  33177. 'uring': 500,
  33178. 'threesuperior': 300,
  33179. 'Ograve': 722,
  33180. 'Agrave': 722,
  33181. 'Abreve': 722,
  33182. 'multiply': 564,
  33183. 'uacute': 500,
  33184. 'Tcaron': 611,
  33185. 'partialdiff': 476,
  33186. 'ydieresis': 500,
  33187. 'Nacute': 722,
  33188. 'icircumflex': 278,
  33189. 'Ecircumflex': 611,
  33190. 'adieresis': 444,
  33191. 'edieresis': 444,
  33192. 'cacute': 444,
  33193. 'nacute': 500,
  33194. 'umacron': 500,
  33195. 'Ncaron': 722,
  33196. 'Iacute': 333,
  33197. 'plusminus': 564,
  33198. 'brokenbar': 200,
  33199. 'registered': 760,
  33200. 'Gbreve': 722,
  33201. 'Idotaccent': 333,
  33202. 'summation': 600,
  33203. 'Egrave': 611,
  33204. 'racute': 333,
  33205. 'omacron': 500,
  33206. 'Zacute': 611,
  33207. 'Zcaron': 611,
  33208. 'greaterequal': 549,
  33209. 'Eth': 722,
  33210. 'Ccedilla': 667,
  33211. 'lcommaaccent': 278,
  33212. 'tcaron': 326,
  33213. 'eogonek': 444,
  33214. 'Uogonek': 722,
  33215. 'Aacute': 722,
  33216. 'Adieresis': 722,
  33217. 'egrave': 444,
  33218. 'zacute': 444,
  33219. 'iogonek': 278,
  33220. 'Oacute': 722,
  33221. 'oacute': 500,
  33222. 'amacron': 444,
  33223. 'sacute': 389,
  33224. 'idieresis': 278,
  33225. 'Ocircumflex': 722,
  33226. 'Ugrave': 722,
  33227. 'Delta': 612,
  33228. 'thorn': 500,
  33229. 'twosuperior': 300,
  33230. 'Odieresis': 722,
  33231. 'mu': 500,
  33232. 'igrave': 278,
  33233. 'ohungarumlaut': 500,
  33234. 'Eogonek': 611,
  33235. 'dcroat': 500,
  33236. 'threequarters': 750,
  33237. 'Scedilla': 556,
  33238. 'lcaron': 344,
  33239. 'Kcommaaccent': 722,
  33240. 'Lacute': 611,
  33241. 'trademark': 980,
  33242. 'edotaccent': 444,
  33243. 'Igrave': 333,
  33244. 'Imacron': 333,
  33245. 'Lcaron': 611,
  33246. 'onehalf': 750,
  33247. 'lessequal': 549,
  33248. 'ocircumflex': 500,
  33249. 'ntilde': 500,
  33250. 'Uhungarumlaut': 722,
  33251. 'Eacute': 611,
  33252. 'emacron': 444,
  33253. 'gbreve': 500,
  33254. 'onequarter': 750,
  33255. 'Scaron': 556,
  33256. 'Scommaaccent': 556,
  33257. 'Ohungarumlaut': 722,
  33258. 'degree': 400,
  33259. 'ograve': 500,
  33260. 'Ccaron': 667,
  33261. 'ugrave': 500,
  33262. 'radical': 453,
  33263. 'Dcaron': 722,
  33264. 'rcommaaccent': 333,
  33265. 'Ntilde': 722,
  33266. 'otilde': 500,
  33267. 'Rcommaaccent': 667,
  33268. 'Lcommaaccent': 611,
  33269. 'Atilde': 722,
  33270. 'Aogonek': 722,
  33271. 'Aring': 722,
  33272. 'Otilde': 722,
  33273. 'zdotaccent': 444,
  33274. 'Ecaron': 611,
  33275. 'Iogonek': 333,
  33276. 'kcommaaccent': 500,
  33277. 'minus': 564,
  33278. 'Icircumflex': 333,
  33279. 'ncaron': 500,
  33280. 'tcommaaccent': 278,
  33281. 'logicalnot': 564,
  33282. 'odieresis': 500,
  33283. 'udieresis': 500,
  33284. 'notequal': 549,
  33285. 'gcommaaccent': 500,
  33286. 'eth': 500,
  33287. 'zcaron': 444,
  33288. 'ncommaaccent': 500,
  33289. 'onesuperior': 300,
  33290. 'imacron': 278,
  33291. 'Euro': 500
  33292. },
  33293. 'Times-Bold': {
  33294. 'space': 250,
  33295. 'exclam': 333,
  33296. 'quotedbl': 555,
  33297. 'numbersign': 500,
  33298. 'dollar': 500,
  33299. 'percent': 1000,
  33300. 'ampersand': 833,
  33301. 'quoteright': 333,
  33302. 'parenleft': 333,
  33303. 'parenright': 333,
  33304. 'asterisk': 500,
  33305. 'plus': 570,
  33306. 'comma': 250,
  33307. 'hyphen': 333,
  33308. 'period': 250,
  33309. 'slash': 278,
  33310. 'zero': 500,
  33311. 'one': 500,
  33312. 'two': 500,
  33313. 'three': 500,
  33314. 'four': 500,
  33315. 'five': 500,
  33316. 'six': 500,
  33317. 'seven': 500,
  33318. 'eight': 500,
  33319. 'nine': 500,
  33320. 'colon': 333,
  33321. 'semicolon': 333,
  33322. 'less': 570,
  33323. 'equal': 570,
  33324. 'greater': 570,
  33325. 'question': 500,
  33326. 'at': 930,
  33327. 'A': 722,
  33328. 'B': 667,
  33329. 'C': 722,
  33330. 'D': 722,
  33331. 'E': 667,
  33332. 'F': 611,
  33333. 'G': 778,
  33334. 'H': 778,
  33335. 'I': 389,
  33336. 'J': 500,
  33337. 'K': 778,
  33338. 'L': 667,
  33339. 'M': 944,
  33340. 'N': 722,
  33341. 'O': 778,
  33342. 'P': 611,
  33343. 'Q': 778,
  33344. 'R': 722,
  33345. 'S': 556,
  33346. 'T': 667,
  33347. 'U': 722,
  33348. 'V': 722,
  33349. 'W': 1000,
  33350. 'X': 722,
  33351. 'Y': 722,
  33352. 'Z': 667,
  33353. 'bracketleft': 333,
  33354. 'backslash': 278,
  33355. 'bracketright': 333,
  33356. 'asciicircum': 581,
  33357. 'underscore': 500,
  33358. 'quoteleft': 333,
  33359. 'a': 500,
  33360. 'b': 556,
  33361. 'c': 444,
  33362. 'd': 556,
  33363. 'e': 444,
  33364. 'f': 333,
  33365. 'g': 500,
  33366. 'h': 556,
  33367. 'i': 278,
  33368. 'j': 333,
  33369. 'k': 556,
  33370. 'l': 278,
  33371. 'm': 833,
  33372. 'n': 556,
  33373. 'o': 500,
  33374. 'p': 556,
  33375. 'q': 556,
  33376. 'r': 444,
  33377. 's': 389,
  33378. 't': 333,
  33379. 'u': 556,
  33380. 'v': 500,
  33381. 'w': 722,
  33382. 'x': 500,
  33383. 'y': 500,
  33384. 'z': 444,
  33385. 'braceleft': 394,
  33386. 'bar': 220,
  33387. 'braceright': 394,
  33388. 'asciitilde': 520,
  33389. 'exclamdown': 333,
  33390. 'cent': 500,
  33391. 'sterling': 500,
  33392. 'fraction': 167,
  33393. 'yen': 500,
  33394. 'florin': 500,
  33395. 'section': 500,
  33396. 'currency': 500,
  33397. 'quotesingle': 278,
  33398. 'quotedblleft': 500,
  33399. 'guillemotleft': 500,
  33400. 'guilsinglleft': 333,
  33401. 'guilsinglright': 333,
  33402. 'fi': 556,
  33403. 'fl': 556,
  33404. 'endash': 500,
  33405. 'dagger': 500,
  33406. 'daggerdbl': 500,
  33407. 'periodcentered': 250,
  33408. 'paragraph': 540,
  33409. 'bullet': 350,
  33410. 'quotesinglbase': 333,
  33411. 'quotedblbase': 500,
  33412. 'quotedblright': 500,
  33413. 'guillemotright': 500,
  33414. 'ellipsis': 1000,
  33415. 'perthousand': 1000,
  33416. 'questiondown': 500,
  33417. 'grave': 333,
  33418. 'acute': 333,
  33419. 'circumflex': 333,
  33420. 'tilde': 333,
  33421. 'macron': 333,
  33422. 'breve': 333,
  33423. 'dotaccent': 333,
  33424. 'dieresis': 333,
  33425. 'ring': 333,
  33426. 'cedilla': 333,
  33427. 'hungarumlaut': 333,
  33428. 'ogonek': 333,
  33429. 'caron': 333,
  33430. 'emdash': 1000,
  33431. 'AE': 1000,
  33432. 'ordfeminine': 300,
  33433. 'Lslash': 667,
  33434. 'Oslash': 778,
  33435. 'OE': 1000,
  33436. 'ordmasculine': 330,
  33437. 'ae': 722,
  33438. 'dotlessi': 278,
  33439. 'lslash': 278,
  33440. 'oslash': 500,
  33441. 'oe': 722,
  33442. 'germandbls': 556,
  33443. 'Idieresis': 389,
  33444. 'eacute': 444,
  33445. 'abreve': 500,
  33446. 'uhungarumlaut': 556,
  33447. 'ecaron': 444,
  33448. 'Ydieresis': 722,
  33449. 'divide': 570,
  33450. 'Yacute': 722,
  33451. 'Acircumflex': 722,
  33452. 'aacute': 500,
  33453. 'Ucircumflex': 722,
  33454. 'yacute': 500,
  33455. 'scommaaccent': 389,
  33456. 'ecircumflex': 444,
  33457. 'Uring': 722,
  33458. 'Udieresis': 722,
  33459. 'aogonek': 500,
  33460. 'Uacute': 722,
  33461. 'uogonek': 556,
  33462. 'Edieresis': 667,
  33463. 'Dcroat': 722,
  33464. 'commaaccent': 250,
  33465. 'copyright': 747,
  33466. 'Emacron': 667,
  33467. 'ccaron': 444,
  33468. 'aring': 500,
  33469. 'Ncommaaccent': 722,
  33470. 'lacute': 278,
  33471. 'agrave': 500,
  33472. 'Tcommaaccent': 667,
  33473. 'Cacute': 722,
  33474. 'atilde': 500,
  33475. 'Edotaccent': 667,
  33476. 'scaron': 389,
  33477. 'scedilla': 389,
  33478. 'iacute': 278,
  33479. 'lozenge': 494,
  33480. 'Rcaron': 722,
  33481. 'Gcommaaccent': 778,
  33482. 'ucircumflex': 556,
  33483. 'acircumflex': 500,
  33484. 'Amacron': 722,
  33485. 'rcaron': 444,
  33486. 'ccedilla': 444,
  33487. 'Zdotaccent': 667,
  33488. 'Thorn': 611,
  33489. 'Omacron': 778,
  33490. 'Racute': 722,
  33491. 'Sacute': 556,
  33492. 'dcaron': 672,
  33493. 'Umacron': 722,
  33494. 'uring': 556,
  33495. 'threesuperior': 300,
  33496. 'Ograve': 778,
  33497. 'Agrave': 722,
  33498. 'Abreve': 722,
  33499. 'multiply': 570,
  33500. 'uacute': 556,
  33501. 'Tcaron': 667,
  33502. 'partialdiff': 494,
  33503. 'ydieresis': 500,
  33504. 'Nacute': 722,
  33505. 'icircumflex': 278,
  33506. 'Ecircumflex': 667,
  33507. 'adieresis': 500,
  33508. 'edieresis': 444,
  33509. 'cacute': 444,
  33510. 'nacute': 556,
  33511. 'umacron': 556,
  33512. 'Ncaron': 722,
  33513. 'Iacute': 389,
  33514. 'plusminus': 570,
  33515. 'brokenbar': 220,
  33516. 'registered': 747,
  33517. 'Gbreve': 778,
  33518. 'Idotaccent': 389,
  33519. 'summation': 600,
  33520. 'Egrave': 667,
  33521. 'racute': 444,
  33522. 'omacron': 500,
  33523. 'Zacute': 667,
  33524. 'Zcaron': 667,
  33525. 'greaterequal': 549,
  33526. 'Eth': 722,
  33527. 'Ccedilla': 722,
  33528. 'lcommaaccent': 278,
  33529. 'tcaron': 416,
  33530. 'eogonek': 444,
  33531. 'Uogonek': 722,
  33532. 'Aacute': 722,
  33533. 'Adieresis': 722,
  33534. 'egrave': 444,
  33535. 'zacute': 444,
  33536. 'iogonek': 278,
  33537. 'Oacute': 778,
  33538. 'oacute': 500,
  33539. 'amacron': 500,
  33540. 'sacute': 389,
  33541. 'idieresis': 278,
  33542. 'Ocircumflex': 778,
  33543. 'Ugrave': 722,
  33544. 'Delta': 612,
  33545. 'thorn': 556,
  33546. 'twosuperior': 300,
  33547. 'Odieresis': 778,
  33548. 'mu': 556,
  33549. 'igrave': 278,
  33550. 'ohungarumlaut': 500,
  33551. 'Eogonek': 667,
  33552. 'dcroat': 556,
  33553. 'threequarters': 750,
  33554. 'Scedilla': 556,
  33555. 'lcaron': 394,
  33556. 'Kcommaaccent': 778,
  33557. 'Lacute': 667,
  33558. 'trademark': 1000,
  33559. 'edotaccent': 444,
  33560. 'Igrave': 389,
  33561. 'Imacron': 389,
  33562. 'Lcaron': 667,
  33563. 'onehalf': 750,
  33564. 'lessequal': 549,
  33565. 'ocircumflex': 500,
  33566. 'ntilde': 556,
  33567. 'Uhungarumlaut': 722,
  33568. 'Eacute': 667,
  33569. 'emacron': 444,
  33570. 'gbreve': 500,
  33571. 'onequarter': 750,
  33572. 'Scaron': 556,
  33573. 'Scommaaccent': 556,
  33574. 'Ohungarumlaut': 778,
  33575. 'degree': 400,
  33576. 'ograve': 500,
  33577. 'Ccaron': 722,
  33578. 'ugrave': 556,
  33579. 'radical': 549,
  33580. 'Dcaron': 722,
  33581. 'rcommaaccent': 444,
  33582. 'Ntilde': 722,
  33583. 'otilde': 500,
  33584. 'Rcommaaccent': 722,
  33585. 'Lcommaaccent': 667,
  33586. 'Atilde': 722,
  33587. 'Aogonek': 722,
  33588. 'Aring': 722,
  33589. 'Otilde': 778,
  33590. 'zdotaccent': 444,
  33591. 'Ecaron': 667,
  33592. 'Iogonek': 389,
  33593. 'kcommaaccent': 556,
  33594. 'minus': 570,
  33595. 'Icircumflex': 389,
  33596. 'ncaron': 556,
  33597. 'tcommaaccent': 333,
  33598. 'logicalnot': 570,
  33599. 'odieresis': 500,
  33600. 'udieresis': 556,
  33601. 'notequal': 549,
  33602. 'gcommaaccent': 500,
  33603. 'eth': 500,
  33604. 'zcaron': 444,
  33605. 'ncommaaccent': 556,
  33606. 'onesuperior': 300,
  33607. 'imacron': 278,
  33608. 'Euro': 500
  33609. },
  33610. 'Times-BoldItalic': {
  33611. 'space': 250,
  33612. 'exclam': 389,
  33613. 'quotedbl': 555,
  33614. 'numbersign': 500,
  33615. 'dollar': 500,
  33616. 'percent': 833,
  33617. 'ampersand': 778,
  33618. 'quoteright': 333,
  33619. 'parenleft': 333,
  33620. 'parenright': 333,
  33621. 'asterisk': 500,
  33622. 'plus': 570,
  33623. 'comma': 250,
  33624. 'hyphen': 333,
  33625. 'period': 250,
  33626. 'slash': 278,
  33627. 'zero': 500,
  33628. 'one': 500,
  33629. 'two': 500,
  33630. 'three': 500,
  33631. 'four': 500,
  33632. 'five': 500,
  33633. 'six': 500,
  33634. 'seven': 500,
  33635. 'eight': 500,
  33636. 'nine': 500,
  33637. 'colon': 333,
  33638. 'semicolon': 333,
  33639. 'less': 570,
  33640. 'equal': 570,
  33641. 'greater': 570,
  33642. 'question': 500,
  33643. 'at': 832,
  33644. 'A': 667,
  33645. 'B': 667,
  33646. 'C': 667,
  33647. 'D': 722,
  33648. 'E': 667,
  33649. 'F': 667,
  33650. 'G': 722,
  33651. 'H': 778,
  33652. 'I': 389,
  33653. 'J': 500,
  33654. 'K': 667,
  33655. 'L': 611,
  33656. 'M': 889,
  33657. 'N': 722,
  33658. 'O': 722,
  33659. 'P': 611,
  33660. 'Q': 722,
  33661. 'R': 667,
  33662. 'S': 556,
  33663. 'T': 611,
  33664. 'U': 722,
  33665. 'V': 667,
  33666. 'W': 889,
  33667. 'X': 667,
  33668. 'Y': 611,
  33669. 'Z': 611,
  33670. 'bracketleft': 333,
  33671. 'backslash': 278,
  33672. 'bracketright': 333,
  33673. 'asciicircum': 570,
  33674. 'underscore': 500,
  33675. 'quoteleft': 333,
  33676. 'a': 500,
  33677. 'b': 500,
  33678. 'c': 444,
  33679. 'd': 500,
  33680. 'e': 444,
  33681. 'f': 333,
  33682. 'g': 500,
  33683. 'h': 556,
  33684. 'i': 278,
  33685. 'j': 278,
  33686. 'k': 500,
  33687. 'l': 278,
  33688. 'm': 778,
  33689. 'n': 556,
  33690. 'o': 500,
  33691. 'p': 500,
  33692. 'q': 500,
  33693. 'r': 389,
  33694. 's': 389,
  33695. 't': 278,
  33696. 'u': 556,
  33697. 'v': 444,
  33698. 'w': 667,
  33699. 'x': 500,
  33700. 'y': 444,
  33701. 'z': 389,
  33702. 'braceleft': 348,
  33703. 'bar': 220,
  33704. 'braceright': 348,
  33705. 'asciitilde': 570,
  33706. 'exclamdown': 389,
  33707. 'cent': 500,
  33708. 'sterling': 500,
  33709. 'fraction': 167,
  33710. 'yen': 500,
  33711. 'florin': 500,
  33712. 'section': 500,
  33713. 'currency': 500,
  33714. 'quotesingle': 278,
  33715. 'quotedblleft': 500,
  33716. 'guillemotleft': 500,
  33717. 'guilsinglleft': 333,
  33718. 'guilsinglright': 333,
  33719. 'fi': 556,
  33720. 'fl': 556,
  33721. 'endash': 500,
  33722. 'dagger': 500,
  33723. 'daggerdbl': 500,
  33724. 'periodcentered': 250,
  33725. 'paragraph': 500,
  33726. 'bullet': 350,
  33727. 'quotesinglbase': 333,
  33728. 'quotedblbase': 500,
  33729. 'quotedblright': 500,
  33730. 'guillemotright': 500,
  33731. 'ellipsis': 1000,
  33732. 'perthousand': 1000,
  33733. 'questiondown': 500,
  33734. 'grave': 333,
  33735. 'acute': 333,
  33736. 'circumflex': 333,
  33737. 'tilde': 333,
  33738. 'macron': 333,
  33739. 'breve': 333,
  33740. 'dotaccent': 333,
  33741. 'dieresis': 333,
  33742. 'ring': 333,
  33743. 'cedilla': 333,
  33744. 'hungarumlaut': 333,
  33745. 'ogonek': 333,
  33746. 'caron': 333,
  33747. 'emdash': 1000,
  33748. 'AE': 944,
  33749. 'ordfeminine': 266,
  33750. 'Lslash': 611,
  33751. 'Oslash': 722,
  33752. 'OE': 944,
  33753. 'ordmasculine': 300,
  33754. 'ae': 722,
  33755. 'dotlessi': 278,
  33756. 'lslash': 278,
  33757. 'oslash': 500,
  33758. 'oe': 722,
  33759. 'germandbls': 500,
  33760. 'Idieresis': 389,
  33761. 'eacute': 444,
  33762. 'abreve': 500,
  33763. 'uhungarumlaut': 556,
  33764. 'ecaron': 444,
  33765. 'Ydieresis': 611,
  33766. 'divide': 570,
  33767. 'Yacute': 611,
  33768. 'Acircumflex': 667,
  33769. 'aacute': 500,
  33770. 'Ucircumflex': 722,
  33771. 'yacute': 444,
  33772. 'scommaaccent': 389,
  33773. 'ecircumflex': 444,
  33774. 'Uring': 722,
  33775. 'Udieresis': 722,
  33776. 'aogonek': 500,
  33777. 'Uacute': 722,
  33778. 'uogonek': 556,
  33779. 'Edieresis': 667,
  33780. 'Dcroat': 722,
  33781. 'commaaccent': 250,
  33782. 'copyright': 747,
  33783. 'Emacron': 667,
  33784. 'ccaron': 444,
  33785. 'aring': 500,
  33786. 'Ncommaaccent': 722,
  33787. 'lacute': 278,
  33788. 'agrave': 500,
  33789. 'Tcommaaccent': 611,
  33790. 'Cacute': 667,
  33791. 'atilde': 500,
  33792. 'Edotaccent': 667,
  33793. 'scaron': 389,
  33794. 'scedilla': 389,
  33795. 'iacute': 278,
  33796. 'lozenge': 494,
  33797. 'Rcaron': 667,
  33798. 'Gcommaaccent': 722,
  33799. 'ucircumflex': 556,
  33800. 'acircumflex': 500,
  33801. 'Amacron': 667,
  33802. 'rcaron': 389,
  33803. 'ccedilla': 444,
  33804. 'Zdotaccent': 611,
  33805. 'Thorn': 611,
  33806. 'Omacron': 722,
  33807. 'Racute': 667,
  33808. 'Sacute': 556,
  33809. 'dcaron': 608,
  33810. 'Umacron': 722,
  33811. 'uring': 556,
  33812. 'threesuperior': 300,
  33813. 'Ograve': 722,
  33814. 'Agrave': 667,
  33815. 'Abreve': 667,
  33816. 'multiply': 570,
  33817. 'uacute': 556,
  33818. 'Tcaron': 611,
  33819. 'partialdiff': 494,
  33820. 'ydieresis': 444,
  33821. 'Nacute': 722,
  33822. 'icircumflex': 278,
  33823. 'Ecircumflex': 667,
  33824. 'adieresis': 500,
  33825. 'edieresis': 444,
  33826. 'cacute': 444,
  33827. 'nacute': 556,
  33828. 'umacron': 556,
  33829. 'Ncaron': 722,
  33830. 'Iacute': 389,
  33831. 'plusminus': 570,
  33832. 'brokenbar': 220,
  33833. 'registered': 747,
  33834. 'Gbreve': 722,
  33835. 'Idotaccent': 389,
  33836. 'summation': 600,
  33837. 'Egrave': 667,
  33838. 'racute': 389,
  33839. 'omacron': 500,
  33840. 'Zacute': 611,
  33841. 'Zcaron': 611,
  33842. 'greaterequal': 549,
  33843. 'Eth': 722,
  33844. 'Ccedilla': 667,
  33845. 'lcommaaccent': 278,
  33846. 'tcaron': 366,
  33847. 'eogonek': 444,
  33848. 'Uogonek': 722,
  33849. 'Aacute': 667,
  33850. 'Adieresis': 667,
  33851. 'egrave': 444,
  33852. 'zacute': 389,
  33853. 'iogonek': 278,
  33854. 'Oacute': 722,
  33855. 'oacute': 500,
  33856. 'amacron': 500,
  33857. 'sacute': 389,
  33858. 'idieresis': 278,
  33859. 'Ocircumflex': 722,
  33860. 'Ugrave': 722,
  33861. 'Delta': 612,
  33862. 'thorn': 500,
  33863. 'twosuperior': 300,
  33864. 'Odieresis': 722,
  33865. 'mu': 576,
  33866. 'igrave': 278,
  33867. 'ohungarumlaut': 500,
  33868. 'Eogonek': 667,
  33869. 'dcroat': 500,
  33870. 'threequarters': 750,
  33871. 'Scedilla': 556,
  33872. 'lcaron': 382,
  33873. 'Kcommaaccent': 667,
  33874. 'Lacute': 611,
  33875. 'trademark': 1000,
  33876. 'edotaccent': 444,
  33877. 'Igrave': 389,
  33878. 'Imacron': 389,
  33879. 'Lcaron': 611,
  33880. 'onehalf': 750,
  33881. 'lessequal': 549,
  33882. 'ocircumflex': 500,
  33883. 'ntilde': 556,
  33884. 'Uhungarumlaut': 722,
  33885. 'Eacute': 667,
  33886. 'emacron': 444,
  33887. 'gbreve': 500,
  33888. 'onequarter': 750,
  33889. 'Scaron': 556,
  33890. 'Scommaaccent': 556,
  33891. 'Ohungarumlaut': 722,
  33892. 'degree': 400,
  33893. 'ograve': 500,
  33894. 'Ccaron': 667,
  33895. 'ugrave': 556,
  33896. 'radical': 549,
  33897. 'Dcaron': 722,
  33898. 'rcommaaccent': 389,
  33899. 'Ntilde': 722,
  33900. 'otilde': 500,
  33901. 'Rcommaaccent': 667,
  33902. 'Lcommaaccent': 611,
  33903. 'Atilde': 667,
  33904. 'Aogonek': 667,
  33905. 'Aring': 667,
  33906. 'Otilde': 722,
  33907. 'zdotaccent': 389,
  33908. 'Ecaron': 667,
  33909. 'Iogonek': 389,
  33910. 'kcommaaccent': 500,
  33911. 'minus': 606,
  33912. 'Icircumflex': 389,
  33913. 'ncaron': 556,
  33914. 'tcommaaccent': 278,
  33915. 'logicalnot': 606,
  33916. 'odieresis': 500,
  33917. 'udieresis': 556,
  33918. 'notequal': 549,
  33919. 'gcommaaccent': 500,
  33920. 'eth': 500,
  33921. 'zcaron': 389,
  33922. 'ncommaaccent': 556,
  33923. 'onesuperior': 300,
  33924. 'imacron': 278,
  33925. 'Euro': 500
  33926. },
  33927. 'Times-Italic': {
  33928. 'space': 250,
  33929. 'exclam': 333,
  33930. 'quotedbl': 420,
  33931. 'numbersign': 500,
  33932. 'dollar': 500,
  33933. 'percent': 833,
  33934. 'ampersand': 778,
  33935. 'quoteright': 333,
  33936. 'parenleft': 333,
  33937. 'parenright': 333,
  33938. 'asterisk': 500,
  33939. 'plus': 675,
  33940. 'comma': 250,
  33941. 'hyphen': 333,
  33942. 'period': 250,
  33943. 'slash': 278,
  33944. 'zero': 500,
  33945. 'one': 500,
  33946. 'two': 500,
  33947. 'three': 500,
  33948. 'four': 500,
  33949. 'five': 500,
  33950. 'six': 500,
  33951. 'seven': 500,
  33952. 'eight': 500,
  33953. 'nine': 500,
  33954. 'colon': 333,
  33955. 'semicolon': 333,
  33956. 'less': 675,
  33957. 'equal': 675,
  33958. 'greater': 675,
  33959. 'question': 500,
  33960. 'at': 920,
  33961. 'A': 611,
  33962. 'B': 611,
  33963. 'C': 667,
  33964. 'D': 722,
  33965. 'E': 611,
  33966. 'F': 611,
  33967. 'G': 722,
  33968. 'H': 722,
  33969. 'I': 333,
  33970. 'J': 444,
  33971. 'K': 667,
  33972. 'L': 556,
  33973. 'M': 833,
  33974. 'N': 667,
  33975. 'O': 722,
  33976. 'P': 611,
  33977. 'Q': 722,
  33978. 'R': 611,
  33979. 'S': 500,
  33980. 'T': 556,
  33981. 'U': 722,
  33982. 'V': 611,
  33983. 'W': 833,
  33984. 'X': 611,
  33985. 'Y': 556,
  33986. 'Z': 556,
  33987. 'bracketleft': 389,
  33988. 'backslash': 278,
  33989. 'bracketright': 389,
  33990. 'asciicircum': 422,
  33991. 'underscore': 500,
  33992. 'quoteleft': 333,
  33993. 'a': 500,
  33994. 'b': 500,
  33995. 'c': 444,
  33996. 'd': 500,
  33997. 'e': 444,
  33998. 'f': 278,
  33999. 'g': 500,
  34000. 'h': 500,
  34001. 'i': 278,
  34002. 'j': 278,
  34003. 'k': 444,
  34004. 'l': 278,
  34005. 'm': 722,
  34006. 'n': 500,
  34007. 'o': 500,
  34008. 'p': 500,
  34009. 'q': 500,
  34010. 'r': 389,
  34011. 's': 389,
  34012. 't': 278,
  34013. 'u': 500,
  34014. 'v': 444,
  34015. 'w': 667,
  34016. 'x': 444,
  34017. 'y': 444,
  34018. 'z': 389,
  34019. 'braceleft': 400,
  34020. 'bar': 275,
  34021. 'braceright': 400,
  34022. 'asciitilde': 541,
  34023. 'exclamdown': 389,
  34024. 'cent': 500,
  34025. 'sterling': 500,
  34026. 'fraction': 167,
  34027. 'yen': 500,
  34028. 'florin': 500,
  34029. 'section': 500,
  34030. 'currency': 500,
  34031. 'quotesingle': 214,
  34032. 'quotedblleft': 556,
  34033. 'guillemotleft': 500,
  34034. 'guilsinglleft': 333,
  34035. 'guilsinglright': 333,
  34036. 'fi': 500,
  34037. 'fl': 500,
  34038. 'endash': 500,
  34039. 'dagger': 500,
  34040. 'daggerdbl': 500,
  34041. 'periodcentered': 250,
  34042. 'paragraph': 523,
  34043. 'bullet': 350,
  34044. 'quotesinglbase': 333,
  34045. 'quotedblbase': 556,
  34046. 'quotedblright': 556,
  34047. 'guillemotright': 500,
  34048. 'ellipsis': 889,
  34049. 'perthousand': 1000,
  34050. 'questiondown': 500,
  34051. 'grave': 333,
  34052. 'acute': 333,
  34053. 'circumflex': 333,
  34054. 'tilde': 333,
  34055. 'macron': 333,
  34056. 'breve': 333,
  34057. 'dotaccent': 333,
  34058. 'dieresis': 333,
  34059. 'ring': 333,
  34060. 'cedilla': 333,
  34061. 'hungarumlaut': 333,
  34062. 'ogonek': 333,
  34063. 'caron': 333,
  34064. 'emdash': 889,
  34065. 'AE': 889,
  34066. 'ordfeminine': 276,
  34067. 'Lslash': 556,
  34068. 'Oslash': 722,
  34069. 'OE': 944,
  34070. 'ordmasculine': 310,
  34071. 'ae': 667,
  34072. 'dotlessi': 278,
  34073. 'lslash': 278,
  34074. 'oslash': 500,
  34075. 'oe': 667,
  34076. 'germandbls': 500,
  34077. 'Idieresis': 333,
  34078. 'eacute': 444,
  34079. 'abreve': 500,
  34080. 'uhungarumlaut': 500,
  34081. 'ecaron': 444,
  34082. 'Ydieresis': 556,
  34083. 'divide': 675,
  34084. 'Yacute': 556,
  34085. 'Acircumflex': 611,
  34086. 'aacute': 500,
  34087. 'Ucircumflex': 722,
  34088. 'yacute': 444,
  34089. 'scommaaccent': 389,
  34090. 'ecircumflex': 444,
  34091. 'Uring': 722,
  34092. 'Udieresis': 722,
  34093. 'aogonek': 500,
  34094. 'Uacute': 722,
  34095. 'uogonek': 500,
  34096. 'Edieresis': 611,
  34097. 'Dcroat': 722,
  34098. 'commaaccent': 250,
  34099. 'copyright': 760,
  34100. 'Emacron': 611,
  34101. 'ccaron': 444,
  34102. 'aring': 500,
  34103. 'Ncommaaccent': 667,
  34104. 'lacute': 278,
  34105. 'agrave': 500,
  34106. 'Tcommaaccent': 556,
  34107. 'Cacute': 667,
  34108. 'atilde': 500,
  34109. 'Edotaccent': 611,
  34110. 'scaron': 389,
  34111. 'scedilla': 389,
  34112. 'iacute': 278,
  34113. 'lozenge': 471,
  34114. 'Rcaron': 611,
  34115. 'Gcommaaccent': 722,
  34116. 'ucircumflex': 500,
  34117. 'acircumflex': 500,
  34118. 'Amacron': 611,
  34119. 'rcaron': 389,
  34120. 'ccedilla': 444,
  34121. 'Zdotaccent': 556,
  34122. 'Thorn': 611,
  34123. 'Omacron': 722,
  34124. 'Racute': 611,
  34125. 'Sacute': 500,
  34126. 'dcaron': 544,
  34127. 'Umacron': 722,
  34128. 'uring': 500,
  34129. 'threesuperior': 300,
  34130. 'Ograve': 722,
  34131. 'Agrave': 611,
  34132. 'Abreve': 611,
  34133. 'multiply': 675,
  34134. 'uacute': 500,
  34135. 'Tcaron': 556,
  34136. 'partialdiff': 476,
  34137. 'ydieresis': 444,
  34138. 'Nacute': 667,
  34139. 'icircumflex': 278,
  34140. 'Ecircumflex': 611,
  34141. 'adieresis': 500,
  34142. 'edieresis': 444,
  34143. 'cacute': 444,
  34144. 'nacute': 500,
  34145. 'umacron': 500,
  34146. 'Ncaron': 667,
  34147. 'Iacute': 333,
  34148. 'plusminus': 675,
  34149. 'brokenbar': 275,
  34150. 'registered': 760,
  34151. 'Gbreve': 722,
  34152. 'Idotaccent': 333,
  34153. 'summation': 600,
  34154. 'Egrave': 611,
  34155. 'racute': 389,
  34156. 'omacron': 500,
  34157. 'Zacute': 556,
  34158. 'Zcaron': 556,
  34159. 'greaterequal': 549,
  34160. 'Eth': 722,
  34161. 'Ccedilla': 667,
  34162. 'lcommaaccent': 278,
  34163. 'tcaron': 300,
  34164. 'eogonek': 444,
  34165. 'Uogonek': 722,
  34166. 'Aacute': 611,
  34167. 'Adieresis': 611,
  34168. 'egrave': 444,
  34169. 'zacute': 389,
  34170. 'iogonek': 278,
  34171. 'Oacute': 722,
  34172. 'oacute': 500,
  34173. 'amacron': 500,
  34174. 'sacute': 389,
  34175. 'idieresis': 278,
  34176. 'Ocircumflex': 722,
  34177. 'Ugrave': 722,
  34178. 'Delta': 612,
  34179. 'thorn': 500,
  34180. 'twosuperior': 300,
  34181. 'Odieresis': 722,
  34182. 'mu': 500,
  34183. 'igrave': 278,
  34184. 'ohungarumlaut': 500,
  34185. 'Eogonek': 611,
  34186. 'dcroat': 500,
  34187. 'threequarters': 750,
  34188. 'Scedilla': 500,
  34189. 'lcaron': 300,
  34190. 'Kcommaaccent': 667,
  34191. 'Lacute': 556,
  34192. 'trademark': 980,
  34193. 'edotaccent': 444,
  34194. 'Igrave': 333,
  34195. 'Imacron': 333,
  34196. 'Lcaron': 611,
  34197. 'onehalf': 750,
  34198. 'lessequal': 549,
  34199. 'ocircumflex': 500,
  34200. 'ntilde': 500,
  34201. 'Uhungarumlaut': 722,
  34202. 'Eacute': 611,
  34203. 'emacron': 444,
  34204. 'gbreve': 500,
  34205. 'onequarter': 750,
  34206. 'Scaron': 500,
  34207. 'Scommaaccent': 500,
  34208. 'Ohungarumlaut': 722,
  34209. 'degree': 400,
  34210. 'ograve': 500,
  34211. 'Ccaron': 667,
  34212. 'ugrave': 500,
  34213. 'radical': 453,
  34214. 'Dcaron': 722,
  34215. 'rcommaaccent': 389,
  34216. 'Ntilde': 667,
  34217. 'otilde': 500,
  34218. 'Rcommaaccent': 611,
  34219. 'Lcommaaccent': 556,
  34220. 'Atilde': 611,
  34221. 'Aogonek': 611,
  34222. 'Aring': 611,
  34223. 'Otilde': 722,
  34224. 'zdotaccent': 389,
  34225. 'Ecaron': 611,
  34226. 'Iogonek': 333,
  34227. 'kcommaaccent': 444,
  34228. 'minus': 675,
  34229. 'Icircumflex': 333,
  34230. 'ncaron': 500,
  34231. 'tcommaaccent': 278,
  34232. 'logicalnot': 675,
  34233. 'odieresis': 500,
  34234. 'udieresis': 500,
  34235. 'notequal': 549,
  34236. 'gcommaaccent': 500,
  34237. 'eth': 500,
  34238. 'zcaron': 389,
  34239. 'ncommaaccent': 500,
  34240. 'onesuperior': 300,
  34241. 'imacron': 278,
  34242. 'Euro': 500
  34243. },
  34244. 'ZapfDingbats': {
  34245. 'space': 278,
  34246. 'a1': 974,
  34247. 'a2': 961,
  34248. 'a202': 974,
  34249. 'a3': 980,
  34250. 'a4': 719,
  34251. 'a5': 789,
  34252. 'a119': 790,
  34253. 'a118': 791,
  34254. 'a117': 690,
  34255. 'a11': 960,
  34256. 'a12': 939,
  34257. 'a13': 549,
  34258. 'a14': 855,
  34259. 'a15': 911,
  34260. 'a16': 933,
  34261. 'a105': 911,
  34262. 'a17': 945,
  34263. 'a18': 974,
  34264. 'a19': 755,
  34265. 'a20': 846,
  34266. 'a21': 762,
  34267. 'a22': 761,
  34268. 'a23': 571,
  34269. 'a24': 677,
  34270. 'a25': 763,
  34271. 'a26': 760,
  34272. 'a27': 759,
  34273. 'a28': 754,
  34274. 'a6': 494,
  34275. 'a7': 552,
  34276. 'a8': 537,
  34277. 'a9': 577,
  34278. 'a10': 692,
  34279. 'a29': 786,
  34280. 'a30': 788,
  34281. 'a31': 788,
  34282. 'a32': 790,
  34283. 'a33': 793,
  34284. 'a34': 794,
  34285. 'a35': 816,
  34286. 'a36': 823,
  34287. 'a37': 789,
  34288. 'a38': 841,
  34289. 'a39': 823,
  34290. 'a40': 833,
  34291. 'a41': 816,
  34292. 'a42': 831,
  34293. 'a43': 923,
  34294. 'a44': 744,
  34295. 'a45': 723,
  34296. 'a46': 749,
  34297. 'a47': 790,
  34298. 'a48': 792,
  34299. 'a49': 695,
  34300. 'a50': 776,
  34301. 'a51': 768,
  34302. 'a52': 792,
  34303. 'a53': 759,
  34304. 'a54': 707,
  34305. 'a55': 708,
  34306. 'a56': 682,
  34307. 'a57': 701,
  34308. 'a58': 826,
  34309. 'a59': 815,
  34310. 'a60': 789,
  34311. 'a61': 789,
  34312. 'a62': 707,
  34313. 'a63': 687,
  34314. 'a64': 696,
  34315. 'a65': 689,
  34316. 'a66': 786,
  34317. 'a67': 787,
  34318. 'a68': 713,
  34319. 'a69': 791,
  34320. 'a70': 785,
  34321. 'a71': 791,
  34322. 'a72': 873,
  34323. 'a73': 761,
  34324. 'a74': 762,
  34325. 'a203': 762,
  34326. 'a75': 759,
  34327. 'a204': 759,
  34328. 'a76': 892,
  34329. 'a77': 892,
  34330. 'a78': 788,
  34331. 'a79': 784,
  34332. 'a81': 438,
  34333. 'a82': 138,
  34334. 'a83': 277,
  34335. 'a84': 415,
  34336. 'a97': 392,
  34337. 'a98': 392,
  34338. 'a99': 668,
  34339. 'a100': 668,
  34340. 'a89': 390,
  34341. 'a90': 390,
  34342. 'a93': 317,
  34343. 'a94': 317,
  34344. 'a91': 276,
  34345. 'a92': 276,
  34346. 'a205': 509,
  34347. 'a85': 509,
  34348. 'a206': 410,
  34349. 'a86': 410,
  34350. 'a87': 234,
  34351. 'a88': 234,
  34352. 'a95': 334,
  34353. 'a96': 334,
  34354. 'a101': 732,
  34355. 'a102': 544,
  34356. 'a103': 544,
  34357. 'a104': 910,
  34358. 'a106': 667,
  34359. 'a107': 760,
  34360. 'a108': 760,
  34361. 'a112': 776,
  34362. 'a111': 595,
  34363. 'a110': 694,
  34364. 'a109': 626,
  34365. 'a120': 788,
  34366. 'a121': 788,
  34367. 'a122': 788,
  34368. 'a123': 788,
  34369. 'a124': 788,
  34370. 'a125': 788,
  34371. 'a126': 788,
  34372. 'a127': 788,
  34373. 'a128': 788,
  34374. 'a129': 788,
  34375. 'a130': 788,
  34376. 'a131': 788,
  34377. 'a132': 788,
  34378. 'a133': 788,
  34379. 'a134': 788,
  34380. 'a135': 788,
  34381. 'a136': 788,
  34382. 'a137': 788,
  34383. 'a138': 788,
  34384. 'a139': 788,
  34385. 'a140': 788,
  34386. 'a141': 788,
  34387. 'a142': 788,
  34388. 'a143': 788,
  34389. 'a144': 788,
  34390. 'a145': 788,
  34391. 'a146': 788,
  34392. 'a147': 788,
  34393. 'a148': 788,
  34394. 'a149': 788,
  34395. 'a150': 788,
  34396. 'a151': 788,
  34397. 'a152': 788,
  34398. 'a153': 788,
  34399. 'a154': 788,
  34400. 'a155': 788,
  34401. 'a156': 788,
  34402. 'a157': 788,
  34403. 'a158': 788,
  34404. 'a159': 788,
  34405. 'a160': 894,
  34406. 'a161': 838,
  34407. 'a163': 1016,
  34408. 'a164': 458,
  34409. 'a196': 748,
  34410. 'a165': 924,
  34411. 'a192': 748,
  34412. 'a166': 918,
  34413. 'a167': 927,
  34414. 'a168': 928,
  34415. 'a169': 928,
  34416. 'a170': 834,
  34417. 'a171': 873,
  34418. 'a172': 828,
  34419. 'a173': 924,
  34420. 'a162': 924,
  34421. 'a174': 917,
  34422. 'a175': 930,
  34423. 'a176': 931,
  34424. 'a177': 463,
  34425. 'a178': 883,
  34426. 'a179': 836,
  34427. 'a193': 836,
  34428. 'a180': 867,
  34429. 'a199': 867,
  34430. 'a181': 696,
  34431. 'a200': 696,
  34432. 'a182': 874,
  34433. 'a201': 874,
  34434. 'a183': 760,
  34435. 'a184': 946,
  34436. 'a197': 771,
  34437. 'a185': 865,
  34438. 'a194': 771,
  34439. 'a198': 888,
  34440. 'a186': 967,
  34441. 'a195': 888,
  34442. 'a187': 831,
  34443. 'a188': 873,
  34444. 'a189': 927,
  34445. 'a190': 970,
  34446. 'a191': 918
  34447. }
  34448. };
  34449. var EOF = {};
  34450. function isEOF(v) {
  34451. return (v === EOF);
  34452. }
  34453. var MAX_LENGTH_TO_CACHE = 1000;
  34454. var Parser = (function ParserClosure() {
  34455. function Parser(lexer, allowStreams, xref) {
  34456. this.lexer = lexer;
  34457. this.allowStreams = allowStreams;
  34458. this.xref = xref;
  34459. this.imageCache = {};
  34460. this.refill();
  34461. }
  34462. Parser.prototype = {
  34463. refill: function Parser_refill() {
  34464. this.buf1 = this.lexer.getObj();
  34465. this.buf2 = this.lexer.getObj();
  34466. },
  34467. shift: function Parser_shift() {
  34468. if (isCmd(this.buf2, 'ID')) {
  34469. this.buf1 = this.buf2;
  34470. this.buf2 = null;
  34471. } else {
  34472. this.buf1 = this.buf2;
  34473. this.buf2 = this.lexer.getObj();
  34474. }
  34475. },
  34476. tryShift: function Parser_tryShift() {
  34477. try {
  34478. this.shift();
  34479. return true;
  34480. } catch (e) {
  34481. if (e instanceof MissingDataException) {
  34482. throw e;
  34483. }
  34484. // Upon failure, the caller should reset this.lexer.pos to a known good
  34485. // state and call this.shift() twice to reset the buffers.
  34486. return false;
  34487. }
  34488. },
  34489. getObj: function Parser_getObj(cipherTransform) {
  34490. var buf1 = this.buf1;
  34491. this.shift();
  34492. if (buf1 instanceof Cmd) {
  34493. switch (buf1.cmd) {
  34494. case 'BI': // inline image
  34495. return this.makeInlineImage(cipherTransform);
  34496. case '[': // array
  34497. var array = [];
  34498. while (!isCmd(this.buf1, ']') && !isEOF(this.buf1)) {
  34499. array.push(this.getObj(cipherTransform));
  34500. }
  34501. if (isEOF(this.buf1)) {
  34502. error('End of file inside array');
  34503. }
  34504. this.shift();
  34505. return array;
  34506. case '<<': // dictionary or stream
  34507. var dict = new Dict(this.xref);
  34508. while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) {
  34509. if (!isName(this.buf1)) {
  34510. info('Malformed dictionary: key must be a name object');
  34511. this.shift();
  34512. continue;
  34513. }
  34514. var key = this.buf1.name;
  34515. this.shift();
  34516. if (isEOF(this.buf1)) {
  34517. break;
  34518. }
  34519. dict.set(key, this.getObj(cipherTransform));
  34520. }
  34521. if (isEOF(this.buf1)) {
  34522. error('End of file inside dictionary');
  34523. }
  34524. // Stream objects are not allowed inside content streams or
  34525. // object streams.
  34526. if (isCmd(this.buf2, 'stream')) {
  34527. return (this.allowStreams ?
  34528. this.makeStream(dict, cipherTransform) : dict);
  34529. }
  34530. this.shift();
  34531. return dict;
  34532. default: // simple object
  34533. return buf1;
  34534. }
  34535. }
  34536. if (isInt(buf1)) { // indirect reference or integer
  34537. var num = buf1;
  34538. if (isInt(this.buf1) && isCmd(this.buf2, 'R')) {
  34539. var ref = new Ref(num, this.buf1);
  34540. this.shift();
  34541. this.shift();
  34542. return ref;
  34543. }
  34544. return num;
  34545. }
  34546. if (isString(buf1)) { // string
  34547. var str = buf1;
  34548. if (cipherTransform) {
  34549. str = cipherTransform.decryptString(str);
  34550. }
  34551. return str;
  34552. }
  34553. // simple object
  34554. return buf1;
  34555. },
  34556. /**
  34557. * Find the end of the stream by searching for the /EI\s/.
  34558. * @returns {number} The inline stream length.
  34559. */
  34560. findDefaultInlineStreamEnd:
  34561. function Parser_findDefaultInlineStreamEnd(stream) {
  34562. var E = 0x45, I = 0x49, SPACE = 0x20, LF = 0xA, CR = 0xD;
  34563. var startPos = stream.pos, state = 0, ch, i, n, followingBytes;
  34564. while ((ch = stream.getByte()) !== -1) {
  34565. if (state === 0) {
  34566. state = (ch === E) ? 1 : 0;
  34567. } else if (state === 1) {
  34568. state = (ch === I) ? 2 : 0;
  34569. } else {
  34570. assert(state === 2);
  34571. if (ch === SPACE || ch === LF || ch === CR) {
  34572. // Let's check the next five bytes are ASCII... just be sure.
  34573. n = 5;
  34574. followingBytes = stream.peekBytes(n);
  34575. for (i = 0; i < n; i++) {
  34576. ch = followingBytes[i];
  34577. if (ch !== LF && ch !== CR && (ch < SPACE || ch > 0x7F)) {
  34578. // Not a LF, CR, SPACE or any visible ASCII character, i.e.
  34579. // it's binary stuff. Resetting the state.
  34580. state = 0;
  34581. break;
  34582. }
  34583. }
  34584. if (state === 2) {
  34585. break; // Finished!
  34586. }
  34587. } else {
  34588. state = 0;
  34589. }
  34590. }
  34591. }
  34592. return ((stream.pos - 4) - startPos);
  34593. },
  34594. /**
  34595. * Find the EOI (end-of-image) marker 0xFFD9 of the stream.
  34596. * @returns {number} The inline stream length.
  34597. */
  34598. findDCTDecodeInlineStreamEnd:
  34599. function Parser_findDCTDecodeInlineStreamEnd(stream) {
  34600. var startPos = stream.pos, foundEOI = false, b, markerLength, length;
  34601. while ((b = stream.getByte()) !== -1) {
  34602. if (b !== 0xFF) { // Not a valid marker.
  34603. continue;
  34604. }
  34605. switch (stream.getByte()) {
  34606. case 0x00: // Byte stuffing.
  34607. // 0xFF00 appears to be a very common byte sequence in JPEG images.
  34608. break;
  34609. case 0xFF: // Fill byte.
  34610. // Avoid skipping a valid marker, resetting the stream position.
  34611. stream.skip(-1);
  34612. break;
  34613. case 0xD9: // EOI
  34614. foundEOI = true;
  34615. break;
  34616. case 0xC0: // SOF0
  34617. case 0xC1: // SOF1
  34618. case 0xC2: // SOF2
  34619. case 0xC3: // SOF3
  34620. case 0xC5: // SOF5
  34621. case 0xC6: // SOF6
  34622. case 0xC7: // SOF7
  34623. case 0xC9: // SOF9
  34624. case 0xCA: // SOF10
  34625. case 0xCB: // SOF11
  34626. case 0xCD: // SOF13
  34627. case 0xCE: // SOF14
  34628. case 0xCF: // SOF15
  34629. case 0xC4: // DHT
  34630. case 0xCC: // DAC
  34631. case 0xDA: // SOS
  34632. case 0xDB: // DQT
  34633. case 0xDC: // DNL
  34634. case 0xDD: // DRI
  34635. case 0xDE: // DHP
  34636. case 0xDF: // EXP
  34637. case 0xE0: // APP0
  34638. case 0xE1: // APP1
  34639. case 0xE2: // APP2
  34640. case 0xE3: // APP3
  34641. case 0xE4: // APP4
  34642. case 0xE5: // APP5
  34643. case 0xE6: // APP6
  34644. case 0xE7: // APP7
  34645. case 0xE8: // APP8
  34646. case 0xE9: // APP9
  34647. case 0xEA: // APP10
  34648. case 0xEB: // APP11
  34649. case 0xEC: // APP12
  34650. case 0xED: // APP13
  34651. case 0xEE: // APP14
  34652. case 0xEF: // APP15
  34653. case 0xFE: // COM
  34654. // The marker should be followed by the length of the segment.
  34655. markerLength = stream.getUint16();
  34656. if (markerLength > 2) {
  34657. // |markerLength| contains the byte length of the marker segment,
  34658. // including its own length (2 bytes) and excluding the marker.
  34659. stream.skip(markerLength - 2); // Jump to the next marker.
  34660. } else {
  34661. // The marker length is invalid, resetting the stream position.
  34662. stream.skip(-2);
  34663. }
  34664. break;
  34665. }
  34666. if (foundEOI) {
  34667. break;
  34668. }
  34669. }
  34670. length = stream.pos - startPos;
  34671. if (b === -1) {
  34672. warn('Inline DCTDecode image stream: ' +
  34673. 'EOI marker not found, searching for /EI/ instead.');
  34674. stream.skip(-length); // Reset the stream position.
  34675. return this.findDefaultInlineStreamEnd(stream);
  34676. }
  34677. this.inlineStreamSkipEI(stream);
  34678. return length;
  34679. },
  34680. /**
  34681. * Find the EOD (end-of-data) marker '~>' (i.e. TILDE + GT) of the stream.
  34682. * @returns {number} The inline stream length.
  34683. */
  34684. findASCII85DecodeInlineStreamEnd:
  34685. function Parser_findASCII85DecodeInlineStreamEnd(stream) {
  34686. var TILDE = 0x7E, GT = 0x3E;
  34687. var startPos = stream.pos, ch, length;
  34688. while ((ch = stream.getByte()) !== -1) {
  34689. if (ch === TILDE && stream.peekByte() === GT) {
  34690. stream.skip();
  34691. break;
  34692. }
  34693. }
  34694. length = stream.pos - startPos;
  34695. if (ch === -1) {
  34696. warn('Inline ASCII85Decode image stream: ' +
  34697. 'EOD marker not found, searching for /EI/ instead.');
  34698. stream.skip(-length); // Reset the stream position.
  34699. return this.findDefaultInlineStreamEnd(stream);
  34700. }
  34701. this.inlineStreamSkipEI(stream);
  34702. return length;
  34703. },
  34704. /**
  34705. * Find the EOD (end-of-data) marker '>' (i.e. GT) of the stream.
  34706. * @returns {number} The inline stream length.
  34707. */
  34708. findASCIIHexDecodeInlineStreamEnd:
  34709. function Parser_findASCIIHexDecodeInlineStreamEnd(stream) {
  34710. var GT = 0x3E;
  34711. var startPos = stream.pos, ch, length;
  34712. while ((ch = stream.getByte()) !== -1) {
  34713. if (ch === GT) {
  34714. break;
  34715. }
  34716. }
  34717. length = stream.pos - startPos;
  34718. if (ch === -1) {
  34719. warn('Inline ASCIIHexDecode image stream: ' +
  34720. 'EOD marker not found, searching for /EI/ instead.');
  34721. stream.skip(-length); // Reset the stream position.
  34722. return this.findDefaultInlineStreamEnd(stream);
  34723. }
  34724. this.inlineStreamSkipEI(stream);
  34725. return length;
  34726. },
  34727. /**
  34728. * Skip over the /EI/ for streams where we search for an EOD marker.
  34729. */
  34730. inlineStreamSkipEI: function Parser_inlineStreamSkipEI(stream) {
  34731. var E = 0x45, I = 0x49;
  34732. var state = 0, ch;
  34733. while ((ch = stream.getByte()) !== -1) {
  34734. if (state === 0) {
  34735. state = (ch === E) ? 1 : 0;
  34736. } else if (state === 1) {
  34737. state = (ch === I) ? 2 : 0;
  34738. } else if (state === 2) {
  34739. break;
  34740. }
  34741. }
  34742. },
  34743. makeInlineImage: function Parser_makeInlineImage(cipherTransform) {
  34744. var lexer = this.lexer;
  34745. var stream = lexer.stream;
  34746. // Parse dictionary.
  34747. var dict = new Dict(this.xref);
  34748. while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) {
  34749. if (!isName(this.buf1)) {
  34750. error('Dictionary key must be a name object');
  34751. }
  34752. var key = this.buf1.name;
  34753. this.shift();
  34754. if (isEOF(this.buf1)) {
  34755. break;
  34756. }
  34757. dict.set(key, this.getObj(cipherTransform));
  34758. }
  34759. // Extract the name of the first (i.e. the current) image filter.
  34760. var filter = dict.get('Filter', 'F'), filterName;
  34761. if (isName(filter)) {
  34762. filterName = filter.name;
  34763. } else if (isArray(filter) && isName(filter[0])) {
  34764. filterName = filter[0].name;
  34765. }
  34766. // Parse image stream.
  34767. var startPos = stream.pos, length, i, ii;
  34768. if (filterName === 'DCTDecode' || filterName === 'DCT') {
  34769. length = this.findDCTDecodeInlineStreamEnd(stream);
  34770. } else if (filterName === 'ASCII85Decide' || filterName === 'A85') {
  34771. length = this.findASCII85DecodeInlineStreamEnd(stream);
  34772. } else if (filterName === 'ASCIIHexDecode' || filterName === 'AHx') {
  34773. length = this.findASCIIHexDecodeInlineStreamEnd(stream);
  34774. } else {
  34775. length = this.findDefaultInlineStreamEnd(stream);
  34776. }
  34777. var imageStream = stream.makeSubStream(startPos, length, dict);
  34778. // Cache all images below the MAX_LENGTH_TO_CACHE threshold by their
  34779. // adler32 checksum.
  34780. var adler32;
  34781. if (length < MAX_LENGTH_TO_CACHE) {
  34782. var imageBytes = imageStream.getBytes();
  34783. imageStream.reset();
  34784. var a = 1;
  34785. var b = 0;
  34786. for (i = 0, ii = imageBytes.length; i < ii; ++i) {
  34787. // No modulo required in the loop if imageBytes.length < 5552.
  34788. a += imageBytes[i] & 0xff;
  34789. b += a;
  34790. }
  34791. adler32 = ((b % 65521) << 16) | (a % 65521);
  34792. if (this.imageCache.adler32 === adler32) {
  34793. this.buf2 = Cmd.get('EI');
  34794. this.shift();
  34795. this.imageCache[adler32].reset();
  34796. return this.imageCache[adler32];
  34797. }
  34798. }
  34799. if (cipherTransform) {
  34800. imageStream = cipherTransform.createStream(imageStream, length);
  34801. }
  34802. imageStream = this.filter(imageStream, dict, length);
  34803. imageStream.dict = dict;
  34804. if (adler32 !== undefined) {
  34805. imageStream.cacheKey = 'inline_' + length + '_' + adler32;
  34806. this.imageCache[adler32] = imageStream;
  34807. }
  34808. this.buf2 = Cmd.get('EI');
  34809. this.shift();
  34810. return imageStream;
  34811. },
  34812. makeStream: function Parser_makeStream(dict, cipherTransform) {
  34813. var lexer = this.lexer;
  34814. var stream = lexer.stream;
  34815. // get stream start position
  34816. lexer.skipToNextLine();
  34817. var pos = stream.pos - 1;
  34818. // get length
  34819. var length = dict.get('Length');
  34820. if (!isInt(length)) {
  34821. info('Bad ' + length + ' attribute in stream');
  34822. length = 0;
  34823. }
  34824. // skip over the stream data
  34825. stream.pos = pos + length;
  34826. lexer.nextChar();
  34827. // Shift '>>' and check whether the new object marks the end of the stream
  34828. if (this.tryShift() && isCmd(this.buf2, 'endstream')) {
  34829. this.shift(); // 'stream'
  34830. } else {
  34831. // bad stream length, scanning for endstream
  34832. stream.pos = pos;
  34833. var SCAN_BLOCK_SIZE = 2048;
  34834. var ENDSTREAM_SIGNATURE_LENGTH = 9;
  34835. var ENDSTREAM_SIGNATURE = [0x65, 0x6E, 0x64, 0x73, 0x74, 0x72, 0x65,
  34836. 0x61, 0x6D];
  34837. var skipped = 0, found = false, i, j;
  34838. while (stream.pos < stream.end) {
  34839. var scanBytes = stream.peekBytes(SCAN_BLOCK_SIZE);
  34840. var scanLength = scanBytes.length - ENDSTREAM_SIGNATURE_LENGTH;
  34841. if (scanLength <= 0) {
  34842. break;
  34843. }
  34844. found = false;
  34845. for (i = 0, j = 0; i < scanLength; i++) {
  34846. var b = scanBytes[i];
  34847. if (b !== ENDSTREAM_SIGNATURE[j]) {
  34848. i -= j;
  34849. j = 0;
  34850. } else {
  34851. j++;
  34852. if (j >= ENDSTREAM_SIGNATURE_LENGTH) {
  34853. i++;
  34854. found = true;
  34855. break;
  34856. }
  34857. }
  34858. }
  34859. if (found) {
  34860. skipped += i - ENDSTREAM_SIGNATURE_LENGTH;
  34861. stream.pos += i - ENDSTREAM_SIGNATURE_LENGTH;
  34862. break;
  34863. }
  34864. skipped += scanLength;
  34865. stream.pos += scanLength;
  34866. }
  34867. if (!found) {
  34868. error('Missing endstream');
  34869. }
  34870. length = skipped;
  34871. lexer.nextChar();
  34872. this.shift();
  34873. this.shift();
  34874. }
  34875. this.shift(); // 'endstream'
  34876. stream = stream.makeSubStream(pos, length, dict);
  34877. if (cipherTransform) {
  34878. stream = cipherTransform.createStream(stream, length);
  34879. }
  34880. stream = this.filter(stream, dict, length);
  34881. stream.dict = dict;
  34882. return stream;
  34883. },
  34884. filter: function Parser_filter(stream, dict, length) {
  34885. var filter = dict.get('Filter', 'F');
  34886. var params = dict.get('DecodeParms', 'DP');
  34887. if (isName(filter)) {
  34888. return this.makeFilter(stream, filter.name, length, params);
  34889. }
  34890. var maybeLength = length;
  34891. if (isArray(filter)) {
  34892. var filterArray = filter;
  34893. var paramsArray = params;
  34894. for (var i = 0, ii = filterArray.length; i < ii; ++i) {
  34895. filter = filterArray[i];
  34896. if (!isName(filter)) {
  34897. error('Bad filter name: ' + filter);
  34898. }
  34899. params = null;
  34900. if (isArray(paramsArray) && (i in paramsArray)) {
  34901. params = paramsArray[i];
  34902. }
  34903. stream = this.makeFilter(stream, filter.name, maybeLength, params);
  34904. // after the first stream the length variable is invalid
  34905. maybeLength = null;
  34906. }
  34907. }
  34908. return stream;
  34909. },
  34910. makeFilter: function Parser_makeFilter(stream, name, maybeLength, params) {
  34911. if (stream.dict.get('Length') === 0 && !maybeLength) {
  34912. warn('Empty "' + name + '" stream.');
  34913. return new NullStream(stream);
  34914. }
  34915. try {
  34916. if (params && this.xref) {
  34917. params = this.xref.fetchIfRef(params);
  34918. }
  34919. var xrefStreamStats = this.xref.stats.streamTypes;
  34920. if (name === 'FlateDecode' || name === 'Fl') {
  34921. xrefStreamStats[StreamType.FLATE] = true;
  34922. if (params) {
  34923. return new PredictorStream(new FlateStream(stream, maybeLength),
  34924. maybeLength, params);
  34925. }
  34926. return new FlateStream(stream, maybeLength);
  34927. }
  34928. if (name === 'LZWDecode' || name === 'LZW') {
  34929. xrefStreamStats[StreamType.LZW] = true;
  34930. var earlyChange = 1;
  34931. if (params) {
  34932. if (params.has('EarlyChange')) {
  34933. earlyChange = params.get('EarlyChange');
  34934. }
  34935. return new PredictorStream(
  34936. new LZWStream(stream, maybeLength, earlyChange),
  34937. maybeLength, params);
  34938. }
  34939. return new LZWStream(stream, maybeLength, earlyChange);
  34940. }
  34941. if (name === 'DCTDecode' || name === 'DCT') {
  34942. xrefStreamStats[StreamType.DCT] = true;
  34943. return new JpegStream(stream, maybeLength, stream.dict, this.xref);
  34944. }
  34945. if (name === 'JPXDecode' || name === 'JPX') {
  34946. xrefStreamStats[StreamType.JPX] = true;
  34947. return new JpxStream(stream, maybeLength, stream.dict);
  34948. }
  34949. if (name === 'ASCII85Decode' || name === 'A85') {
  34950. xrefStreamStats[StreamType.A85] = true;
  34951. return new Ascii85Stream(stream, maybeLength);
  34952. }
  34953. if (name === 'ASCIIHexDecode' || name === 'AHx') {
  34954. xrefStreamStats[StreamType.AHX] = true;
  34955. return new AsciiHexStream(stream, maybeLength);
  34956. }
  34957. if (name === 'CCITTFaxDecode' || name === 'CCF') {
  34958. xrefStreamStats[StreamType.CCF] = true;
  34959. return new CCITTFaxStream(stream, maybeLength, params);
  34960. }
  34961. if (name === 'RunLengthDecode' || name === 'RL') {
  34962. xrefStreamStats[StreamType.RL] = true;
  34963. return new RunLengthStream(stream, maybeLength);
  34964. }
  34965. if (name === 'JBIG2Decode') {
  34966. xrefStreamStats[StreamType.JBIG] = true;
  34967. return new Jbig2Stream(stream, maybeLength, stream.dict);
  34968. }
  34969. warn('filter "' + name + '" not supported yet');
  34970. return stream;
  34971. } catch (ex) {
  34972. if (ex instanceof MissingDataException) {
  34973. throw ex;
  34974. }
  34975. warn('Invalid stream: \"' + ex + '\"');
  34976. return new NullStream(stream);
  34977. }
  34978. }
  34979. };
  34980. return Parser;
  34981. })();
  34982. var Lexer = (function LexerClosure() {
  34983. function Lexer(stream, knownCommands) {
  34984. this.stream = stream;
  34985. this.nextChar();
  34986. // While lexing, we build up many strings one char at a time. Using += for
  34987. // this can result in lots of garbage strings. It's better to build an
  34988. // array of single-char strings and then join() them together at the end.
  34989. // And reusing a single array (i.e. |this.strBuf|) over and over for this
  34990. // purpose uses less memory than using a new array for each string.
  34991. this.strBuf = [];
  34992. // The PDFs might have "glued" commands with other commands, operands or
  34993. // literals, e.g. "q1". The knownCommands is a dictionary of the valid
  34994. // commands and their prefixes. The prefixes are built the following way:
  34995. // if there a command that is a prefix of the other valid command or
  34996. // literal (e.g. 'f' and 'false') the following prefixes must be included,
  34997. // 'fa', 'fal', 'fals'. The prefixes are not needed, if the command has no
  34998. // other commands or literals as a prefix. The knowCommands is optional.
  34999. this.knownCommands = knownCommands;
  35000. }
  35001. Lexer.isSpace = function Lexer_isSpace(ch) {
  35002. // Space is one of the following characters: SPACE, TAB, CR or LF.
  35003. return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
  35004. };
  35005. // A '1' in this array means the character is white space. A '1' or
  35006. // '2' means the character ends a name or command.
  35007. var specialChars = [
  35008. 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x
  35009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
  35010. 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x
  35011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x
  35012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x
  35013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x
  35014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x
  35015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x
  35016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x
  35017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x
  35018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax
  35019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx
  35020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx
  35021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx
  35022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex
  35023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx
  35024. ];
  35025. function toHexDigit(ch) {
  35026. if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
  35027. return ch & 0x0F;
  35028. }
  35029. if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
  35030. // 'A'-'F', 'a'-'f'
  35031. return (ch & 0x0F) + 9;
  35032. }
  35033. return -1;
  35034. }
  35035. Lexer.prototype = {
  35036. nextChar: function Lexer_nextChar() {
  35037. return (this.currentChar = this.stream.getByte());
  35038. },
  35039. peekChar: function Lexer_peekChar() {
  35040. return this.stream.peekByte();
  35041. },
  35042. getNumber: function Lexer_getNumber() {
  35043. var ch = this.currentChar;
  35044. var eNotation = false;
  35045. var divideBy = 0; // different from 0 if it's a floating point value
  35046. var sign = 1;
  35047. if (ch === 0x2D) { // '-'
  35048. sign = -1;
  35049. ch = this.nextChar();
  35050. if (ch === 0x2D) { // '-'
  35051. // Ignore double negative (this is consistent with Adobe Reader).
  35052. ch = this.nextChar();
  35053. }
  35054. } else if (ch === 0x2B) { // '+'
  35055. ch = this.nextChar();
  35056. }
  35057. if (ch === 0x2E) { // '.'
  35058. divideBy = 10;
  35059. ch = this.nextChar();
  35060. }
  35061. if (ch < 0x30 || ch > 0x39) { // '0' - '9'
  35062. error('Invalid number: ' + String.fromCharCode(ch));
  35063. return 0;
  35064. }
  35065. var baseValue = ch - 0x30; // '0'
  35066. var powerValue = 0;
  35067. var powerValueSign = 1;
  35068. while ((ch = this.nextChar()) >= 0) {
  35069. if (0x30 <= ch && ch <= 0x39) { // '0' - '9'
  35070. var currentDigit = ch - 0x30; // '0'
  35071. if (eNotation) { // We are after an 'e' or 'E'
  35072. powerValue = powerValue * 10 + currentDigit;
  35073. } else {
  35074. if (divideBy !== 0) { // We are after a point
  35075. divideBy *= 10;
  35076. }
  35077. baseValue = baseValue * 10 + currentDigit;
  35078. }
  35079. } else if (ch === 0x2E) { // '.'
  35080. if (divideBy === 0) {
  35081. divideBy = 1;
  35082. } else {
  35083. // A number can have only one '.'
  35084. break;
  35085. }
  35086. } else if (ch === 0x2D) { // '-'
  35087. // ignore minus signs in the middle of numbers to match
  35088. // Adobe's behavior
  35089. warn('Badly formated number');
  35090. } else if (ch === 0x45 || ch === 0x65) { // 'E', 'e'
  35091. // 'E' can be either a scientific notation or the beginning of a new
  35092. // operator
  35093. ch = this.peekChar();
  35094. if (ch === 0x2B || ch === 0x2D) { // '+', '-'
  35095. powerValueSign = (ch === 0x2D) ? -1 : 1;
  35096. this.nextChar(); // Consume the sign character
  35097. } else if (ch < 0x30 || ch > 0x39) { // '0' - '9'
  35098. // The 'E' must be the beginning of a new operator
  35099. break;
  35100. }
  35101. eNotation = true;
  35102. } else {
  35103. // the last character doesn't belong to us
  35104. break;
  35105. }
  35106. }
  35107. if (divideBy !== 0) {
  35108. baseValue /= divideBy;
  35109. }
  35110. if (eNotation) {
  35111. baseValue *= Math.pow(10, powerValueSign * powerValue);
  35112. }
  35113. return sign * baseValue;
  35114. },
  35115. getString: function Lexer_getString() {
  35116. var numParen = 1;
  35117. var done = false;
  35118. var strBuf = this.strBuf;
  35119. strBuf.length = 0;
  35120. var ch = this.nextChar();
  35121. while (true) {
  35122. var charBuffered = false;
  35123. switch (ch | 0) {
  35124. case -1:
  35125. warn('Unterminated string');
  35126. done = true;
  35127. break;
  35128. case 0x28: // '('
  35129. ++numParen;
  35130. strBuf.push('(');
  35131. break;
  35132. case 0x29: // ')'
  35133. if (--numParen === 0) {
  35134. this.nextChar(); // consume strings ')'
  35135. done = true;
  35136. } else {
  35137. strBuf.push(')');
  35138. }
  35139. break;
  35140. case 0x5C: // '\\'
  35141. ch = this.nextChar();
  35142. switch (ch) {
  35143. case -1:
  35144. warn('Unterminated string');
  35145. done = true;
  35146. break;
  35147. case 0x6E: // 'n'
  35148. strBuf.push('\n');
  35149. break;
  35150. case 0x72: // 'r'
  35151. strBuf.push('\r');
  35152. break;
  35153. case 0x74: // 't'
  35154. strBuf.push('\t');
  35155. break;
  35156. case 0x62: // 'b'
  35157. strBuf.push('\b');
  35158. break;
  35159. case 0x66: // 'f'
  35160. strBuf.push('\f');
  35161. break;
  35162. case 0x5C: // '\'
  35163. case 0x28: // '('
  35164. case 0x29: // ')'
  35165. strBuf.push(String.fromCharCode(ch));
  35166. break;
  35167. case 0x30: case 0x31: case 0x32: case 0x33: // '0'-'3'
  35168. case 0x34: case 0x35: case 0x36: case 0x37: // '4'-'7'
  35169. var x = ch & 0x0F;
  35170. ch = this.nextChar();
  35171. charBuffered = true;
  35172. if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'
  35173. x = (x << 3) + (ch & 0x0F);
  35174. ch = this.nextChar();
  35175. if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'
  35176. charBuffered = false;
  35177. x = (x << 3) + (ch & 0x0F);
  35178. }
  35179. }
  35180. strBuf.push(String.fromCharCode(x));
  35181. break;
  35182. case 0x0D: // CR
  35183. if (this.peekChar() === 0x0A) { // LF
  35184. this.nextChar();
  35185. }
  35186. break;
  35187. case 0x0A: // LF
  35188. break;
  35189. default:
  35190. strBuf.push(String.fromCharCode(ch));
  35191. break;
  35192. }
  35193. break;
  35194. default:
  35195. strBuf.push(String.fromCharCode(ch));
  35196. break;
  35197. }
  35198. if (done) {
  35199. break;
  35200. }
  35201. if (!charBuffered) {
  35202. ch = this.nextChar();
  35203. }
  35204. }
  35205. return strBuf.join('');
  35206. },
  35207. getName: function Lexer_getName() {
  35208. var ch;
  35209. var strBuf = this.strBuf;
  35210. strBuf.length = 0;
  35211. while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
  35212. if (ch === 0x23) { // '#'
  35213. ch = this.nextChar();
  35214. var x = toHexDigit(ch);
  35215. if (x !== -1) {
  35216. var x2 = toHexDigit(this.nextChar());
  35217. if (x2 === -1) {
  35218. error('Illegal digit in hex char in name: ' + x2);
  35219. }
  35220. strBuf.push(String.fromCharCode((x << 4) | x2));
  35221. } else {
  35222. strBuf.push('#', String.fromCharCode(ch));
  35223. }
  35224. } else {
  35225. strBuf.push(String.fromCharCode(ch));
  35226. }
  35227. }
  35228. if (strBuf.length > 127) {
  35229. warn('name token is longer than allowed by the spec: ' + strBuf.length);
  35230. }
  35231. return Name.get(strBuf.join(''));
  35232. },
  35233. getHexString: function Lexer_getHexString() {
  35234. var strBuf = this.strBuf;
  35235. strBuf.length = 0;
  35236. var ch = this.currentChar;
  35237. var isFirstHex = true;
  35238. var firstDigit;
  35239. var secondDigit;
  35240. while (true) {
  35241. if (ch < 0) {
  35242. warn('Unterminated hex string');
  35243. break;
  35244. } else if (ch === 0x3E) { // '>'
  35245. this.nextChar();
  35246. break;
  35247. } else if (specialChars[ch] === 1) {
  35248. ch = this.nextChar();
  35249. continue;
  35250. } else {
  35251. if (isFirstHex) {
  35252. firstDigit = toHexDigit(ch);
  35253. if (firstDigit === -1) {
  35254. warn('Ignoring invalid character "' + ch + '" in hex string');
  35255. ch = this.nextChar();
  35256. continue;
  35257. }
  35258. } else {
  35259. secondDigit = toHexDigit(ch);
  35260. if (secondDigit === -1) {
  35261. warn('Ignoring invalid character "' + ch + '" in hex string');
  35262. ch = this.nextChar();
  35263. continue;
  35264. }
  35265. strBuf.push(String.fromCharCode((firstDigit << 4) | secondDigit));
  35266. }
  35267. isFirstHex = !isFirstHex;
  35268. ch = this.nextChar();
  35269. }
  35270. }
  35271. return strBuf.join('');
  35272. },
  35273. getObj: function Lexer_getObj() {
  35274. // skip whitespace and comments
  35275. var comment = false;
  35276. var ch = this.currentChar;
  35277. while (true) {
  35278. if (ch < 0) {
  35279. return EOF;
  35280. }
  35281. if (comment) {
  35282. if (ch === 0x0A || ch === 0x0D) { // LF, CR
  35283. comment = false;
  35284. }
  35285. } else if (ch === 0x25) { // '%'
  35286. comment = true;
  35287. } else if (specialChars[ch] !== 1) {
  35288. break;
  35289. }
  35290. ch = this.nextChar();
  35291. }
  35292. // start reading token
  35293. switch (ch | 0) {
  35294. case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'
  35295. case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'
  35296. case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'
  35297. return this.getNumber();
  35298. case 0x28: // '('
  35299. return this.getString();
  35300. case 0x2F: // '/'
  35301. return this.getName();
  35302. // array punctuation
  35303. case 0x5B: // '['
  35304. this.nextChar();
  35305. return Cmd.get('[');
  35306. case 0x5D: // ']'
  35307. this.nextChar();
  35308. return Cmd.get(']');
  35309. // hex string or dict punctuation
  35310. case 0x3C: // '<'
  35311. ch = this.nextChar();
  35312. if (ch === 0x3C) {
  35313. // dict punctuation
  35314. this.nextChar();
  35315. return Cmd.get('<<');
  35316. }
  35317. return this.getHexString();
  35318. // dict punctuation
  35319. case 0x3E: // '>'
  35320. ch = this.nextChar();
  35321. if (ch === 0x3E) {
  35322. this.nextChar();
  35323. return Cmd.get('>>');
  35324. }
  35325. return Cmd.get('>');
  35326. case 0x7B: // '{'
  35327. this.nextChar();
  35328. return Cmd.get('{');
  35329. case 0x7D: // '}'
  35330. this.nextChar();
  35331. return Cmd.get('}');
  35332. case 0x29: // ')'
  35333. error('Illegal character: ' + ch);
  35334. break;
  35335. }
  35336. // command
  35337. var str = String.fromCharCode(ch);
  35338. var knownCommands = this.knownCommands;
  35339. var knownCommandFound = knownCommands && knownCommands[str] !== undefined;
  35340. while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
  35341. // stop if known command is found and next character does not make
  35342. // the str a command
  35343. var possibleCommand = str + String.fromCharCode(ch);
  35344. if (knownCommandFound && knownCommands[possibleCommand] === undefined) {
  35345. break;
  35346. }
  35347. if (str.length === 128) {
  35348. error('Command token too long: ' + str.length);
  35349. }
  35350. str = possibleCommand;
  35351. knownCommandFound = knownCommands && knownCommands[str] !== undefined;
  35352. }
  35353. if (str === 'true') {
  35354. return true;
  35355. }
  35356. if (str === 'false') {
  35357. return false;
  35358. }
  35359. if (str === 'null') {
  35360. return null;
  35361. }
  35362. return Cmd.get(str);
  35363. },
  35364. skipToNextLine: function Lexer_skipToNextLine() {
  35365. var ch = this.currentChar;
  35366. while (ch >= 0) {
  35367. if (ch === 0x0D) { // CR
  35368. ch = this.nextChar();
  35369. if (ch === 0x0A) { // LF
  35370. this.nextChar();
  35371. }
  35372. break;
  35373. } else if (ch === 0x0A) { // LF
  35374. this.nextChar();
  35375. break;
  35376. }
  35377. ch = this.nextChar();
  35378. }
  35379. }
  35380. };
  35381. return Lexer;
  35382. })();
  35383. var Linearization = {
  35384. create: function LinearizationCreate(stream) {
  35385. function getInt(name, allowZeroValue) {
  35386. var obj = linDict.get(name);
  35387. if (isInt(obj) && (allowZeroValue ? obj >= 0 : obj > 0)) {
  35388. return obj;
  35389. }
  35390. throw new Error('The "' + name + '" parameter in the linearization ' +
  35391. 'dictionary is invalid.');
  35392. }
  35393. function getHints() {
  35394. var hints = linDict.get('H'), hintsLength, item;
  35395. if (isArray(hints) &&
  35396. ((hintsLength = hints.length) === 2 || hintsLength === 4)) {
  35397. for (var index = 0; index < hintsLength; index++) {
  35398. if (!(isInt(item = hints[index]) && item > 0)) {
  35399. throw new Error('Hint (' + index +
  35400. ') in the linearization dictionary is invalid.');
  35401. }
  35402. }
  35403. return hints;
  35404. }
  35405. throw new Error('Hint array in the linearization dictionary is invalid.');
  35406. }
  35407. var parser = new Parser(new Lexer(stream), false, null);
  35408. var obj1 = parser.getObj();
  35409. var obj2 = parser.getObj();
  35410. var obj3 = parser.getObj();
  35411. var linDict = parser.getObj();
  35412. var obj, length;
  35413. if (!(isInt(obj1) && isInt(obj2) && isCmd(obj3, 'obj') && isDict(linDict) &&
  35414. isNum(obj = linDict.get('Linearized')) && obj > 0)) {
  35415. return null; // No valid linearization dictionary found.
  35416. } else if ((length = getInt('L')) !== stream.length) {
  35417. throw new Error('The "L" parameter in the linearization dictionary ' +
  35418. 'does not equal the stream length.');
  35419. }
  35420. return {
  35421. length: length,
  35422. hints: getHints(),
  35423. objectNumberFirst: getInt('O'),
  35424. endFirst: getInt('E'),
  35425. numPages: getInt('N'),
  35426. mainXRefEntriesOffset: getInt('T'),
  35427. pageFirst: (linDict.has('P') ? getInt('P', true) : 0)
  35428. };
  35429. }
  35430. };
  35431. var PostScriptParser = (function PostScriptParserClosure() {
  35432. function PostScriptParser(lexer) {
  35433. this.lexer = lexer;
  35434. this.operators = [];
  35435. this.token = null;
  35436. this.prev = null;
  35437. }
  35438. PostScriptParser.prototype = {
  35439. nextToken: function PostScriptParser_nextToken() {
  35440. this.prev = this.token;
  35441. this.token = this.lexer.getToken();
  35442. },
  35443. accept: function PostScriptParser_accept(type) {
  35444. if (this.token.type === type) {
  35445. this.nextToken();
  35446. return true;
  35447. }
  35448. return false;
  35449. },
  35450. expect: function PostScriptParser_expect(type) {
  35451. if (this.accept(type)) {
  35452. return true;
  35453. }
  35454. error('Unexpected symbol: found ' + this.token.type + ' expected ' +
  35455. type + '.');
  35456. },
  35457. parse: function PostScriptParser_parse() {
  35458. this.nextToken();
  35459. this.expect(PostScriptTokenTypes.LBRACE);
  35460. this.parseBlock();
  35461. this.expect(PostScriptTokenTypes.RBRACE);
  35462. return this.operators;
  35463. },
  35464. parseBlock: function PostScriptParser_parseBlock() {
  35465. while (true) {
  35466. if (this.accept(PostScriptTokenTypes.NUMBER)) {
  35467. this.operators.push(this.prev.value);
  35468. } else if (this.accept(PostScriptTokenTypes.OPERATOR)) {
  35469. this.operators.push(this.prev.value);
  35470. } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
  35471. this.parseCondition();
  35472. } else {
  35473. return;
  35474. }
  35475. }
  35476. },
  35477. parseCondition: function PostScriptParser_parseCondition() {
  35478. // Add two place holders that will be updated later
  35479. var conditionLocation = this.operators.length;
  35480. this.operators.push(null, null);
  35481. this.parseBlock();
  35482. this.expect(PostScriptTokenTypes.RBRACE);
  35483. if (this.accept(PostScriptTokenTypes.IF)) {
  35484. // The true block is right after the 'if' so it just falls through on
  35485. // true else it jumps and skips the true block.
  35486. this.operators[conditionLocation] = this.operators.length;
  35487. this.operators[conditionLocation + 1] = 'jz';
  35488. } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
  35489. var jumpLocation = this.operators.length;
  35490. this.operators.push(null, null);
  35491. var endOfTrue = this.operators.length;
  35492. this.parseBlock();
  35493. this.expect(PostScriptTokenTypes.RBRACE);
  35494. this.expect(PostScriptTokenTypes.IFELSE);
  35495. // The jump is added at the end of the true block to skip the false
  35496. // block.
  35497. this.operators[jumpLocation] = this.operators.length;
  35498. this.operators[jumpLocation + 1] = 'j';
  35499. this.operators[conditionLocation] = endOfTrue;
  35500. this.operators[conditionLocation + 1] = 'jz';
  35501. } else {
  35502. error('PS Function: error parsing conditional.');
  35503. }
  35504. }
  35505. };
  35506. return PostScriptParser;
  35507. })();
  35508. var PostScriptTokenTypes = {
  35509. LBRACE: 0,
  35510. RBRACE: 1,
  35511. NUMBER: 2,
  35512. OPERATOR: 3,
  35513. IF: 4,
  35514. IFELSE: 5
  35515. };
  35516. var PostScriptToken = (function PostScriptTokenClosure() {
  35517. function PostScriptToken(type, value) {
  35518. this.type = type;
  35519. this.value = value;
  35520. }
  35521. var opCache = {};
  35522. PostScriptToken.getOperator = function PostScriptToken_getOperator(op) {
  35523. var opValue = opCache[op];
  35524. if (opValue) {
  35525. return opValue;
  35526. }
  35527. return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);
  35528. };
  35529. PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE,
  35530. '{');
  35531. PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE,
  35532. '}');
  35533. PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF');
  35534. PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE,
  35535. 'IFELSE');
  35536. return PostScriptToken;
  35537. })();
  35538. var PostScriptLexer = (function PostScriptLexerClosure() {
  35539. function PostScriptLexer(stream) {
  35540. this.stream = stream;
  35541. this.nextChar();
  35542. this.strBuf = [];
  35543. }
  35544. PostScriptLexer.prototype = {
  35545. nextChar: function PostScriptLexer_nextChar() {
  35546. return (this.currentChar = this.stream.getByte());
  35547. },
  35548. getToken: function PostScriptLexer_getToken() {
  35549. var comment = false;
  35550. var ch = this.currentChar;
  35551. // skip comments
  35552. while (true) {
  35553. if (ch < 0) {
  35554. return EOF;
  35555. }
  35556. if (comment) {
  35557. if (ch === 0x0A || ch === 0x0D) {
  35558. comment = false;
  35559. }
  35560. } else if (ch === 0x25) { // '%'
  35561. comment = true;
  35562. } else if (!Lexer.isSpace(ch)) {
  35563. break;
  35564. }
  35565. ch = this.nextChar();
  35566. }
  35567. switch (ch | 0) {
  35568. case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'
  35569. case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'
  35570. case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'
  35571. return new PostScriptToken(PostScriptTokenTypes.NUMBER,
  35572. this.getNumber());
  35573. case 0x7B: // '{'
  35574. this.nextChar();
  35575. return PostScriptToken.LBRACE;
  35576. case 0x7D: // '}'
  35577. this.nextChar();
  35578. return PostScriptToken.RBRACE;
  35579. }
  35580. // operator
  35581. var strBuf = this.strBuf;
  35582. strBuf.length = 0;
  35583. strBuf[0] = String.fromCharCode(ch);
  35584. while ((ch = this.nextChar()) >= 0 && // and 'A'-'Z', 'a'-'z'
  35585. ((ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A))) {
  35586. strBuf.push(String.fromCharCode(ch));
  35587. }
  35588. var str = strBuf.join('');
  35589. switch (str.toLowerCase()) {
  35590. case 'if':
  35591. return PostScriptToken.IF;
  35592. case 'ifelse':
  35593. return PostScriptToken.IFELSE;
  35594. default:
  35595. return PostScriptToken.getOperator(str);
  35596. }
  35597. },
  35598. getNumber: function PostScriptLexer_getNumber() {
  35599. var ch = this.currentChar;
  35600. var strBuf = this.strBuf;
  35601. strBuf.length = 0;
  35602. strBuf[0] = String.fromCharCode(ch);
  35603. while ((ch = this.nextChar()) >= 0) {
  35604. if ((ch >= 0x30 && ch <= 0x39) || // '0'-'9'
  35605. ch === 0x2D || ch === 0x2E) { // '-', '.'
  35606. strBuf.push(String.fromCharCode(ch));
  35607. } else {
  35608. break;
  35609. }
  35610. }
  35611. var value = parseFloat(strBuf.join(''));
  35612. if (isNaN(value)) {
  35613. error('Invalid floating point number: ' + value);
  35614. }
  35615. return value;
  35616. }
  35617. };
  35618. return PostScriptLexer;
  35619. })();
  35620. var Stream = (function StreamClosure() {
  35621. function Stream(arrayBuffer, start, length, dict) {
  35622. this.bytes = (arrayBuffer instanceof Uint8Array ?
  35623. arrayBuffer : new Uint8Array(arrayBuffer));
  35624. this.start = start || 0;
  35625. this.pos = this.start;
  35626. this.end = (start + length) || this.bytes.length;
  35627. this.dict = dict;
  35628. }
  35629. // required methods for a stream. if a particular stream does not
  35630. // implement these, an error should be thrown
  35631. Stream.prototype = {
  35632. get length() {
  35633. return this.end - this.start;
  35634. },
  35635. get isEmpty() {
  35636. return this.length === 0;
  35637. },
  35638. getByte: function Stream_getByte() {
  35639. if (this.pos >= this.end) {
  35640. return -1;
  35641. }
  35642. return this.bytes[this.pos++];
  35643. },
  35644. getUint16: function Stream_getUint16() {
  35645. var b0 = this.getByte();
  35646. var b1 = this.getByte();
  35647. if (b0 === -1 || b1 === -1) {
  35648. return -1;
  35649. }
  35650. return (b0 << 8) + b1;
  35651. },
  35652. getInt32: function Stream_getInt32() {
  35653. var b0 = this.getByte();
  35654. var b1 = this.getByte();
  35655. var b2 = this.getByte();
  35656. var b3 = this.getByte();
  35657. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  35658. },
  35659. // returns subarray of original buffer
  35660. // should only be read
  35661. getBytes: function Stream_getBytes(length) {
  35662. var bytes = this.bytes;
  35663. var pos = this.pos;
  35664. var strEnd = this.end;
  35665. if (!length) {
  35666. return bytes.subarray(pos, strEnd);
  35667. }
  35668. var end = pos + length;
  35669. if (end > strEnd) {
  35670. end = strEnd;
  35671. }
  35672. this.pos = end;
  35673. return bytes.subarray(pos, end);
  35674. },
  35675. peekByte: function Stream_peekByte() {
  35676. var peekedByte = this.getByte();
  35677. this.pos--;
  35678. return peekedByte;
  35679. },
  35680. peekBytes: function Stream_peekBytes(length) {
  35681. var bytes = this.getBytes(length);
  35682. this.pos -= bytes.length;
  35683. return bytes;
  35684. },
  35685. skip: function Stream_skip(n) {
  35686. if (!n) {
  35687. n = 1;
  35688. }
  35689. this.pos += n;
  35690. },
  35691. reset: function Stream_reset() {
  35692. this.pos = this.start;
  35693. },
  35694. moveStart: function Stream_moveStart() {
  35695. this.start = this.pos;
  35696. },
  35697. makeSubStream: function Stream_makeSubStream(start, length, dict) {
  35698. return new Stream(this.bytes.buffer, start, length, dict);
  35699. },
  35700. isStream: true
  35701. };
  35702. return Stream;
  35703. })();
  35704. var StringStream = (function StringStreamClosure() {
  35705. function StringStream(str) {
  35706. var length = str.length;
  35707. var bytes = new Uint8Array(length);
  35708. for (var n = 0; n < length; ++n) {
  35709. bytes[n] = str.charCodeAt(n);
  35710. }
  35711. Stream.call(this, bytes);
  35712. }
  35713. StringStream.prototype = Stream.prototype;
  35714. return StringStream;
  35715. })();
  35716. // super class for the decoding streams
  35717. var DecodeStream = (function DecodeStreamClosure() {
  35718. // Lots of DecodeStreams are created whose buffers are never used. For these
  35719. // we share a single empty buffer. This is (a) space-efficient and (b) avoids
  35720. // having special cases that would be required if we used |null| for an empty
  35721. // buffer.
  35722. var emptyBuffer = new Uint8Array(0);
  35723. function DecodeStream(maybeMinBufferLength) {
  35724. this.pos = 0;
  35725. this.bufferLength = 0;
  35726. this.eof = false;
  35727. this.buffer = emptyBuffer;
  35728. this.minBufferLength = 512;
  35729. if (maybeMinBufferLength) {
  35730. // Compute the first power of two that is as big as maybeMinBufferLength.
  35731. while (this.minBufferLength < maybeMinBufferLength) {
  35732. this.minBufferLength *= 2;
  35733. }
  35734. }
  35735. }
  35736. DecodeStream.prototype = {
  35737. get isEmpty() {
  35738. while (!this.eof && this.bufferLength === 0) {
  35739. this.readBlock();
  35740. }
  35741. return this.bufferLength === 0;
  35742. },
  35743. ensureBuffer: function DecodeStream_ensureBuffer(requested) {
  35744. var buffer = this.buffer;
  35745. if (requested <= buffer.byteLength) {
  35746. return buffer;
  35747. }
  35748. var size = this.minBufferLength;
  35749. while (size < requested) {
  35750. size *= 2;
  35751. }
  35752. var buffer2 = new Uint8Array(size);
  35753. buffer2.set(buffer);
  35754. return (this.buffer = buffer2);
  35755. },
  35756. getByte: function DecodeStream_getByte() {
  35757. var pos = this.pos;
  35758. while (this.bufferLength <= pos) {
  35759. if (this.eof) {
  35760. return -1;
  35761. }
  35762. this.readBlock();
  35763. }
  35764. return this.buffer[this.pos++];
  35765. },
  35766. getUint16: function DecodeStream_getUint16() {
  35767. var b0 = this.getByte();
  35768. var b1 = this.getByte();
  35769. if (b0 === -1 || b1 === -1) {
  35770. return -1;
  35771. }
  35772. return (b0 << 8) + b1;
  35773. },
  35774. getInt32: function DecodeStream_getInt32() {
  35775. var b0 = this.getByte();
  35776. var b1 = this.getByte();
  35777. var b2 = this.getByte();
  35778. var b3 = this.getByte();
  35779. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  35780. },
  35781. getBytes: function DecodeStream_getBytes(length) {
  35782. var end, pos = this.pos;
  35783. if (length) {
  35784. this.ensureBuffer(pos + length);
  35785. end = pos + length;
  35786. while (!this.eof && this.bufferLength < end) {
  35787. this.readBlock();
  35788. }
  35789. var bufEnd = this.bufferLength;
  35790. if (end > bufEnd) {
  35791. end = bufEnd;
  35792. }
  35793. } else {
  35794. while (!this.eof) {
  35795. this.readBlock();
  35796. }
  35797. end = this.bufferLength;
  35798. }
  35799. this.pos = end;
  35800. return this.buffer.subarray(pos, end);
  35801. },
  35802. peekByte: function DecodeStream_peekByte() {
  35803. var peekedByte = this.getByte();
  35804. this.pos--;
  35805. return peekedByte;
  35806. },
  35807. peekBytes: function DecodeStream_peekBytes(length) {
  35808. var bytes = this.getBytes(length);
  35809. this.pos -= bytes.length;
  35810. return bytes;
  35811. },
  35812. makeSubStream: function DecodeStream_makeSubStream(start, length, dict) {
  35813. var end = start + length;
  35814. while (this.bufferLength <= end && !this.eof) {
  35815. this.readBlock();
  35816. }
  35817. return new Stream(this.buffer, start, length, dict);
  35818. },
  35819. skip: function DecodeStream_skip(n) {
  35820. if (!n) {
  35821. n = 1;
  35822. }
  35823. this.pos += n;
  35824. },
  35825. reset: function DecodeStream_reset() {
  35826. this.pos = 0;
  35827. },
  35828. getBaseStreams: function DecodeStream_getBaseStreams() {
  35829. if (this.str && this.str.getBaseStreams) {
  35830. return this.str.getBaseStreams();
  35831. }
  35832. return [];
  35833. }
  35834. };
  35835. return DecodeStream;
  35836. })();
  35837. var StreamsSequenceStream = (function StreamsSequenceStreamClosure() {
  35838. function StreamsSequenceStream(streams) {
  35839. this.streams = streams;
  35840. DecodeStream.call(this, /* maybeLength = */ null);
  35841. }
  35842. StreamsSequenceStream.prototype = Object.create(DecodeStream.prototype);
  35843. StreamsSequenceStream.prototype.readBlock =
  35844. function streamSequenceStreamReadBlock() {
  35845. var streams = this.streams;
  35846. if (streams.length === 0) {
  35847. this.eof = true;
  35848. return;
  35849. }
  35850. var stream = streams.shift();
  35851. var chunk = stream.getBytes();
  35852. var bufferLength = this.bufferLength;
  35853. var newLength = bufferLength + chunk.length;
  35854. var buffer = this.ensureBuffer(newLength);
  35855. buffer.set(chunk, bufferLength);
  35856. this.bufferLength = newLength;
  35857. };
  35858. StreamsSequenceStream.prototype.getBaseStreams =
  35859. function StreamsSequenceStream_getBaseStreams() {
  35860. var baseStreams = [];
  35861. for (var i = 0, ii = this.streams.length; i < ii; i++) {
  35862. var stream = this.streams[i];
  35863. if (stream.getBaseStreams) {
  35864. Util.appendToArray(baseStreams, stream.getBaseStreams());
  35865. }
  35866. }
  35867. return baseStreams;
  35868. };
  35869. return StreamsSequenceStream;
  35870. })();
  35871. var FlateStream = (function FlateStreamClosure() {
  35872. var codeLenCodeMap = new Int32Array([
  35873. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  35874. ]);
  35875. var lengthDecode = new Int32Array([
  35876. 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
  35877. 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
  35878. 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
  35879. 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
  35880. ]);
  35881. var distDecode = new Int32Array([
  35882. 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
  35883. 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
  35884. 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
  35885. 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
  35886. ]);
  35887. var fixedLitCodeTab = [new Int32Array([
  35888. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
  35889. 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
  35890. 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
  35891. 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
  35892. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
  35893. 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
  35894. 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
  35895. 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
  35896. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
  35897. 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
  35898. 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
  35899. 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
  35900. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
  35901. 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
  35902. 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
  35903. 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
  35904. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
  35905. 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
  35906. 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
  35907. 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
  35908. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
  35909. 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
  35910. 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
  35911. 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
  35912. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
  35913. 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
  35914. 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
  35915. 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
  35916. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
  35917. 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
  35918. 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
  35919. 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
  35920. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
  35921. 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
  35922. 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
  35923. 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
  35924. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
  35925. 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
  35926. 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
  35927. 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
  35928. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
  35929. 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
  35930. 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
  35931. 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
  35932. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
  35933. 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
  35934. 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
  35935. 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
  35936. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
  35937. 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
  35938. 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
  35939. 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
  35940. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
  35941. 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
  35942. 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
  35943. 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
  35944. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
  35945. 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
  35946. 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
  35947. 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
  35948. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
  35949. 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
  35950. 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
  35951. 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
  35952. ]), 9];
  35953. var fixedDistCodeTab = [new Int32Array([
  35954. 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
  35955. 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
  35956. 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
  35957. 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
  35958. ]), 5];
  35959. function FlateStream(str, maybeLength) {
  35960. this.str = str;
  35961. this.dict = str.dict;
  35962. var cmf = str.getByte();
  35963. var flg = str.getByte();
  35964. if (cmf === -1 || flg === -1) {
  35965. error('Invalid header in flate stream: ' + cmf + ', ' + flg);
  35966. }
  35967. if ((cmf & 0x0f) !== 0x08) {
  35968. error('Unknown compression method in flate stream: ' + cmf + ', ' + flg);
  35969. }
  35970. if ((((cmf << 8) + flg) % 31) !== 0) {
  35971. error('Bad FCHECK in flate stream: ' + cmf + ', ' + flg);
  35972. }
  35973. if (flg & 0x20) {
  35974. error('FDICT bit set in flate stream: ' + cmf + ', ' + flg);
  35975. }
  35976. this.codeSize = 0;
  35977. this.codeBuf = 0;
  35978. DecodeStream.call(this, maybeLength);
  35979. }
  35980. FlateStream.prototype = Object.create(DecodeStream.prototype);
  35981. FlateStream.prototype.getBits = function FlateStream_getBits(bits) {
  35982. var str = this.str;
  35983. var codeSize = this.codeSize;
  35984. var codeBuf = this.codeBuf;
  35985. var b;
  35986. while (codeSize < bits) {
  35987. if ((b = str.getByte()) === -1) {
  35988. error('Bad encoding in flate stream');
  35989. }
  35990. codeBuf |= b << codeSize;
  35991. codeSize += 8;
  35992. }
  35993. b = codeBuf & ((1 << bits) - 1);
  35994. this.codeBuf = codeBuf >> bits;
  35995. this.codeSize = codeSize -= bits;
  35996. return b;
  35997. };
  35998. FlateStream.prototype.getCode = function FlateStream_getCode(table) {
  35999. var str = this.str;
  36000. var codes = table[0];
  36001. var maxLen = table[1];
  36002. var codeSize = this.codeSize;
  36003. var codeBuf = this.codeBuf;
  36004. var b;
  36005. while (codeSize < maxLen) {
  36006. if ((b = str.getByte()) === -1) {
  36007. // premature end of stream. code might however still be valid.
  36008. // codeSize < codeLen check below guards against incomplete codeVal.
  36009. break;
  36010. }
  36011. codeBuf |= (b << codeSize);
  36012. codeSize += 8;
  36013. }
  36014. var code = codes[codeBuf & ((1 << maxLen) - 1)];
  36015. var codeLen = code >> 16;
  36016. var codeVal = code & 0xffff;
  36017. if (codeLen < 1 || codeSize < codeLen) {
  36018. error('Bad encoding in flate stream');
  36019. }
  36020. this.codeBuf = (codeBuf >> codeLen);
  36021. this.codeSize = (codeSize - codeLen);
  36022. return codeVal;
  36023. };
  36024. FlateStream.prototype.generateHuffmanTable =
  36025. function flateStreamGenerateHuffmanTable(lengths) {
  36026. var n = lengths.length;
  36027. // find max code length
  36028. var maxLen = 0;
  36029. var i;
  36030. for (i = 0; i < n; ++i) {
  36031. if (lengths[i] > maxLen) {
  36032. maxLen = lengths[i];
  36033. }
  36034. }
  36035. // build the table
  36036. var size = 1 << maxLen;
  36037. var codes = new Int32Array(size);
  36038. for (var len = 1, code = 0, skip = 2;
  36039. len <= maxLen;
  36040. ++len, code <<= 1, skip <<= 1) {
  36041. for (var val = 0; val < n; ++val) {
  36042. if (lengths[val] === len) {
  36043. // bit-reverse the code
  36044. var code2 = 0;
  36045. var t = code;
  36046. for (i = 0; i < len; ++i) {
  36047. code2 = (code2 << 1) | (t & 1);
  36048. t >>= 1;
  36049. }
  36050. // fill the table entries
  36051. for (i = code2; i < size; i += skip) {
  36052. codes[i] = (len << 16) | val;
  36053. }
  36054. ++code;
  36055. }
  36056. }
  36057. }
  36058. return [codes, maxLen];
  36059. };
  36060. FlateStream.prototype.readBlock = function FlateStream_readBlock() {
  36061. var buffer, len;
  36062. var str = this.str;
  36063. // read block header
  36064. var hdr = this.getBits(3);
  36065. if (hdr & 1) {
  36066. this.eof = true;
  36067. }
  36068. hdr >>= 1;
  36069. if (hdr === 0) { // uncompressed block
  36070. var b;
  36071. if ((b = str.getByte()) === -1) {
  36072. error('Bad block header in flate stream');
  36073. }
  36074. var blockLen = b;
  36075. if ((b = str.getByte()) === -1) {
  36076. error('Bad block header in flate stream');
  36077. }
  36078. blockLen |= (b << 8);
  36079. if ((b = str.getByte()) === -1) {
  36080. error('Bad block header in flate stream');
  36081. }
  36082. var check = b;
  36083. if ((b = str.getByte()) === -1) {
  36084. error('Bad block header in flate stream');
  36085. }
  36086. check |= (b << 8);
  36087. if (check !== (~blockLen & 0xffff) &&
  36088. (blockLen !== 0 || check !== 0)) {
  36089. // Ignoring error for bad "empty" block (see issue 1277)
  36090. error('Bad uncompressed block length in flate stream');
  36091. }
  36092. this.codeBuf = 0;
  36093. this.codeSize = 0;
  36094. var bufferLength = this.bufferLength;
  36095. buffer = this.ensureBuffer(bufferLength + blockLen);
  36096. var end = bufferLength + blockLen;
  36097. this.bufferLength = end;
  36098. if (blockLen === 0) {
  36099. if (str.peekByte() === -1) {
  36100. this.eof = true;
  36101. }
  36102. } else {
  36103. for (var n = bufferLength; n < end; ++n) {
  36104. if ((b = str.getByte()) === -1) {
  36105. this.eof = true;
  36106. break;
  36107. }
  36108. buffer[n] = b;
  36109. }
  36110. }
  36111. return;
  36112. }
  36113. var litCodeTable;
  36114. var distCodeTable;
  36115. if (hdr === 1) { // compressed block, fixed codes
  36116. litCodeTable = fixedLitCodeTab;
  36117. distCodeTable = fixedDistCodeTab;
  36118. } else if (hdr === 2) { // compressed block, dynamic codes
  36119. var numLitCodes = this.getBits(5) + 257;
  36120. var numDistCodes = this.getBits(5) + 1;
  36121. var numCodeLenCodes = this.getBits(4) + 4;
  36122. // build the code lengths code table
  36123. var codeLenCodeLengths = new Uint8Array(codeLenCodeMap.length);
  36124. var i;
  36125. for (i = 0; i < numCodeLenCodes; ++i) {
  36126. codeLenCodeLengths[codeLenCodeMap[i]] = this.getBits(3);
  36127. }
  36128. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
  36129. // build the literal and distance code tables
  36130. len = 0;
  36131. i = 0;
  36132. var codes = numLitCodes + numDistCodes;
  36133. var codeLengths = new Uint8Array(codes);
  36134. var bitsLength, bitsOffset, what;
  36135. while (i < codes) {
  36136. var code = this.getCode(codeLenCodeTab);
  36137. if (code === 16) {
  36138. bitsLength = 2; bitsOffset = 3; what = len;
  36139. } else if (code === 17) {
  36140. bitsLength = 3; bitsOffset = 3; what = (len = 0);
  36141. } else if (code === 18) {
  36142. bitsLength = 7; bitsOffset = 11; what = (len = 0);
  36143. } else {
  36144. codeLengths[i++] = len = code;
  36145. continue;
  36146. }
  36147. var repeatLength = this.getBits(bitsLength) + bitsOffset;
  36148. while (repeatLength-- > 0) {
  36149. codeLengths[i++] = what;
  36150. }
  36151. }
  36152. litCodeTable =
  36153. this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes));
  36154. distCodeTable =
  36155. this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes));
  36156. } else {
  36157. error('Unknown block type in flate stream');
  36158. }
  36159. buffer = this.buffer;
  36160. var limit = buffer ? buffer.length : 0;
  36161. var pos = this.bufferLength;
  36162. while (true) {
  36163. var code1 = this.getCode(litCodeTable);
  36164. if (code1 < 256) {
  36165. if (pos + 1 >= limit) {
  36166. buffer = this.ensureBuffer(pos + 1);
  36167. limit = buffer.length;
  36168. }
  36169. buffer[pos++] = code1;
  36170. continue;
  36171. }
  36172. if (code1 === 256) {
  36173. this.bufferLength = pos;
  36174. return;
  36175. }
  36176. code1 -= 257;
  36177. code1 = lengthDecode[code1];
  36178. var code2 = code1 >> 16;
  36179. if (code2 > 0) {
  36180. code2 = this.getBits(code2);
  36181. }
  36182. len = (code1 & 0xffff) + code2;
  36183. code1 = this.getCode(distCodeTable);
  36184. code1 = distDecode[code1];
  36185. code2 = code1 >> 16;
  36186. if (code2 > 0) {
  36187. code2 = this.getBits(code2);
  36188. }
  36189. var dist = (code1 & 0xffff) + code2;
  36190. if (pos + len >= limit) {
  36191. buffer = this.ensureBuffer(pos + len);
  36192. limit = buffer.length;
  36193. }
  36194. for (var k = 0; k < len; ++k, ++pos) {
  36195. buffer[pos] = buffer[pos - dist];
  36196. }
  36197. }
  36198. };
  36199. return FlateStream;
  36200. })();
  36201. var PredictorStream = (function PredictorStreamClosure() {
  36202. function PredictorStream(str, maybeLength, params) {
  36203. var predictor = this.predictor = params.get('Predictor') || 1;
  36204. if (predictor <= 1) {
  36205. return str; // no prediction
  36206. }
  36207. if (predictor !== 2 && (predictor < 10 || predictor > 15)) {
  36208. error('Unsupported predictor: ' + predictor);
  36209. }
  36210. if (predictor === 2) {
  36211. this.readBlock = this.readBlockTiff;
  36212. } else {
  36213. this.readBlock = this.readBlockPng;
  36214. }
  36215. this.str = str;
  36216. this.dict = str.dict;
  36217. var colors = this.colors = params.get('Colors') || 1;
  36218. var bits = this.bits = params.get('BitsPerComponent') || 8;
  36219. var columns = this.columns = params.get('Columns') || 1;
  36220. this.pixBytes = (colors * bits + 7) >> 3;
  36221. this.rowBytes = (columns * colors * bits + 7) >> 3;
  36222. DecodeStream.call(this, maybeLength);
  36223. return this;
  36224. }
  36225. PredictorStream.prototype = Object.create(DecodeStream.prototype);
  36226. PredictorStream.prototype.readBlockTiff =
  36227. function predictorStreamReadBlockTiff() {
  36228. var rowBytes = this.rowBytes;
  36229. var bufferLength = this.bufferLength;
  36230. var buffer = this.ensureBuffer(bufferLength + rowBytes);
  36231. var bits = this.bits;
  36232. var colors = this.colors;
  36233. var rawBytes = this.str.getBytes(rowBytes);
  36234. this.eof = !rawBytes.length;
  36235. if (this.eof) {
  36236. return;
  36237. }
  36238. var inbuf = 0, outbuf = 0;
  36239. var inbits = 0, outbits = 0;
  36240. var pos = bufferLength;
  36241. var i;
  36242. if (bits === 1) {
  36243. for (i = 0; i < rowBytes; ++i) {
  36244. var c = rawBytes[i];
  36245. inbuf = (inbuf << 8) | c;
  36246. // bitwise addition is exclusive or
  36247. // first shift inbuf and then add
  36248. buffer[pos++] = (c ^ (inbuf >> colors)) & 0xFF;
  36249. // truncate inbuf (assumes colors < 16)
  36250. inbuf &= 0xFFFF;
  36251. }
  36252. } else if (bits === 8) {
  36253. for (i = 0; i < colors; ++i) {
  36254. buffer[pos++] = rawBytes[i];
  36255. }
  36256. for (; i < rowBytes; ++i) {
  36257. buffer[pos] = buffer[pos - colors] + rawBytes[i];
  36258. pos++;
  36259. }
  36260. } else {
  36261. var compArray = new Uint8Array(colors + 1);
  36262. var bitMask = (1 << bits) - 1;
  36263. var j = 0, k = bufferLength;
  36264. var columns = this.columns;
  36265. for (i = 0; i < columns; ++i) {
  36266. for (var kk = 0; kk < colors; ++kk) {
  36267. if (inbits < bits) {
  36268. inbuf = (inbuf << 8) | (rawBytes[j++] & 0xFF);
  36269. inbits += 8;
  36270. }
  36271. compArray[kk] = (compArray[kk] +
  36272. (inbuf >> (inbits - bits))) & bitMask;
  36273. inbits -= bits;
  36274. outbuf = (outbuf << bits) | compArray[kk];
  36275. outbits += bits;
  36276. if (outbits >= 8) {
  36277. buffer[k++] = (outbuf >> (outbits - 8)) & 0xFF;
  36278. outbits -= 8;
  36279. }
  36280. }
  36281. }
  36282. if (outbits > 0) {
  36283. buffer[k++] = (outbuf << (8 - outbits)) +
  36284. (inbuf & ((1 << (8 - outbits)) - 1));
  36285. }
  36286. }
  36287. this.bufferLength += rowBytes;
  36288. };
  36289. PredictorStream.prototype.readBlockPng =
  36290. function predictorStreamReadBlockPng() {
  36291. var rowBytes = this.rowBytes;
  36292. var pixBytes = this.pixBytes;
  36293. var predictor = this.str.getByte();
  36294. var rawBytes = this.str.getBytes(rowBytes);
  36295. this.eof = !rawBytes.length;
  36296. if (this.eof) {
  36297. return;
  36298. }
  36299. var bufferLength = this.bufferLength;
  36300. var buffer = this.ensureBuffer(bufferLength + rowBytes);
  36301. var prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength);
  36302. if (prevRow.length === 0) {
  36303. prevRow = new Uint8Array(rowBytes);
  36304. }
  36305. var i, j = bufferLength, up, c;
  36306. switch (predictor) {
  36307. case 0:
  36308. for (i = 0; i < rowBytes; ++i) {
  36309. buffer[j++] = rawBytes[i];
  36310. }
  36311. break;
  36312. case 1:
  36313. for (i = 0; i < pixBytes; ++i) {
  36314. buffer[j++] = rawBytes[i];
  36315. }
  36316. for (; i < rowBytes; ++i) {
  36317. buffer[j] = (buffer[j - pixBytes] + rawBytes[i]) & 0xFF;
  36318. j++;
  36319. }
  36320. break;
  36321. case 2:
  36322. for (i = 0; i < rowBytes; ++i) {
  36323. buffer[j++] = (prevRow[i] + rawBytes[i]) & 0xFF;
  36324. }
  36325. break;
  36326. case 3:
  36327. for (i = 0; i < pixBytes; ++i) {
  36328. buffer[j++] = (prevRow[i] >> 1) + rawBytes[i];
  36329. }
  36330. for (; i < rowBytes; ++i) {
  36331. buffer[j] = (((prevRow[i] + buffer[j - pixBytes]) >> 1) +
  36332. rawBytes[i]) & 0xFF;
  36333. j++;
  36334. }
  36335. break;
  36336. case 4:
  36337. // we need to save the up left pixels values. the simplest way
  36338. // is to create a new buffer
  36339. for (i = 0; i < pixBytes; ++i) {
  36340. up = prevRow[i];
  36341. c = rawBytes[i];
  36342. buffer[j++] = up + c;
  36343. }
  36344. for (; i < rowBytes; ++i) {
  36345. up = prevRow[i];
  36346. var upLeft = prevRow[i - pixBytes];
  36347. var left = buffer[j - pixBytes];
  36348. var p = left + up - upLeft;
  36349. var pa = p - left;
  36350. if (pa < 0) {
  36351. pa = -pa;
  36352. }
  36353. var pb = p - up;
  36354. if (pb < 0) {
  36355. pb = -pb;
  36356. }
  36357. var pc = p - upLeft;
  36358. if (pc < 0) {
  36359. pc = -pc;
  36360. }
  36361. c = rawBytes[i];
  36362. if (pa <= pb && pa <= pc) {
  36363. buffer[j++] = left + c;
  36364. } else if (pb <= pc) {
  36365. buffer[j++] = up + c;
  36366. } else {
  36367. buffer[j++] = upLeft + c;
  36368. }
  36369. }
  36370. break;
  36371. default:
  36372. error('Unsupported predictor: ' + predictor);
  36373. }
  36374. this.bufferLength += rowBytes;
  36375. };
  36376. return PredictorStream;
  36377. })();
  36378. /**
  36379. * Depending on the type of JPEG a JpegStream is handled in different ways. For
  36380. * JPEG's that are supported natively such as DeviceGray and DeviceRGB the image
  36381. * data is stored and then loaded by the browser. For unsupported JPEG's we use
  36382. * a library to decode these images and the stream behaves like all the other
  36383. * DecodeStreams.
  36384. */
  36385. var JpegStream = (function JpegStreamClosure() {
  36386. function JpegStream(stream, maybeLength, dict, xref) {
  36387. // Some images may contain 'junk' before the SOI (start-of-image) marker.
  36388. // Note: this seems to mainly affect inline images.
  36389. var ch;
  36390. while ((ch = stream.getByte()) !== -1) {
  36391. if (ch === 0xFF) { // Find the first byte of the SOI marker (0xFFD8).
  36392. stream.skip(-1); // Reset the stream position to the SOI.
  36393. break;
  36394. }
  36395. }
  36396. this.stream = stream;
  36397. this.maybeLength = maybeLength;
  36398. this.dict = dict;
  36399. DecodeStream.call(this, maybeLength);
  36400. }
  36401. JpegStream.prototype = Object.create(DecodeStream.prototype);
  36402. Object.defineProperty(JpegStream.prototype, 'bytes', {
  36403. get: function JpegStream_bytes() {
  36404. // If this.maybeLength is null, we'll get the entire stream.
  36405. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  36406. },
  36407. configurable: true
  36408. });
  36409. JpegStream.prototype.ensureBuffer = function JpegStream_ensureBuffer(req) {
  36410. if (this.bufferLength) {
  36411. return;
  36412. }
  36413. try {
  36414. var jpegImage = new JpegImage();
  36415. // checking if values needs to be transformed before conversion
  36416. if (this.forceRGB && this.dict && isArray(this.dict.get('Decode'))) {
  36417. var decodeArr = this.dict.get('Decode');
  36418. var bitsPerComponent = this.dict.get('BitsPerComponent') || 8;
  36419. var decodeArrLength = decodeArr.length;
  36420. var transform = new Int32Array(decodeArrLength);
  36421. var transformNeeded = false;
  36422. var maxValue = (1 << bitsPerComponent) - 1;
  36423. for (var i = 0; i < decodeArrLength; i += 2) {
  36424. transform[i] = ((decodeArr[i + 1] - decodeArr[i]) * 256) | 0;
  36425. transform[i + 1] = (decodeArr[i] * maxValue) | 0;
  36426. if (transform[i] !== 256 || transform[i + 1] !== 0) {
  36427. transformNeeded = true;
  36428. }
  36429. }
  36430. if (transformNeeded) {
  36431. jpegImage.decodeTransform = transform;
  36432. }
  36433. }
  36434. jpegImage.parse(this.bytes);
  36435. var data = jpegImage.getData(this.drawWidth, this.drawHeight,
  36436. this.forceRGB);
  36437. this.buffer = data;
  36438. this.bufferLength = data.length;
  36439. this.eof = true;
  36440. } catch (e) {
  36441. error('JPEG error: ' + e);
  36442. }
  36443. };
  36444. JpegStream.prototype.getBytes = function JpegStream_getBytes(length) {
  36445. this.ensureBuffer();
  36446. return this.buffer;
  36447. };
  36448. JpegStream.prototype.getIR = function JpegStream_getIR() {
  36449. return PDFJS.createObjectURL(this.bytes, 'image/jpeg');
  36450. };
  36451. /**
  36452. * Checks if the image can be decoded and displayed by the browser without any
  36453. * further processing such as color space conversions.
  36454. */
  36455. JpegStream.prototype.isNativelySupported =
  36456. function JpegStream_isNativelySupported(xref, res) {
  36457. var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);
  36458. return (cs.name === 'DeviceGray' || cs.name === 'DeviceRGB') &&
  36459. cs.isDefaultDecode(this.dict.get('Decode', 'D'));
  36460. };
  36461. /**
  36462. * Checks if the image can be decoded by the browser.
  36463. */
  36464. JpegStream.prototype.isNativelyDecodable =
  36465. function JpegStream_isNativelyDecodable(xref, res) {
  36466. var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);
  36467. return (cs.numComps === 1 || cs.numComps === 3) &&
  36468. cs.isDefaultDecode(this.dict.get('Decode', 'D'));
  36469. };
  36470. return JpegStream;
  36471. })();
  36472. /**
  36473. * For JPEG 2000's we use a library to decode these images and
  36474. * the stream behaves like all the other DecodeStreams.
  36475. */
  36476. var JpxStream = (function JpxStreamClosure() {
  36477. function JpxStream(stream, maybeLength, dict) {
  36478. this.stream = stream;
  36479. this.maybeLength = maybeLength;
  36480. this.dict = dict;
  36481. DecodeStream.call(this, maybeLength);
  36482. }
  36483. JpxStream.prototype = Object.create(DecodeStream.prototype);
  36484. Object.defineProperty(JpxStream.prototype, 'bytes', {
  36485. get: function JpxStream_bytes() {
  36486. // If this.maybeLength is null, we'll get the entire stream.
  36487. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  36488. },
  36489. configurable: true
  36490. });
  36491. JpxStream.prototype.ensureBuffer = function JpxStream_ensureBuffer(req) {
  36492. if (this.bufferLength) {
  36493. return;
  36494. }
  36495. var jpxImage = new JpxImage();
  36496. jpxImage.parse(this.bytes);
  36497. var width = jpxImage.width;
  36498. var height = jpxImage.height;
  36499. var componentsCount = jpxImage.componentsCount;
  36500. var tileCount = jpxImage.tiles.length;
  36501. if (tileCount === 1) {
  36502. this.buffer = jpxImage.tiles[0].items;
  36503. } else {
  36504. var data = new Uint8Array(width * height * componentsCount);
  36505. for (var k = 0; k < tileCount; k++) {
  36506. var tileComponents = jpxImage.tiles[k];
  36507. var tileWidth = tileComponents.width;
  36508. var tileHeight = tileComponents.height;
  36509. var tileLeft = tileComponents.left;
  36510. var tileTop = tileComponents.top;
  36511. var src = tileComponents.items;
  36512. var srcPosition = 0;
  36513. var dataPosition = (width * tileTop + tileLeft) * componentsCount;
  36514. var imgRowSize = width * componentsCount;
  36515. var tileRowSize = tileWidth * componentsCount;
  36516. for (var j = 0; j < tileHeight; j++) {
  36517. var rowBytes = src.subarray(srcPosition, srcPosition + tileRowSize);
  36518. data.set(rowBytes, dataPosition);
  36519. srcPosition += tileRowSize;
  36520. dataPosition += imgRowSize;
  36521. }
  36522. }
  36523. this.buffer = data;
  36524. }
  36525. this.bufferLength = this.buffer.length;
  36526. this.eof = true;
  36527. };
  36528. return JpxStream;
  36529. })();
  36530. /**
  36531. * For JBIG2's we use a library to decode these images and
  36532. * the stream behaves like all the other DecodeStreams.
  36533. */
  36534. var Jbig2Stream = (function Jbig2StreamClosure() {
  36535. function Jbig2Stream(stream, maybeLength, dict) {
  36536. this.stream = stream;
  36537. this.maybeLength = maybeLength;
  36538. this.dict = dict;
  36539. DecodeStream.call(this, maybeLength);
  36540. }
  36541. Jbig2Stream.prototype = Object.create(DecodeStream.prototype);
  36542. Object.defineProperty(Jbig2Stream.prototype, 'bytes', {
  36543. get: function Jbig2Stream_bytes() {
  36544. // If this.maybeLength is null, we'll get the entire stream.
  36545. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  36546. },
  36547. configurable: true
  36548. });
  36549. Jbig2Stream.prototype.ensureBuffer = function Jbig2Stream_ensureBuffer(req) {
  36550. if (this.bufferLength) {
  36551. return;
  36552. }
  36553. var jbig2Image = new Jbig2Image();
  36554. var chunks = [], xref = this.dict.xref;
  36555. var decodeParams = xref.fetchIfRef(this.dict.get('DecodeParms'));
  36556. // According to the PDF specification, DecodeParms can be either
  36557. // a dictionary, or an array whose elements are dictionaries.
  36558. if (isArray(decodeParams)) {
  36559. if (decodeParams.length > 1) {
  36560. warn('JBIG2 - \'DecodeParms\' array with multiple elements ' +
  36561. 'not supported.');
  36562. }
  36563. decodeParams = xref.fetchIfRef(decodeParams[0]);
  36564. }
  36565. if (decodeParams && decodeParams.has('JBIG2Globals')) {
  36566. var globalsStream = decodeParams.get('JBIG2Globals');
  36567. var globals = globalsStream.getBytes();
  36568. chunks.push({data: globals, start: 0, end: globals.length});
  36569. }
  36570. chunks.push({data: this.bytes, start: 0, end: this.bytes.length});
  36571. var data = jbig2Image.parseChunks(chunks);
  36572. var dataLength = data.length;
  36573. // JBIG2 had black as 1 and white as 0, inverting the colors
  36574. for (var i = 0; i < dataLength; i++) {
  36575. data[i] ^= 0xFF;
  36576. }
  36577. this.buffer = data;
  36578. this.bufferLength = dataLength;
  36579. this.eof = true;
  36580. };
  36581. return Jbig2Stream;
  36582. })();
  36583. var DecryptStream = (function DecryptStreamClosure() {
  36584. function DecryptStream(str, maybeLength, decrypt) {
  36585. this.str = str;
  36586. this.dict = str.dict;
  36587. this.decrypt = decrypt;
  36588. this.nextChunk = null;
  36589. this.initialized = false;
  36590. DecodeStream.call(this, maybeLength);
  36591. }
  36592. var chunkSize = 512;
  36593. DecryptStream.prototype = Object.create(DecodeStream.prototype);
  36594. DecryptStream.prototype.readBlock = function DecryptStream_readBlock() {
  36595. var chunk;
  36596. if (this.initialized) {
  36597. chunk = this.nextChunk;
  36598. } else {
  36599. chunk = this.str.getBytes(chunkSize);
  36600. this.initialized = true;
  36601. }
  36602. if (!chunk || chunk.length === 0) {
  36603. this.eof = true;
  36604. return;
  36605. }
  36606. this.nextChunk = this.str.getBytes(chunkSize);
  36607. var hasMoreData = this.nextChunk && this.nextChunk.length > 0;
  36608. var decrypt = this.decrypt;
  36609. chunk = decrypt(chunk, !hasMoreData);
  36610. var bufferLength = this.bufferLength;
  36611. var i, n = chunk.length;
  36612. var buffer = this.ensureBuffer(bufferLength + n);
  36613. for (i = 0; i < n; i++) {
  36614. buffer[bufferLength++] = chunk[i];
  36615. }
  36616. this.bufferLength = bufferLength;
  36617. };
  36618. return DecryptStream;
  36619. })();
  36620. var Ascii85Stream = (function Ascii85StreamClosure() {
  36621. function Ascii85Stream(str, maybeLength) {
  36622. this.str = str;
  36623. this.dict = str.dict;
  36624. this.input = new Uint8Array(5);
  36625. // Most streams increase in size when decoded, but Ascii85 streams
  36626. // typically shrink by ~20%.
  36627. if (maybeLength) {
  36628. maybeLength = 0.8 * maybeLength;
  36629. }
  36630. DecodeStream.call(this, maybeLength);
  36631. }
  36632. Ascii85Stream.prototype = Object.create(DecodeStream.prototype);
  36633. Ascii85Stream.prototype.readBlock = function Ascii85Stream_readBlock() {
  36634. var TILDA_CHAR = 0x7E; // '~'
  36635. var Z_LOWER_CHAR = 0x7A; // 'z'
  36636. var EOF = -1;
  36637. var str = this.str;
  36638. var c = str.getByte();
  36639. while (Lexer.isSpace(c)) {
  36640. c = str.getByte();
  36641. }
  36642. if (c === EOF || c === TILDA_CHAR) {
  36643. this.eof = true;
  36644. return;
  36645. }
  36646. var bufferLength = this.bufferLength, buffer;
  36647. var i;
  36648. // special code for z
  36649. if (c === Z_LOWER_CHAR) {
  36650. buffer = this.ensureBuffer(bufferLength + 4);
  36651. for (i = 0; i < 4; ++i) {
  36652. buffer[bufferLength + i] = 0;
  36653. }
  36654. this.bufferLength += 4;
  36655. } else {
  36656. var input = this.input;
  36657. input[0] = c;
  36658. for (i = 1; i < 5; ++i) {
  36659. c = str.getByte();
  36660. while (Lexer.isSpace(c)) {
  36661. c = str.getByte();
  36662. }
  36663. input[i] = c;
  36664. if (c === EOF || c === TILDA_CHAR) {
  36665. break;
  36666. }
  36667. }
  36668. buffer = this.ensureBuffer(bufferLength + i - 1);
  36669. this.bufferLength += i - 1;
  36670. // partial ending;
  36671. if (i < 5) {
  36672. for (; i < 5; ++i) {
  36673. input[i] = 0x21 + 84;
  36674. }
  36675. this.eof = true;
  36676. }
  36677. var t = 0;
  36678. for (i = 0; i < 5; ++i) {
  36679. t = t * 85 + (input[i] - 0x21);
  36680. }
  36681. for (i = 3; i >= 0; --i) {
  36682. buffer[bufferLength + i] = t & 0xFF;
  36683. t >>= 8;
  36684. }
  36685. }
  36686. };
  36687. return Ascii85Stream;
  36688. })();
  36689. var AsciiHexStream = (function AsciiHexStreamClosure() {
  36690. function AsciiHexStream(str, maybeLength) {
  36691. this.str = str;
  36692. this.dict = str.dict;
  36693. this.firstDigit = -1;
  36694. // Most streams increase in size when decoded, but AsciiHex streams shrink
  36695. // by 50%.
  36696. if (maybeLength) {
  36697. maybeLength = 0.5 * maybeLength;
  36698. }
  36699. DecodeStream.call(this, maybeLength);
  36700. }
  36701. AsciiHexStream.prototype = Object.create(DecodeStream.prototype);
  36702. AsciiHexStream.prototype.readBlock = function AsciiHexStream_readBlock() {
  36703. var UPSTREAM_BLOCK_SIZE = 8000;
  36704. var bytes = this.str.getBytes(UPSTREAM_BLOCK_SIZE);
  36705. if (!bytes.length) {
  36706. this.eof = true;
  36707. return;
  36708. }
  36709. var maxDecodeLength = (bytes.length + 1) >> 1;
  36710. var buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);
  36711. var bufferLength = this.bufferLength;
  36712. var firstDigit = this.firstDigit;
  36713. for (var i = 0, ii = bytes.length; i < ii; i++) {
  36714. var ch = bytes[i], digit;
  36715. if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
  36716. digit = ch & 0x0F;
  36717. } else if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
  36718. // 'A'-'Z', 'a'-'z'
  36719. digit = (ch & 0x0F) + 9;
  36720. } else if (ch === 0x3E) { // '>'
  36721. this.eof = true;
  36722. break;
  36723. } else { // probably whitespace
  36724. continue; // ignoring
  36725. }
  36726. if (firstDigit < 0) {
  36727. firstDigit = digit;
  36728. } else {
  36729. buffer[bufferLength++] = (firstDigit << 4) | digit;
  36730. firstDigit = -1;
  36731. }
  36732. }
  36733. if (firstDigit >= 0 && this.eof) {
  36734. // incomplete byte
  36735. buffer[bufferLength++] = (firstDigit << 4);
  36736. firstDigit = -1;
  36737. }
  36738. this.firstDigit = firstDigit;
  36739. this.bufferLength = bufferLength;
  36740. };
  36741. return AsciiHexStream;
  36742. })();
  36743. var RunLengthStream = (function RunLengthStreamClosure() {
  36744. function RunLengthStream(str, maybeLength) {
  36745. this.str = str;
  36746. this.dict = str.dict;
  36747. DecodeStream.call(this, maybeLength);
  36748. }
  36749. RunLengthStream.prototype = Object.create(DecodeStream.prototype);
  36750. RunLengthStream.prototype.readBlock = function RunLengthStream_readBlock() {
  36751. // The repeatHeader has following format. The first byte defines type of run
  36752. // and amount of bytes to repeat/copy: n = 0 through 127 - copy next n bytes
  36753. // (in addition to the second byte from the header), n = 129 through 255 -
  36754. // duplicate the second byte from the header (257 - n) times, n = 128 - end.
  36755. var repeatHeader = this.str.getBytes(2);
  36756. if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] === 128) {
  36757. this.eof = true;
  36758. return;
  36759. }
  36760. var buffer;
  36761. var bufferLength = this.bufferLength;
  36762. var n = repeatHeader[0];
  36763. if (n < 128) {
  36764. // copy n bytes
  36765. buffer = this.ensureBuffer(bufferLength + n + 1);
  36766. buffer[bufferLength++] = repeatHeader[1];
  36767. if (n > 0) {
  36768. var source = this.str.getBytes(n);
  36769. buffer.set(source, bufferLength);
  36770. bufferLength += n;
  36771. }
  36772. } else {
  36773. n = 257 - n;
  36774. var b = repeatHeader[1];
  36775. buffer = this.ensureBuffer(bufferLength + n + 1);
  36776. for (var i = 0; i < n; i++) {
  36777. buffer[bufferLength++] = b;
  36778. }
  36779. }
  36780. this.bufferLength = bufferLength;
  36781. };
  36782. return RunLengthStream;
  36783. })();
  36784. var CCITTFaxStream = (function CCITTFaxStreamClosure() {
  36785. var ccittEOL = -2;
  36786. var twoDimPass = 0;
  36787. var twoDimHoriz = 1;
  36788. var twoDimVert0 = 2;
  36789. var twoDimVertR1 = 3;
  36790. var twoDimVertL1 = 4;
  36791. var twoDimVertR2 = 5;
  36792. var twoDimVertL2 = 6;
  36793. var twoDimVertR3 = 7;
  36794. var twoDimVertL3 = 8;
  36795. var twoDimTable = [
  36796. [-1, -1], [-1, -1], // 000000x
  36797. [7, twoDimVertL3], // 0000010
  36798. [7, twoDimVertR3], // 0000011
  36799. [6, twoDimVertL2], [6, twoDimVertL2], // 000010x
  36800. [6, twoDimVertR2], [6, twoDimVertR2], // 000011x
  36801. [4, twoDimPass], [4, twoDimPass], // 0001xxx
  36802. [4, twoDimPass], [4, twoDimPass],
  36803. [4, twoDimPass], [4, twoDimPass],
  36804. [4, twoDimPass], [4, twoDimPass],
  36805. [3, twoDimHoriz], [3, twoDimHoriz], // 001xxxx
  36806. [3, twoDimHoriz], [3, twoDimHoriz],
  36807. [3, twoDimHoriz], [3, twoDimHoriz],
  36808. [3, twoDimHoriz], [3, twoDimHoriz],
  36809. [3, twoDimHoriz], [3, twoDimHoriz],
  36810. [3, twoDimHoriz], [3, twoDimHoriz],
  36811. [3, twoDimHoriz], [3, twoDimHoriz],
  36812. [3, twoDimHoriz], [3, twoDimHoriz],
  36813. [3, twoDimVertL1], [3, twoDimVertL1], // 010xxxx
  36814. [3, twoDimVertL1], [3, twoDimVertL1],
  36815. [3, twoDimVertL1], [3, twoDimVertL1],
  36816. [3, twoDimVertL1], [3, twoDimVertL1],
  36817. [3, twoDimVertL1], [3, twoDimVertL1],
  36818. [3, twoDimVertL1], [3, twoDimVertL1],
  36819. [3, twoDimVertL1], [3, twoDimVertL1],
  36820. [3, twoDimVertL1], [3, twoDimVertL1],
  36821. [3, twoDimVertR1], [3, twoDimVertR1], // 011xxxx
  36822. [3, twoDimVertR1], [3, twoDimVertR1],
  36823. [3, twoDimVertR1], [3, twoDimVertR1],
  36824. [3, twoDimVertR1], [3, twoDimVertR1],
  36825. [3, twoDimVertR1], [3, twoDimVertR1],
  36826. [3, twoDimVertR1], [3, twoDimVertR1],
  36827. [3, twoDimVertR1], [3, twoDimVertR1],
  36828. [3, twoDimVertR1], [3, twoDimVertR1],
  36829. [1, twoDimVert0], [1, twoDimVert0], // 1xxxxxx
  36830. [1, twoDimVert0], [1, twoDimVert0],
  36831. [1, twoDimVert0], [1, twoDimVert0],
  36832. [1, twoDimVert0], [1, twoDimVert0],
  36833. [1, twoDimVert0], [1, twoDimVert0],
  36834. [1, twoDimVert0], [1, twoDimVert0],
  36835. [1, twoDimVert0], [1, twoDimVert0],
  36836. [1, twoDimVert0], [1, twoDimVert0],
  36837. [1, twoDimVert0], [1, twoDimVert0],
  36838. [1, twoDimVert0], [1, twoDimVert0],
  36839. [1, twoDimVert0], [1, twoDimVert0],
  36840. [1, twoDimVert0], [1, twoDimVert0],
  36841. [1, twoDimVert0], [1, twoDimVert0],
  36842. [1, twoDimVert0], [1, twoDimVert0],
  36843. [1, twoDimVert0], [1, twoDimVert0],
  36844. [1, twoDimVert0], [1, twoDimVert0],
  36845. [1, twoDimVert0], [1, twoDimVert0],
  36846. [1, twoDimVert0], [1, twoDimVert0],
  36847. [1, twoDimVert0], [1, twoDimVert0],
  36848. [1, twoDimVert0], [1, twoDimVert0],
  36849. [1, twoDimVert0], [1, twoDimVert0],
  36850. [1, twoDimVert0], [1, twoDimVert0],
  36851. [1, twoDimVert0], [1, twoDimVert0],
  36852. [1, twoDimVert0], [1, twoDimVert0],
  36853. [1, twoDimVert0], [1, twoDimVert0],
  36854. [1, twoDimVert0], [1, twoDimVert0],
  36855. [1, twoDimVert0], [1, twoDimVert0],
  36856. [1, twoDimVert0], [1, twoDimVert0],
  36857. [1, twoDimVert0], [1, twoDimVert0],
  36858. [1, twoDimVert0], [1, twoDimVert0],
  36859. [1, twoDimVert0], [1, twoDimVert0],
  36860. [1, twoDimVert0], [1, twoDimVert0]
  36861. ];
  36862. var whiteTable1 = [
  36863. [-1, -1], // 00000
  36864. [12, ccittEOL], // 00001
  36865. [-1, -1], [-1, -1], // 0001x
  36866. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 001xx
  36867. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 010xx
  36868. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 011xx
  36869. [11, 1792], [11, 1792], // 1000x
  36870. [12, 1984], // 10010
  36871. [12, 2048], // 10011
  36872. [12, 2112], // 10100
  36873. [12, 2176], // 10101
  36874. [12, 2240], // 10110
  36875. [12, 2304], // 10111
  36876. [11, 1856], [11, 1856], // 1100x
  36877. [11, 1920], [11, 1920], // 1101x
  36878. [12, 2368], // 11100
  36879. [12, 2432], // 11101
  36880. [12, 2496], // 11110
  36881. [12, 2560] // 11111
  36882. ];
  36883. var whiteTable2 = [
  36884. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 0000000xx
  36885. [8, 29], [8, 29], // 00000010x
  36886. [8, 30], [8, 30], // 00000011x
  36887. [8, 45], [8, 45], // 00000100x
  36888. [8, 46], [8, 46], // 00000101x
  36889. [7, 22], [7, 22], [7, 22], [7, 22], // 0000011xx
  36890. [7, 23], [7, 23], [7, 23], [7, 23], // 0000100xx
  36891. [8, 47], [8, 47], // 00001010x
  36892. [8, 48], [8, 48], // 00001011x
  36893. [6, 13], [6, 13], [6, 13], [6, 13], // 000011xxx
  36894. [6, 13], [6, 13], [6, 13], [6, 13],
  36895. [7, 20], [7, 20], [7, 20], [7, 20], // 0001000xx
  36896. [8, 33], [8, 33], // 00010010x
  36897. [8, 34], [8, 34], // 00010011x
  36898. [8, 35], [8, 35], // 00010100x
  36899. [8, 36], [8, 36], // 00010101x
  36900. [8, 37], [8, 37], // 00010110x
  36901. [8, 38], [8, 38], // 00010111x
  36902. [7, 19], [7, 19], [7, 19], [7, 19], // 0001100xx
  36903. [8, 31], [8, 31], // 00011010x
  36904. [8, 32], [8, 32], // 00011011x
  36905. [6, 1], [6, 1], [6, 1], [6, 1], // 000111xxx
  36906. [6, 1], [6, 1], [6, 1], [6, 1],
  36907. [6, 12], [6, 12], [6, 12], [6, 12], // 001000xxx
  36908. [6, 12], [6, 12], [6, 12], [6, 12],
  36909. [8, 53], [8, 53], // 00100100x
  36910. [8, 54], [8, 54], // 00100101x
  36911. [7, 26], [7, 26], [7, 26], [7, 26], // 0010011xx
  36912. [8, 39], [8, 39], // 00101000x
  36913. [8, 40], [8, 40], // 00101001x
  36914. [8, 41], [8, 41], // 00101010x
  36915. [8, 42], [8, 42], // 00101011x
  36916. [8, 43], [8, 43], // 00101100x
  36917. [8, 44], [8, 44], // 00101101x
  36918. [7, 21], [7, 21], [7, 21], [7, 21], // 0010111xx
  36919. [7, 28], [7, 28], [7, 28], [7, 28], // 0011000xx
  36920. [8, 61], [8, 61], // 00110010x
  36921. [8, 62], [8, 62], // 00110011x
  36922. [8, 63], [8, 63], // 00110100x
  36923. [8, 0], [8, 0], // 00110101x
  36924. [8, 320], [8, 320], // 00110110x
  36925. [8, 384], [8, 384], // 00110111x
  36926. [5, 10], [5, 10], [5, 10], [5, 10], // 00111xxxx
  36927. [5, 10], [5, 10], [5, 10], [5, 10],
  36928. [5, 10], [5, 10], [5, 10], [5, 10],
  36929. [5, 10], [5, 10], [5, 10], [5, 10],
  36930. [5, 11], [5, 11], [5, 11], [5, 11], // 01000xxxx
  36931. [5, 11], [5, 11], [5, 11], [5, 11],
  36932. [5, 11], [5, 11], [5, 11], [5, 11],
  36933. [5, 11], [5, 11], [5, 11], [5, 11],
  36934. [7, 27], [7, 27], [7, 27], [7, 27], // 0100100xx
  36935. [8, 59], [8, 59], // 01001010x
  36936. [8, 60], [8, 60], // 01001011x
  36937. [9, 1472], // 010011000
  36938. [9, 1536], // 010011001
  36939. [9, 1600], // 010011010
  36940. [9, 1728], // 010011011
  36941. [7, 18], [7, 18], [7, 18], [7, 18], // 0100111xx
  36942. [7, 24], [7, 24], [7, 24], [7, 24], // 0101000xx
  36943. [8, 49], [8, 49], // 01010010x
  36944. [8, 50], [8, 50], // 01010011x
  36945. [8, 51], [8, 51], // 01010100x
  36946. [8, 52], [8, 52], // 01010101x
  36947. [7, 25], [7, 25], [7, 25], [7, 25], // 0101011xx
  36948. [8, 55], [8, 55], // 01011000x
  36949. [8, 56], [8, 56], // 01011001x
  36950. [8, 57], [8, 57], // 01011010x
  36951. [8, 58], [8, 58], // 01011011x
  36952. [6, 192], [6, 192], [6, 192], [6, 192], // 010111xxx
  36953. [6, 192], [6, 192], [6, 192], [6, 192],
  36954. [6, 1664], [6, 1664], [6, 1664], [6, 1664], // 011000xxx
  36955. [6, 1664], [6, 1664], [6, 1664], [6, 1664],
  36956. [8, 448], [8, 448], // 01100100x
  36957. [8, 512], [8, 512], // 01100101x
  36958. [9, 704], // 011001100
  36959. [9, 768], // 011001101
  36960. [8, 640], [8, 640], // 01100111x
  36961. [8, 576], [8, 576], // 01101000x
  36962. [9, 832], // 011010010
  36963. [9, 896], // 011010011
  36964. [9, 960], // 011010100
  36965. [9, 1024], // 011010101
  36966. [9, 1088], // 011010110
  36967. [9, 1152], // 011010111
  36968. [9, 1216], // 011011000
  36969. [9, 1280], // 011011001
  36970. [9, 1344], // 011011010
  36971. [9, 1408], // 011011011
  36972. [7, 256], [7, 256], [7, 256], [7, 256], // 0110111xx
  36973. [4, 2], [4, 2], [4, 2], [4, 2], // 0111xxxxx
  36974. [4, 2], [4, 2], [4, 2], [4, 2],
  36975. [4, 2], [4, 2], [4, 2], [4, 2],
  36976. [4, 2], [4, 2], [4, 2], [4, 2],
  36977. [4, 2], [4, 2], [4, 2], [4, 2],
  36978. [4, 2], [4, 2], [4, 2], [4, 2],
  36979. [4, 2], [4, 2], [4, 2], [4, 2],
  36980. [4, 2], [4, 2], [4, 2], [4, 2],
  36981. [4, 3], [4, 3], [4, 3], [4, 3], // 1000xxxxx
  36982. [4, 3], [4, 3], [4, 3], [4, 3],
  36983. [4, 3], [4, 3], [4, 3], [4, 3],
  36984. [4, 3], [4, 3], [4, 3], [4, 3],
  36985. [4, 3], [4, 3], [4, 3], [4, 3],
  36986. [4, 3], [4, 3], [4, 3], [4, 3],
  36987. [4, 3], [4, 3], [4, 3], [4, 3],
  36988. [4, 3], [4, 3], [4, 3], [4, 3],
  36989. [5, 128], [5, 128], [5, 128], [5, 128], // 10010xxxx
  36990. [5, 128], [5, 128], [5, 128], [5, 128],
  36991. [5, 128], [5, 128], [5, 128], [5, 128],
  36992. [5, 128], [5, 128], [5, 128], [5, 128],
  36993. [5, 8], [5, 8], [5, 8], [5, 8], // 10011xxxx
  36994. [5, 8], [5, 8], [5, 8], [5, 8],
  36995. [5, 8], [5, 8], [5, 8], [5, 8],
  36996. [5, 8], [5, 8], [5, 8], [5, 8],
  36997. [5, 9], [5, 9], [5, 9], [5, 9], // 10100xxxx
  36998. [5, 9], [5, 9], [5, 9], [5, 9],
  36999. [5, 9], [5, 9], [5, 9], [5, 9],
  37000. [5, 9], [5, 9], [5, 9], [5, 9],
  37001. [6, 16], [6, 16], [6, 16], [6, 16], // 101010xxx
  37002. [6, 16], [6, 16], [6, 16], [6, 16],
  37003. [6, 17], [6, 17], [6, 17], [6, 17], // 101011xxx
  37004. [6, 17], [6, 17], [6, 17], [6, 17],
  37005. [4, 4], [4, 4], [4, 4], [4, 4], // 1011xxxxx
  37006. [4, 4], [4, 4], [4, 4], [4, 4],
  37007. [4, 4], [4, 4], [4, 4], [4, 4],
  37008. [4, 4], [4, 4], [4, 4], [4, 4],
  37009. [4, 4], [4, 4], [4, 4], [4, 4],
  37010. [4, 4], [4, 4], [4, 4], [4, 4],
  37011. [4, 4], [4, 4], [4, 4], [4, 4],
  37012. [4, 4], [4, 4], [4, 4], [4, 4],
  37013. [4, 5], [4, 5], [4, 5], [4, 5], // 1100xxxxx
  37014. [4, 5], [4, 5], [4, 5], [4, 5],
  37015. [4, 5], [4, 5], [4, 5], [4, 5],
  37016. [4, 5], [4, 5], [4, 5], [4, 5],
  37017. [4, 5], [4, 5], [4, 5], [4, 5],
  37018. [4, 5], [4, 5], [4, 5], [4, 5],
  37019. [4, 5], [4, 5], [4, 5], [4, 5],
  37020. [4, 5], [4, 5], [4, 5], [4, 5],
  37021. [6, 14], [6, 14], [6, 14], [6, 14], // 110100xxx
  37022. [6, 14], [6, 14], [6, 14], [6, 14],
  37023. [6, 15], [6, 15], [6, 15], [6, 15], // 110101xxx
  37024. [6, 15], [6, 15], [6, 15], [6, 15],
  37025. [5, 64], [5, 64], [5, 64], [5, 64], // 11011xxxx
  37026. [5, 64], [5, 64], [5, 64], [5, 64],
  37027. [5, 64], [5, 64], [5, 64], [5, 64],
  37028. [5, 64], [5, 64], [5, 64], [5, 64],
  37029. [4, 6], [4, 6], [4, 6], [4, 6], // 1110xxxxx
  37030. [4, 6], [4, 6], [4, 6], [4, 6],
  37031. [4, 6], [4, 6], [4, 6], [4, 6],
  37032. [4, 6], [4, 6], [4, 6], [4, 6],
  37033. [4, 6], [4, 6], [4, 6], [4, 6],
  37034. [4, 6], [4, 6], [4, 6], [4, 6],
  37035. [4, 6], [4, 6], [4, 6], [4, 6],
  37036. [4, 6], [4, 6], [4, 6], [4, 6],
  37037. [4, 7], [4, 7], [4, 7], [4, 7], // 1111xxxxx
  37038. [4, 7], [4, 7], [4, 7], [4, 7],
  37039. [4, 7], [4, 7], [4, 7], [4, 7],
  37040. [4, 7], [4, 7], [4, 7], [4, 7],
  37041. [4, 7], [4, 7], [4, 7], [4, 7],
  37042. [4, 7], [4, 7], [4, 7], [4, 7],
  37043. [4, 7], [4, 7], [4, 7], [4, 7],
  37044. [4, 7], [4, 7], [4, 7], [4, 7]
  37045. ];
  37046. var blackTable1 = [
  37047. [-1, -1], [-1, -1], // 000000000000x
  37048. [12, ccittEOL], [12, ccittEOL], // 000000000001x
  37049. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000001xx
  37050. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000010xx
  37051. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000011xx
  37052. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000100xx
  37053. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000101xx
  37054. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000110xx
  37055. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000111xx
  37056. [11, 1792], [11, 1792], [11, 1792], [11, 1792], // 00000001000xx
  37057. [12, 1984], [12, 1984], // 000000010010x
  37058. [12, 2048], [12, 2048], // 000000010011x
  37059. [12, 2112], [12, 2112], // 000000010100x
  37060. [12, 2176], [12, 2176], // 000000010101x
  37061. [12, 2240], [12, 2240], // 000000010110x
  37062. [12, 2304], [12, 2304], // 000000010111x
  37063. [11, 1856], [11, 1856], [11, 1856], [11, 1856], // 00000001100xx
  37064. [11, 1920], [11, 1920], [11, 1920], [11, 1920], // 00000001101xx
  37065. [12, 2368], [12, 2368], // 000000011100x
  37066. [12, 2432], [12, 2432], // 000000011101x
  37067. [12, 2496], [12, 2496], // 000000011110x
  37068. [12, 2560], [12, 2560], // 000000011111x
  37069. [10, 18], [10, 18], [10, 18], [10, 18], // 0000001000xxx
  37070. [10, 18], [10, 18], [10, 18], [10, 18],
  37071. [12, 52], [12, 52], // 000000100100x
  37072. [13, 640], // 0000001001010
  37073. [13, 704], // 0000001001011
  37074. [13, 768], // 0000001001100
  37075. [13, 832], // 0000001001101
  37076. [12, 55], [12, 55], // 000000100111x
  37077. [12, 56], [12, 56], // 000000101000x
  37078. [13, 1280], // 0000001010010
  37079. [13, 1344], // 0000001010011
  37080. [13, 1408], // 0000001010100
  37081. [13, 1472], // 0000001010101
  37082. [12, 59], [12, 59], // 000000101011x
  37083. [12, 60], [12, 60], // 000000101100x
  37084. [13, 1536], // 0000001011010
  37085. [13, 1600], // 0000001011011
  37086. [11, 24], [11, 24], [11, 24], [11, 24], // 00000010111xx
  37087. [11, 25], [11, 25], [11, 25], [11, 25], // 00000011000xx
  37088. [13, 1664], // 0000001100100
  37089. [13, 1728], // 0000001100101
  37090. [12, 320], [12, 320], // 000000110011x
  37091. [12, 384], [12, 384], // 000000110100x
  37092. [12, 448], [12, 448], // 000000110101x
  37093. [13, 512], // 0000001101100
  37094. [13, 576], // 0000001101101
  37095. [12, 53], [12, 53], // 000000110111x
  37096. [12, 54], [12, 54], // 000000111000x
  37097. [13, 896], // 0000001110010
  37098. [13, 960], // 0000001110011
  37099. [13, 1024], // 0000001110100
  37100. [13, 1088], // 0000001110101
  37101. [13, 1152], // 0000001110110
  37102. [13, 1216], // 0000001110111
  37103. [10, 64], [10, 64], [10, 64], [10, 64], // 0000001111xxx
  37104. [10, 64], [10, 64], [10, 64], [10, 64]
  37105. ];
  37106. var blackTable2 = [
  37107. [8, 13], [8, 13], [8, 13], [8, 13], // 00000100xxxx
  37108. [8, 13], [8, 13], [8, 13], [8, 13],
  37109. [8, 13], [8, 13], [8, 13], [8, 13],
  37110. [8, 13], [8, 13], [8, 13], [8, 13],
  37111. [11, 23], [11, 23], // 00000101000x
  37112. [12, 50], // 000001010010
  37113. [12, 51], // 000001010011
  37114. [12, 44], // 000001010100
  37115. [12, 45], // 000001010101
  37116. [12, 46], // 000001010110
  37117. [12, 47], // 000001010111
  37118. [12, 57], // 000001011000
  37119. [12, 58], // 000001011001
  37120. [12, 61], // 000001011010
  37121. [12, 256], // 000001011011
  37122. [10, 16], [10, 16], [10, 16], [10, 16], // 0000010111xx
  37123. [10, 17], [10, 17], [10, 17], [10, 17], // 0000011000xx
  37124. [12, 48], // 000001100100
  37125. [12, 49], // 000001100101
  37126. [12, 62], // 000001100110
  37127. [12, 63], // 000001100111
  37128. [12, 30], // 000001101000
  37129. [12, 31], // 000001101001
  37130. [12, 32], // 000001101010
  37131. [12, 33], // 000001101011
  37132. [12, 40], // 000001101100
  37133. [12, 41], // 000001101101
  37134. [11, 22], [11, 22], // 00000110111x
  37135. [8, 14], [8, 14], [8, 14], [8, 14], // 00000111xxxx
  37136. [8, 14], [8, 14], [8, 14], [8, 14],
  37137. [8, 14], [8, 14], [8, 14], [8, 14],
  37138. [8, 14], [8, 14], [8, 14], [8, 14],
  37139. [7, 10], [7, 10], [7, 10], [7, 10], // 0000100xxxxx
  37140. [7, 10], [7, 10], [7, 10], [7, 10],
  37141. [7, 10], [7, 10], [7, 10], [7, 10],
  37142. [7, 10], [7, 10], [7, 10], [7, 10],
  37143. [7, 10], [7, 10], [7, 10], [7, 10],
  37144. [7, 10], [7, 10], [7, 10], [7, 10],
  37145. [7, 10], [7, 10], [7, 10], [7, 10],
  37146. [7, 10], [7, 10], [7, 10], [7, 10],
  37147. [7, 11], [7, 11], [7, 11], [7, 11], // 0000101xxxxx
  37148. [7, 11], [7, 11], [7, 11], [7, 11],
  37149. [7, 11], [7, 11], [7, 11], [7, 11],
  37150. [7, 11], [7, 11], [7, 11], [7, 11],
  37151. [7, 11], [7, 11], [7, 11], [7, 11],
  37152. [7, 11], [7, 11], [7, 11], [7, 11],
  37153. [7, 11], [7, 11], [7, 11], [7, 11],
  37154. [7, 11], [7, 11], [7, 11], [7, 11],
  37155. [9, 15], [9, 15], [9, 15], [9, 15], // 000011000xxx
  37156. [9, 15], [9, 15], [9, 15], [9, 15],
  37157. [12, 128], // 000011001000
  37158. [12, 192], // 000011001001
  37159. [12, 26], // 000011001010
  37160. [12, 27], // 000011001011
  37161. [12, 28], // 000011001100
  37162. [12, 29], // 000011001101
  37163. [11, 19], [11, 19], // 00001100111x
  37164. [11, 20], [11, 20], // 00001101000x
  37165. [12, 34], // 000011010010
  37166. [12, 35], // 000011010011
  37167. [12, 36], // 000011010100
  37168. [12, 37], // 000011010101
  37169. [12, 38], // 000011010110
  37170. [12, 39], // 000011010111
  37171. [11, 21], [11, 21], // 00001101100x
  37172. [12, 42], // 000011011010
  37173. [12, 43], // 000011011011
  37174. [10, 0], [10, 0], [10, 0], [10, 0], // 0000110111xx
  37175. [7, 12], [7, 12], [7, 12], [7, 12], // 0000111xxxxx
  37176. [7, 12], [7, 12], [7, 12], [7, 12],
  37177. [7, 12], [7, 12], [7, 12], [7, 12],
  37178. [7, 12], [7, 12], [7, 12], [7, 12],
  37179. [7, 12], [7, 12], [7, 12], [7, 12],
  37180. [7, 12], [7, 12], [7, 12], [7, 12],
  37181. [7, 12], [7, 12], [7, 12], [7, 12],
  37182. [7, 12], [7, 12], [7, 12], [7, 12]
  37183. ];
  37184. var blackTable3 = [
  37185. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 0000xx
  37186. [6, 9], // 000100
  37187. [6, 8], // 000101
  37188. [5, 7], [5, 7], // 00011x
  37189. [4, 6], [4, 6], [4, 6], [4, 6], // 0010xx
  37190. [4, 5], [4, 5], [4, 5], [4, 5], // 0011xx
  37191. [3, 1], [3, 1], [3, 1], [3, 1], // 010xxx
  37192. [3, 1], [3, 1], [3, 1], [3, 1],
  37193. [3, 4], [3, 4], [3, 4], [3, 4], // 011xxx
  37194. [3, 4], [3, 4], [3, 4], [3, 4],
  37195. [2, 3], [2, 3], [2, 3], [2, 3], // 10xxxx
  37196. [2, 3], [2, 3], [2, 3], [2, 3],
  37197. [2, 3], [2, 3], [2, 3], [2, 3],
  37198. [2, 3], [2, 3], [2, 3], [2, 3],
  37199. [2, 2], [2, 2], [2, 2], [2, 2], // 11xxxx
  37200. [2, 2], [2, 2], [2, 2], [2, 2],
  37201. [2, 2], [2, 2], [2, 2], [2, 2],
  37202. [2, 2], [2, 2], [2, 2], [2, 2]
  37203. ];
  37204. function CCITTFaxStream(str, maybeLength, params) {
  37205. this.str = str;
  37206. this.dict = str.dict;
  37207. params = params || Dict.empty;
  37208. this.encoding = params.get('K') || 0;
  37209. this.eoline = params.get('EndOfLine') || false;
  37210. this.byteAlign = params.get('EncodedByteAlign') || false;
  37211. this.columns = params.get('Columns') || 1728;
  37212. this.rows = params.get('Rows') || 0;
  37213. var eoblock = params.get('EndOfBlock');
  37214. if (eoblock === null || eoblock === undefined) {
  37215. eoblock = true;
  37216. }
  37217. this.eoblock = eoblock;
  37218. this.black = params.get('BlackIs1') || false;
  37219. this.codingLine = new Uint32Array(this.columns + 1);
  37220. this.refLine = new Uint32Array(this.columns + 2);
  37221. this.codingLine[0] = this.columns;
  37222. this.codingPos = 0;
  37223. this.row = 0;
  37224. this.nextLine2D = this.encoding < 0;
  37225. this.inputBits = 0;
  37226. this.inputBuf = 0;
  37227. this.outputBits = 0;
  37228. var code1;
  37229. while ((code1 = this.lookBits(12)) === 0) {
  37230. this.eatBits(1);
  37231. }
  37232. if (code1 === 1) {
  37233. this.eatBits(12);
  37234. }
  37235. if (this.encoding > 0) {
  37236. this.nextLine2D = !this.lookBits(1);
  37237. this.eatBits(1);
  37238. }
  37239. DecodeStream.call(this, maybeLength);
  37240. }
  37241. CCITTFaxStream.prototype = Object.create(DecodeStream.prototype);
  37242. CCITTFaxStream.prototype.readBlock = function CCITTFaxStream_readBlock() {
  37243. while (!this.eof) {
  37244. var c = this.lookChar();
  37245. this.ensureBuffer(this.bufferLength + 1);
  37246. this.buffer[this.bufferLength++] = c;
  37247. }
  37248. };
  37249. CCITTFaxStream.prototype.addPixels =
  37250. function ccittFaxStreamAddPixels(a1, blackPixels) {
  37251. var codingLine = this.codingLine;
  37252. var codingPos = this.codingPos;
  37253. if (a1 > codingLine[codingPos]) {
  37254. if (a1 > this.columns) {
  37255. info('row is wrong length');
  37256. this.err = true;
  37257. a1 = this.columns;
  37258. }
  37259. if ((codingPos & 1) ^ blackPixels) {
  37260. ++codingPos;
  37261. }
  37262. codingLine[codingPos] = a1;
  37263. }
  37264. this.codingPos = codingPos;
  37265. };
  37266. CCITTFaxStream.prototype.addPixelsNeg =
  37267. function ccittFaxStreamAddPixelsNeg(a1, blackPixels) {
  37268. var codingLine = this.codingLine;
  37269. var codingPos = this.codingPos;
  37270. if (a1 > codingLine[codingPos]) {
  37271. if (a1 > this.columns) {
  37272. info('row is wrong length');
  37273. this.err = true;
  37274. a1 = this.columns;
  37275. }
  37276. if ((codingPos & 1) ^ blackPixels) {
  37277. ++codingPos;
  37278. }
  37279. codingLine[codingPos] = a1;
  37280. } else if (a1 < codingLine[codingPos]) {
  37281. if (a1 < 0) {
  37282. info('invalid code');
  37283. this.err = true;
  37284. a1 = 0;
  37285. }
  37286. while (codingPos > 0 && a1 < codingLine[codingPos - 1]) {
  37287. --codingPos;
  37288. }
  37289. codingLine[codingPos] = a1;
  37290. }
  37291. this.codingPos = codingPos;
  37292. };
  37293. CCITTFaxStream.prototype.lookChar = function CCITTFaxStream_lookChar() {
  37294. var refLine = this.refLine;
  37295. var codingLine = this.codingLine;
  37296. var columns = this.columns;
  37297. var refPos, blackPixels, bits, i;
  37298. if (this.outputBits === 0) {
  37299. if (this.eof) {
  37300. return null;
  37301. }
  37302. this.err = false;
  37303. var code1, code2, code3;
  37304. if (this.nextLine2D) {
  37305. for (i = 0; codingLine[i] < columns; ++i) {
  37306. refLine[i] = codingLine[i];
  37307. }
  37308. refLine[i++] = columns;
  37309. refLine[i] = columns;
  37310. codingLine[0] = 0;
  37311. this.codingPos = 0;
  37312. refPos = 0;
  37313. blackPixels = 0;
  37314. while (codingLine[this.codingPos] < columns) {
  37315. code1 = this.getTwoDimCode();
  37316. switch (code1) {
  37317. case twoDimPass:
  37318. this.addPixels(refLine[refPos + 1], blackPixels);
  37319. if (refLine[refPos + 1] < columns) {
  37320. refPos += 2;
  37321. }
  37322. break;
  37323. case twoDimHoriz:
  37324. code1 = code2 = 0;
  37325. if (blackPixels) {
  37326. do {
  37327. code1 += (code3 = this.getBlackCode());
  37328. } while (code3 >= 64);
  37329. do {
  37330. code2 += (code3 = this.getWhiteCode());
  37331. } while (code3 >= 64);
  37332. } else {
  37333. do {
  37334. code1 += (code3 = this.getWhiteCode());
  37335. } while (code3 >= 64);
  37336. do {
  37337. code2 += (code3 = this.getBlackCode());
  37338. } while (code3 >= 64);
  37339. }
  37340. this.addPixels(codingLine[this.codingPos] +
  37341. code1, blackPixels);
  37342. if (codingLine[this.codingPos] < columns) {
  37343. this.addPixels(codingLine[this.codingPos] + code2,
  37344. blackPixels ^ 1);
  37345. }
  37346. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37347. refLine[refPos] < columns) {
  37348. refPos += 2;
  37349. }
  37350. break;
  37351. case twoDimVertR3:
  37352. this.addPixels(refLine[refPos] + 3, blackPixels);
  37353. blackPixels ^= 1;
  37354. if (codingLine[this.codingPos] < columns) {
  37355. ++refPos;
  37356. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37357. refLine[refPos] < columns) {
  37358. refPos += 2;
  37359. }
  37360. }
  37361. break;
  37362. case twoDimVertR2:
  37363. this.addPixels(refLine[refPos] + 2, blackPixels);
  37364. blackPixels ^= 1;
  37365. if (codingLine[this.codingPos] < columns) {
  37366. ++refPos;
  37367. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37368. refLine[refPos] < columns) {
  37369. refPos += 2;
  37370. }
  37371. }
  37372. break;
  37373. case twoDimVertR1:
  37374. this.addPixels(refLine[refPos] + 1, blackPixels);
  37375. blackPixels ^= 1;
  37376. if (codingLine[this.codingPos] < columns) {
  37377. ++refPos;
  37378. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37379. refLine[refPos] < columns) {
  37380. refPos += 2;
  37381. }
  37382. }
  37383. break;
  37384. case twoDimVert0:
  37385. this.addPixels(refLine[refPos], blackPixels);
  37386. blackPixels ^= 1;
  37387. if (codingLine[this.codingPos] < columns) {
  37388. ++refPos;
  37389. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37390. refLine[refPos] < columns) {
  37391. refPos += 2;
  37392. }
  37393. }
  37394. break;
  37395. case twoDimVertL3:
  37396. this.addPixelsNeg(refLine[refPos] - 3, blackPixels);
  37397. blackPixels ^= 1;
  37398. if (codingLine[this.codingPos] < columns) {
  37399. if (refPos > 0) {
  37400. --refPos;
  37401. } else {
  37402. ++refPos;
  37403. }
  37404. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37405. refLine[refPos] < columns) {
  37406. refPos += 2;
  37407. }
  37408. }
  37409. break;
  37410. case twoDimVertL2:
  37411. this.addPixelsNeg(refLine[refPos] - 2, blackPixels);
  37412. blackPixels ^= 1;
  37413. if (codingLine[this.codingPos] < columns) {
  37414. if (refPos > 0) {
  37415. --refPos;
  37416. } else {
  37417. ++refPos;
  37418. }
  37419. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37420. refLine[refPos] < columns) {
  37421. refPos += 2;
  37422. }
  37423. }
  37424. break;
  37425. case twoDimVertL1:
  37426. this.addPixelsNeg(refLine[refPos] - 1, blackPixels);
  37427. blackPixels ^= 1;
  37428. if (codingLine[this.codingPos] < columns) {
  37429. if (refPos > 0) {
  37430. --refPos;
  37431. } else {
  37432. ++refPos;
  37433. }
  37434. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37435. refLine[refPos] < columns) {
  37436. refPos += 2;
  37437. }
  37438. }
  37439. break;
  37440. case EOF:
  37441. this.addPixels(columns, 0);
  37442. this.eof = true;
  37443. break;
  37444. default:
  37445. info('bad 2d code');
  37446. this.addPixels(columns, 0);
  37447. this.err = true;
  37448. }
  37449. }
  37450. } else {
  37451. codingLine[0] = 0;
  37452. this.codingPos = 0;
  37453. blackPixels = 0;
  37454. while (codingLine[this.codingPos] < columns) {
  37455. code1 = 0;
  37456. if (blackPixels) {
  37457. do {
  37458. code1 += (code3 = this.getBlackCode());
  37459. } while (code3 >= 64);
  37460. } else {
  37461. do {
  37462. code1 += (code3 = this.getWhiteCode());
  37463. } while (code3 >= 64);
  37464. }
  37465. this.addPixels(codingLine[this.codingPos] + code1, blackPixels);
  37466. blackPixels ^= 1;
  37467. }
  37468. }
  37469. var gotEOL = false;
  37470. if (this.byteAlign) {
  37471. this.inputBits &= ~7;
  37472. }
  37473. if (!this.eoblock && this.row === this.rows - 1) {
  37474. this.eof = true;
  37475. } else {
  37476. code1 = this.lookBits(12);
  37477. if (this.eoline) {
  37478. while (code1 !== EOF && code1 !== 1) {
  37479. this.eatBits(1);
  37480. code1 = this.lookBits(12);
  37481. }
  37482. } else {
  37483. while (code1 === 0) {
  37484. this.eatBits(1);
  37485. code1 = this.lookBits(12);
  37486. }
  37487. }
  37488. if (code1 === 1) {
  37489. this.eatBits(12);
  37490. gotEOL = true;
  37491. } else if (code1 === EOF) {
  37492. this.eof = true;
  37493. }
  37494. }
  37495. if (!this.eof && this.encoding > 0) {
  37496. this.nextLine2D = !this.lookBits(1);
  37497. this.eatBits(1);
  37498. }
  37499. if (this.eoblock && gotEOL && this.byteAlign) {
  37500. code1 = this.lookBits(12);
  37501. if (code1 === 1) {
  37502. this.eatBits(12);
  37503. if (this.encoding > 0) {
  37504. this.lookBits(1);
  37505. this.eatBits(1);
  37506. }
  37507. if (this.encoding >= 0) {
  37508. for (i = 0; i < 4; ++i) {
  37509. code1 = this.lookBits(12);
  37510. if (code1 !== 1) {
  37511. info('bad rtc code: ' + code1);
  37512. }
  37513. this.eatBits(12);
  37514. if (this.encoding > 0) {
  37515. this.lookBits(1);
  37516. this.eatBits(1);
  37517. }
  37518. }
  37519. }
  37520. this.eof = true;
  37521. }
  37522. } else if (this.err && this.eoline) {
  37523. while (true) {
  37524. code1 = this.lookBits(13);
  37525. if (code1 === EOF) {
  37526. this.eof = true;
  37527. return null;
  37528. }
  37529. if ((code1 >> 1) === 1) {
  37530. break;
  37531. }
  37532. this.eatBits(1);
  37533. }
  37534. this.eatBits(12);
  37535. if (this.encoding > 0) {
  37536. this.eatBits(1);
  37537. this.nextLine2D = !(code1 & 1);
  37538. }
  37539. }
  37540. if (codingLine[0] > 0) {
  37541. this.outputBits = codingLine[this.codingPos = 0];
  37542. } else {
  37543. this.outputBits = codingLine[this.codingPos = 1];
  37544. }
  37545. this.row++;
  37546. }
  37547. var c;
  37548. if (this.outputBits >= 8) {
  37549. c = (this.codingPos & 1) ? 0 : 0xFF;
  37550. this.outputBits -= 8;
  37551. if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {
  37552. this.codingPos++;
  37553. this.outputBits = (codingLine[this.codingPos] -
  37554. codingLine[this.codingPos - 1]);
  37555. }
  37556. } else {
  37557. bits = 8;
  37558. c = 0;
  37559. do {
  37560. if (this.outputBits > bits) {
  37561. c <<= bits;
  37562. if (!(this.codingPos & 1)) {
  37563. c |= 0xFF >> (8 - bits);
  37564. }
  37565. this.outputBits -= bits;
  37566. bits = 0;
  37567. } else {
  37568. c <<= this.outputBits;
  37569. if (!(this.codingPos & 1)) {
  37570. c |= 0xFF >> (8 - this.outputBits);
  37571. }
  37572. bits -= this.outputBits;
  37573. this.outputBits = 0;
  37574. if (codingLine[this.codingPos] < columns) {
  37575. this.codingPos++;
  37576. this.outputBits = (codingLine[this.codingPos] -
  37577. codingLine[this.codingPos - 1]);
  37578. } else if (bits > 0) {
  37579. c <<= bits;
  37580. bits = 0;
  37581. }
  37582. }
  37583. } while (bits);
  37584. }
  37585. if (this.black) {
  37586. c ^= 0xFF;
  37587. }
  37588. return c;
  37589. };
  37590. // This functions returns the code found from the table.
  37591. // The start and end parameters set the boundaries for searching the table.
  37592. // The limit parameter is optional. Function returns an array with three
  37593. // values. The first array element indicates whether a valid code is being
  37594. // returned. The second array element is the actual code. The third array
  37595. // element indicates whether EOF was reached.
  37596. CCITTFaxStream.prototype.findTableCode =
  37597. function ccittFaxStreamFindTableCode(start, end, table, limit) {
  37598. var limitValue = limit || 0;
  37599. for (var i = start; i <= end; ++i) {
  37600. var code = this.lookBits(i);
  37601. if (code === EOF) {
  37602. return [true, 1, false];
  37603. }
  37604. if (i < end) {
  37605. code <<= end - i;
  37606. }
  37607. if (!limitValue || code >= limitValue) {
  37608. var p = table[code - limitValue];
  37609. if (p[0] === i) {
  37610. this.eatBits(i);
  37611. return [true, p[1], true];
  37612. }
  37613. }
  37614. }
  37615. return [false, 0, false];
  37616. };
  37617. CCITTFaxStream.prototype.getTwoDimCode =
  37618. function ccittFaxStreamGetTwoDimCode() {
  37619. var code = 0;
  37620. var p;
  37621. if (this.eoblock) {
  37622. code = this.lookBits(7);
  37623. p = twoDimTable[code];
  37624. if (p && p[0] > 0) {
  37625. this.eatBits(p[0]);
  37626. return p[1];
  37627. }
  37628. } else {
  37629. var result = this.findTableCode(1, 7, twoDimTable);
  37630. if (result[0] && result[2]) {
  37631. return result[1];
  37632. }
  37633. }
  37634. info('Bad two dim code');
  37635. return EOF;
  37636. };
  37637. CCITTFaxStream.prototype.getWhiteCode =
  37638. function ccittFaxStreamGetWhiteCode() {
  37639. var code = 0;
  37640. var p;
  37641. if (this.eoblock) {
  37642. code = this.lookBits(12);
  37643. if (code === EOF) {
  37644. return 1;
  37645. }
  37646. if ((code >> 5) === 0) {
  37647. p = whiteTable1[code];
  37648. } else {
  37649. p = whiteTable2[code >> 3];
  37650. }
  37651. if (p[0] > 0) {
  37652. this.eatBits(p[0]);
  37653. return p[1];
  37654. }
  37655. } else {
  37656. var result = this.findTableCode(1, 9, whiteTable2);
  37657. if (result[0]) {
  37658. return result[1];
  37659. }
  37660. result = this.findTableCode(11, 12, whiteTable1);
  37661. if (result[0]) {
  37662. return result[1];
  37663. }
  37664. }
  37665. info('bad white code');
  37666. this.eatBits(1);
  37667. return 1;
  37668. };
  37669. CCITTFaxStream.prototype.getBlackCode =
  37670. function ccittFaxStreamGetBlackCode() {
  37671. var code, p;
  37672. if (this.eoblock) {
  37673. code = this.lookBits(13);
  37674. if (code === EOF) {
  37675. return 1;
  37676. }
  37677. if ((code >> 7) === 0) {
  37678. p = blackTable1[code];
  37679. } else if ((code >> 9) === 0 && (code >> 7) !== 0) {
  37680. p = blackTable2[(code >> 1) - 64];
  37681. } else {
  37682. p = blackTable3[code >> 7];
  37683. }
  37684. if (p[0] > 0) {
  37685. this.eatBits(p[0]);
  37686. return p[1];
  37687. }
  37688. } else {
  37689. var result = this.findTableCode(2, 6, blackTable3);
  37690. if (result[0]) {
  37691. return result[1];
  37692. }
  37693. result = this.findTableCode(7, 12, blackTable2, 64);
  37694. if (result[0]) {
  37695. return result[1];
  37696. }
  37697. result = this.findTableCode(10, 13, blackTable1);
  37698. if (result[0]) {
  37699. return result[1];
  37700. }
  37701. }
  37702. info('bad black code');
  37703. this.eatBits(1);
  37704. return 1;
  37705. };
  37706. CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) {
  37707. var c;
  37708. while (this.inputBits < n) {
  37709. if ((c = this.str.getByte()) === -1) {
  37710. if (this.inputBits === 0) {
  37711. return EOF;
  37712. }
  37713. return ((this.inputBuf << (n - this.inputBits)) &
  37714. (0xFFFF >> (16 - n)));
  37715. }
  37716. this.inputBuf = (this.inputBuf << 8) + c;
  37717. this.inputBits += 8;
  37718. }
  37719. return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n));
  37720. };
  37721. CCITTFaxStream.prototype.eatBits = function CCITTFaxStream_eatBits(n) {
  37722. if ((this.inputBits -= n) < 0) {
  37723. this.inputBits = 0;
  37724. }
  37725. };
  37726. return CCITTFaxStream;
  37727. })();
  37728. var LZWStream = (function LZWStreamClosure() {
  37729. function LZWStream(str, maybeLength, earlyChange) {
  37730. this.str = str;
  37731. this.dict = str.dict;
  37732. this.cachedData = 0;
  37733. this.bitsCached = 0;
  37734. var maxLzwDictionarySize = 4096;
  37735. var lzwState = {
  37736. earlyChange: earlyChange,
  37737. codeLength: 9,
  37738. nextCode: 258,
  37739. dictionaryValues: new Uint8Array(maxLzwDictionarySize),
  37740. dictionaryLengths: new Uint16Array(maxLzwDictionarySize),
  37741. dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize),
  37742. currentSequence: new Uint8Array(maxLzwDictionarySize),
  37743. currentSequenceLength: 0
  37744. };
  37745. for (var i = 0; i < 256; ++i) {
  37746. lzwState.dictionaryValues[i] = i;
  37747. lzwState.dictionaryLengths[i] = 1;
  37748. }
  37749. this.lzwState = lzwState;
  37750. DecodeStream.call(this, maybeLength);
  37751. }
  37752. LZWStream.prototype = Object.create(DecodeStream.prototype);
  37753. LZWStream.prototype.readBits = function LZWStream_readBits(n) {
  37754. var bitsCached = this.bitsCached;
  37755. var cachedData = this.cachedData;
  37756. while (bitsCached < n) {
  37757. var c = this.str.getByte();
  37758. if (c === -1) {
  37759. this.eof = true;
  37760. return null;
  37761. }
  37762. cachedData = (cachedData << 8) | c;
  37763. bitsCached += 8;
  37764. }
  37765. this.bitsCached = (bitsCached -= n);
  37766. this.cachedData = cachedData;
  37767. this.lastCode = null;
  37768. return (cachedData >>> bitsCached) & ((1 << n) - 1);
  37769. };
  37770. LZWStream.prototype.readBlock = function LZWStream_readBlock() {
  37771. var blockSize = 512;
  37772. var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize;
  37773. var i, j, q;
  37774. var lzwState = this.lzwState;
  37775. if (!lzwState) {
  37776. return; // eof was found
  37777. }
  37778. var earlyChange = lzwState.earlyChange;
  37779. var nextCode = lzwState.nextCode;
  37780. var dictionaryValues = lzwState.dictionaryValues;
  37781. var dictionaryLengths = lzwState.dictionaryLengths;
  37782. var dictionaryPrevCodes = lzwState.dictionaryPrevCodes;
  37783. var codeLength = lzwState.codeLength;
  37784. var prevCode = lzwState.prevCode;
  37785. var currentSequence = lzwState.currentSequence;
  37786. var currentSequenceLength = lzwState.currentSequenceLength;
  37787. var decodedLength = 0;
  37788. var currentBufferLength = this.bufferLength;
  37789. var buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
  37790. for (i = 0; i < blockSize; i++) {
  37791. var code = this.readBits(codeLength);
  37792. var hasPrev = currentSequenceLength > 0;
  37793. if (code < 256) {
  37794. currentSequence[0] = code;
  37795. currentSequenceLength = 1;
  37796. } else if (code >= 258) {
  37797. if (code < nextCode) {
  37798. currentSequenceLength = dictionaryLengths[code];
  37799. for (j = currentSequenceLength - 1, q = code; j >= 0; j--) {
  37800. currentSequence[j] = dictionaryValues[q];
  37801. q = dictionaryPrevCodes[q];
  37802. }
  37803. } else {
  37804. currentSequence[currentSequenceLength++] = currentSequence[0];
  37805. }
  37806. } else if (code === 256) {
  37807. codeLength = 9;
  37808. nextCode = 258;
  37809. currentSequenceLength = 0;
  37810. continue;
  37811. } else {
  37812. this.eof = true;
  37813. delete this.lzwState;
  37814. break;
  37815. }
  37816. if (hasPrev) {
  37817. dictionaryPrevCodes[nextCode] = prevCode;
  37818. dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1;
  37819. dictionaryValues[nextCode] = currentSequence[0];
  37820. nextCode++;
  37821. codeLength = (nextCode + earlyChange) & (nextCode + earlyChange - 1) ?
  37822. codeLength : Math.min(Math.log(nextCode + earlyChange) /
  37823. 0.6931471805599453 + 1, 12) | 0;
  37824. }
  37825. prevCode = code;
  37826. decodedLength += currentSequenceLength;
  37827. if (estimatedDecodedSize < decodedLength) {
  37828. do {
  37829. estimatedDecodedSize += decodedSizeDelta;
  37830. } while (estimatedDecodedSize < decodedLength);
  37831. buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
  37832. }
  37833. for (j = 0; j < currentSequenceLength; j++) {
  37834. buffer[currentBufferLength++] = currentSequence[j];
  37835. }
  37836. }
  37837. lzwState.nextCode = nextCode;
  37838. lzwState.codeLength = codeLength;
  37839. lzwState.prevCode = prevCode;
  37840. lzwState.currentSequenceLength = currentSequenceLength;
  37841. this.bufferLength = currentBufferLength;
  37842. };
  37843. return LZWStream;
  37844. })();
  37845. var NullStream = (function NullStreamClosure() {
  37846. function NullStream() {
  37847. Stream.call(this, new Uint8Array(0));
  37848. }
  37849. NullStream.prototype = Stream.prototype;
  37850. return NullStream;
  37851. })();
  37852. var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
  37853. setup: function wphSetup(handler) {
  37854. var pdfManager;
  37855. function loadDocument(recoveryMode) {
  37856. var loadDocumentCapability = createPromiseCapability();
  37857. var parseSuccess = function parseSuccess() {
  37858. var numPagesPromise = pdfManager.ensureDoc('numPages');
  37859. var fingerprintPromise = pdfManager.ensureDoc('fingerprint');
  37860. var encryptedPromise = pdfManager.ensureXRef('encrypt');
  37861. Promise.all([numPagesPromise, fingerprintPromise,
  37862. encryptedPromise]).then(function onDocReady(results) {
  37863. var doc = {
  37864. numPages: results[0],
  37865. fingerprint: results[1],
  37866. encrypted: !!results[2],
  37867. };
  37868. loadDocumentCapability.resolve(doc);
  37869. },
  37870. parseFailure);
  37871. };
  37872. var parseFailure = function parseFailure(e) {
  37873. loadDocumentCapability.reject(e);
  37874. };
  37875. pdfManager.ensureDoc('checkHeader', []).then(function() {
  37876. pdfManager.ensureDoc('parseStartXRef', []).then(function() {
  37877. pdfManager.ensureDoc('parse', [recoveryMode]).then(
  37878. parseSuccess, parseFailure);
  37879. }, parseFailure);
  37880. }, parseFailure);
  37881. return loadDocumentCapability.promise;
  37882. }
  37883. function getPdfManager(data) {
  37884. var pdfManagerCapability = createPromiseCapability();
  37885. var source = data.source;
  37886. var disableRange = data.disableRange;
  37887. if (source.data) {
  37888. try {
  37889. pdfManager = new LocalPdfManager(source.data, source.password);
  37890. pdfManagerCapability.resolve();
  37891. } catch (ex) {
  37892. pdfManagerCapability.reject(ex);
  37893. }
  37894. return pdfManagerCapability.promise;
  37895. } else if (source.chunkedViewerLoading) {
  37896. try {
  37897. pdfManager = new NetworkPdfManager(source, handler);
  37898. pdfManagerCapability.resolve();
  37899. } catch (ex) {
  37900. pdfManagerCapability.reject(ex);
  37901. }
  37902. return pdfManagerCapability.promise;
  37903. }
  37904. var networkManager = new NetworkManager(source.url, {
  37905. httpHeaders: source.httpHeaders,
  37906. withCredentials: source.withCredentials
  37907. });
  37908. var cachedChunks = [];
  37909. var fullRequestXhrId = networkManager.requestFull({
  37910. onHeadersReceived: function onHeadersReceived() {
  37911. if (disableRange) {
  37912. return;
  37913. }
  37914. var fullRequestXhr = networkManager.getRequestXhr(fullRequestXhrId);
  37915. if (fullRequestXhr.getResponseHeader('Accept-Ranges') !== 'bytes') {
  37916. return;
  37917. }
  37918. var contentEncoding =
  37919. fullRequestXhr.getResponseHeader('Content-Encoding') || 'identity';
  37920. if (contentEncoding !== 'identity') {
  37921. return;
  37922. }
  37923. var length = fullRequestXhr.getResponseHeader('Content-Length');
  37924. length = parseInt(length, 10);
  37925. if (!isInt(length)) {
  37926. return;
  37927. }
  37928. source.length = length;
  37929. if (length <= 2 * RANGE_CHUNK_SIZE) {
  37930. // The file size is smaller than the size of two chunks, so it does
  37931. // not make any sense to abort the request and retry with a range
  37932. // request.
  37933. return;
  37934. }
  37935. if (networkManager.isStreamingRequest(fullRequestXhrId)) {
  37936. // We can continue fetching when progressive loading is enabled,
  37937. // and we don't need the autoFetch feature.
  37938. source.disableAutoFetch = true;
  37939. } else {
  37940. // NOTE: by cancelling the full request, and then issuing range
  37941. // requests, there will be an issue for sites where you can only
  37942. // request the pdf once. However, if this is the case, then the
  37943. // server should not be returning that it can support range
  37944. // requests.
  37945. networkManager.abortRequest(fullRequestXhrId);
  37946. }
  37947. try {
  37948. pdfManager = new NetworkPdfManager(source, handler);
  37949. pdfManagerCapability.resolve(pdfManager);
  37950. } catch (ex) {
  37951. pdfManagerCapability.reject(ex);
  37952. }
  37953. },
  37954. onProgressiveData: source.disableStream ? null :
  37955. function onProgressiveData(chunk) {
  37956. if (!pdfManager) {
  37957. cachedChunks.push(chunk);
  37958. return;
  37959. }
  37960. pdfManager.sendProgressiveData(chunk);
  37961. },
  37962. onDone: function onDone(args) {
  37963. if (pdfManager) {
  37964. return; // already processed
  37965. }
  37966. var pdfFile;
  37967. if (args === null) {
  37968. // TODO add some streaming manager, e.g. for unknown length files.
  37969. // The data was returned in the onProgressiveData, combining...
  37970. var pdfFileLength = 0, pos = 0;
  37971. cachedChunks.forEach(function (chunk) {
  37972. pdfFileLength += chunk.byteLength;
  37973. });
  37974. if (source.length && pdfFileLength !== source.length) {
  37975. warn('reported HTTP length is different from actual');
  37976. }
  37977. var pdfFileArray = new Uint8Array(pdfFileLength);
  37978. cachedChunks.forEach(function (chunk) {
  37979. pdfFileArray.set(new Uint8Array(chunk), pos);
  37980. pos += chunk.byteLength;
  37981. });
  37982. pdfFile = pdfFileArray.buffer;
  37983. } else {
  37984. pdfFile = args.chunk;
  37985. }
  37986. // the data is array, instantiating directly from it
  37987. try {
  37988. pdfManager = new LocalPdfManager(pdfFile, source.password);
  37989. pdfManagerCapability.resolve();
  37990. } catch (ex) {
  37991. pdfManagerCapability.reject(ex);
  37992. }
  37993. },
  37994. onError: function onError(status) {
  37995. var exception;
  37996. if (status === 404) {
  37997. exception = new MissingPDFException('Missing PDF "' +
  37998. source.url + '".');
  37999. handler.send('MissingPDF', exception);
  38000. } else {
  38001. exception = new UnexpectedResponseException(
  38002. 'Unexpected server response (' + status +
  38003. ') while retrieving PDF "' + source.url + '".', status);
  38004. handler.send('UnexpectedResponse', exception);
  38005. }
  38006. },
  38007. onProgress: function onProgress(evt) {
  38008. handler.send('DocProgress', {
  38009. loaded: evt.loaded,
  38010. total: evt.lengthComputable ? evt.total : source.length
  38011. });
  38012. }
  38013. });
  38014. return pdfManagerCapability.promise;
  38015. }
  38016. handler.on('test', function wphSetupTest(data) {
  38017. // check if Uint8Array can be sent to worker
  38018. if (!(data instanceof Uint8Array)) {
  38019. handler.send('test', false);
  38020. return;
  38021. }
  38022. // making sure postMessage transfers are working
  38023. var supportTransfers = data[0] === 255;
  38024. handler.postMessageTransfers = supportTransfers;
  38025. // check if the response property is supported by xhr
  38026. var xhr = new XMLHttpRequest();
  38027. var responseExists = 'response' in xhr;
  38028. // check if the property is actually implemented
  38029. try {
  38030. var dummy = xhr.responseType;
  38031. } catch (e) {
  38032. responseExists = false;
  38033. }
  38034. if (!responseExists) {
  38035. handler.send('test', false);
  38036. return;
  38037. }
  38038. handler.send('test', {
  38039. supportTypedArray: true,
  38040. supportTransfers: supportTransfers
  38041. });
  38042. });
  38043. handler.on('GetDocRequest', function wphSetupDoc(data) {
  38044. var onSuccess = function(doc) {
  38045. handler.send('GetDoc', { pdfInfo: doc });
  38046. };
  38047. var onFailure = function(e) {
  38048. if (e instanceof PasswordException) {
  38049. if (e.code === PasswordResponses.NEED_PASSWORD) {
  38050. handler.send('NeedPassword', e);
  38051. } else if (e.code === PasswordResponses.INCORRECT_PASSWORD) {
  38052. handler.send('IncorrectPassword', e);
  38053. }
  38054. } else if (e instanceof InvalidPDFException) {
  38055. handler.send('InvalidPDF', e);
  38056. } else if (e instanceof MissingPDFException) {
  38057. handler.send('MissingPDF', e);
  38058. } else if (e instanceof UnexpectedResponseException) {
  38059. handler.send('UnexpectedResponse', e);
  38060. } else {
  38061. handler.send('UnknownError',
  38062. new UnknownErrorException(e.message, e.toString()));
  38063. }
  38064. };
  38065. PDFJS.maxImageSize = data.maxImageSize === undefined ?
  38066. -1 : data.maxImageSize;
  38067. PDFJS.disableFontFace = data.disableFontFace;
  38068. PDFJS.disableCreateObjectURL = data.disableCreateObjectURL;
  38069. PDFJS.verbosity = data.verbosity;
  38070. PDFJS.cMapUrl = data.cMapUrl === undefined ?
  38071. null : data.cMapUrl;
  38072. PDFJS.cMapPacked = data.cMapPacked === true;
  38073. getPdfManager(data).then(function () {
  38074. handler.send('PDFManagerReady', null);
  38075. pdfManager.onLoadedStream().then(function(stream) {
  38076. handler.send('DataLoaded', { length: stream.bytes.byteLength });
  38077. });
  38078. }).then(function pdfManagerReady() {
  38079. loadDocument(false).then(onSuccess, function loadFailure(ex) {
  38080. // Try again with recoveryMode == true
  38081. if (!(ex instanceof XRefParseException)) {
  38082. if (ex instanceof PasswordException) {
  38083. // after password exception prepare to receive a new password
  38084. // to repeat loading
  38085. pdfManager.passwordChanged().then(pdfManagerReady);
  38086. }
  38087. onFailure(ex);
  38088. return;
  38089. }
  38090. pdfManager.requestLoadedStream();
  38091. pdfManager.onLoadedStream().then(function() {
  38092. loadDocument(true).then(onSuccess, onFailure);
  38093. });
  38094. }, onFailure);
  38095. }, onFailure);
  38096. });
  38097. handler.on('GetPage', function wphSetupGetPage(data) {
  38098. return pdfManager.getPage(data.pageIndex).then(function(page) {
  38099. var rotatePromise = pdfManager.ensure(page, 'rotate');
  38100. var refPromise = pdfManager.ensure(page, 'ref');
  38101. var viewPromise = pdfManager.ensure(page, 'view');
  38102. return Promise.all([rotatePromise, refPromise, viewPromise]).then(
  38103. function(results) {
  38104. return {
  38105. rotate: results[0],
  38106. ref: results[1],
  38107. view: results[2]
  38108. };
  38109. });
  38110. });
  38111. });
  38112. handler.on('GetPageIndex', function wphSetupGetPageIndex(data) {
  38113. var ref = new Ref(data.ref.num, data.ref.gen);
  38114. var catalog = pdfManager.pdfDocument.catalog;
  38115. return catalog.getPageIndex(ref);
  38116. });
  38117. handler.on('GetDestinations',
  38118. function wphSetupGetDestinations(data) {
  38119. return pdfManager.ensureCatalog('destinations');
  38120. }
  38121. );
  38122. handler.on('GetDestination',
  38123. function wphSetupGetDestination(data) {
  38124. return pdfManager.ensureCatalog('getDestination', [ data.id ]);
  38125. }
  38126. );
  38127. handler.on('GetAttachments',
  38128. function wphSetupGetAttachments(data) {
  38129. return pdfManager.ensureCatalog('attachments');
  38130. }
  38131. );
  38132. handler.on('GetJavaScript',
  38133. function wphSetupGetJavaScript(data) {
  38134. return pdfManager.ensureCatalog('javaScript');
  38135. }
  38136. );
  38137. handler.on('GetOutline',
  38138. function wphSetupGetOutline(data) {
  38139. return pdfManager.ensureCatalog('documentOutline');
  38140. }
  38141. );
  38142. handler.on('GetMetadata',
  38143. function wphSetupGetMetadata(data) {
  38144. return Promise.all([pdfManager.ensureDoc('documentInfo'),
  38145. pdfManager.ensureCatalog('metadata')]);
  38146. }
  38147. );
  38148. handler.on('GetData', function wphSetupGetData(data) {
  38149. pdfManager.requestLoadedStream();
  38150. return pdfManager.onLoadedStream().then(function(stream) {
  38151. return stream.bytes;
  38152. });
  38153. });
  38154. handler.on('GetStats',
  38155. function wphSetupGetStats(data) {
  38156. return pdfManager.pdfDocument.xref.stats;
  38157. }
  38158. );
  38159. handler.on('UpdatePassword', function wphSetupUpdatePassword(data) {
  38160. pdfManager.updatePassword(data);
  38161. });
  38162. handler.on('GetAnnotations', function wphSetupGetAnnotations(data) {
  38163. return pdfManager.getPage(data.pageIndex).then(function(page) {
  38164. return pdfManager.ensure(page, 'getAnnotationsData', []);
  38165. });
  38166. });
  38167. handler.on('RenderPageRequest', function wphSetupRenderPage(data) {
  38168. pdfManager.getPage(data.pageIndex).then(function(page) {
  38169. var pageNum = data.pageIndex + 1;
  38170. var start = Date.now();
  38171. // Pre compile the pdf page and fetch the fonts/images.
  38172. page.getOperatorList(handler, data.intent).then(function(operatorList) {
  38173. info('page=' + pageNum + ' - getOperatorList: time=' +
  38174. (Date.now() - start) + 'ms, len=' + operatorList.fnArray.length);
  38175. }, function(e) {
  38176. var minimumStackMessage =
  38177. 'worker.js: while trying to getPage() and getOperatorList()';
  38178. var wrappedException;
  38179. // Turn the error into an obj that can be serialized
  38180. if (typeof e === 'string') {
  38181. wrappedException = {
  38182. message: e,
  38183. stack: minimumStackMessage
  38184. };
  38185. } else if (typeof e === 'object') {
  38186. wrappedException = {
  38187. message: e.message || e.toString(),
  38188. stack: e.stack || minimumStackMessage
  38189. };
  38190. } else {
  38191. wrappedException = {
  38192. message: 'Unknown exception type: ' + (typeof e),
  38193. stack: minimumStackMessage
  38194. };
  38195. }
  38196. handler.send('PageError', {
  38197. pageNum: pageNum,
  38198. error: wrappedException,
  38199. intent: data.intent
  38200. });
  38201. });
  38202. });
  38203. }, this);
  38204. handler.on('GetTextContent', function wphExtractText(data) {
  38205. return pdfManager.getPage(data.pageIndex).then(function(page) {
  38206. var pageNum = data.pageIndex + 1;
  38207. var start = Date.now();
  38208. return page.extractTextContent().then(function(textContent) {
  38209. info('text indexing: page=' + pageNum + ' - time=' +
  38210. (Date.now() - start) + 'ms');
  38211. return textContent;
  38212. });
  38213. });
  38214. });
  38215. handler.on('Cleanup', function wphCleanup(data) {
  38216. return pdfManager.cleanup();
  38217. });
  38218. handler.on('Terminate', function wphTerminate(data) {
  38219. pdfManager.terminate();
  38220. });
  38221. }
  38222. };
  38223. var consoleTimer = {};
  38224. var workerConsole = {
  38225. log: function log() {
  38226. var args = Array.prototype.slice.call(arguments);
  38227. globalScope.postMessage({
  38228. action: 'console_log',
  38229. data: args
  38230. });
  38231. },
  38232. error: function error() {
  38233. var args = Array.prototype.slice.call(arguments);
  38234. globalScope.postMessage({
  38235. action: 'console_error',
  38236. data: args
  38237. });
  38238. throw 'pdf.js execution error';
  38239. },
  38240. time: function time(name) {
  38241. consoleTimer[name] = Date.now();
  38242. },
  38243. timeEnd: function timeEnd(name) {
  38244. var time = consoleTimer[name];
  38245. if (!time) {
  38246. error('Unknown timer name ' + name);
  38247. }
  38248. this.log('Timer:', name, Date.now() - time);
  38249. }
  38250. };
  38251. // Worker thread?
  38252. if (typeof window === 'undefined') {
  38253. if (!('console' in globalScope)) {
  38254. globalScope.console = workerConsole;
  38255. }
  38256. // Listen for unsupported features so we can pass them on to the main thread.
  38257. PDFJS.UnsupportedManager.listen(function (msg) {
  38258. globalScope.postMessage({
  38259. action: '_unsupported_feature',
  38260. data: msg
  38261. });
  38262. });
  38263. var handler = new MessageHandler('worker_processor', this);
  38264. WorkerMessageHandler.setup(handler);
  38265. }
  38266. /* This class implements the QM Coder decoding as defined in
  38267. * JPEG 2000 Part I Final Committee Draft Version 1.0
  38268. * Annex C.3 Arithmetic decoding procedure
  38269. * available at http://www.jpeg.org/public/fcd15444-1.pdf
  38270. *
  38271. * The arithmetic decoder is used in conjunction with context models to decode
  38272. * JPEG2000 and JBIG2 streams.
  38273. */
  38274. var ArithmeticDecoder = (function ArithmeticDecoderClosure() {
  38275. // Table C-2
  38276. var QeTable = [
  38277. {qe: 0x5601, nmps: 1, nlps: 1, switchFlag: 1},
  38278. {qe: 0x3401, nmps: 2, nlps: 6, switchFlag: 0},
  38279. {qe: 0x1801, nmps: 3, nlps: 9, switchFlag: 0},
  38280. {qe: 0x0AC1, nmps: 4, nlps: 12, switchFlag: 0},
  38281. {qe: 0x0521, nmps: 5, nlps: 29, switchFlag: 0},
  38282. {qe: 0x0221, nmps: 38, nlps: 33, switchFlag: 0},
  38283. {qe: 0x5601, nmps: 7, nlps: 6, switchFlag: 1},
  38284. {qe: 0x5401, nmps: 8, nlps: 14, switchFlag: 0},
  38285. {qe: 0x4801, nmps: 9, nlps: 14, switchFlag: 0},
  38286. {qe: 0x3801, nmps: 10, nlps: 14, switchFlag: 0},
  38287. {qe: 0x3001, nmps: 11, nlps: 17, switchFlag: 0},
  38288. {qe: 0x2401, nmps: 12, nlps: 18, switchFlag: 0},
  38289. {qe: 0x1C01, nmps: 13, nlps: 20, switchFlag: 0},
  38290. {qe: 0x1601, nmps: 29, nlps: 21, switchFlag: 0},
  38291. {qe: 0x5601, nmps: 15, nlps: 14, switchFlag: 1},
  38292. {qe: 0x5401, nmps: 16, nlps: 14, switchFlag: 0},
  38293. {qe: 0x5101, nmps: 17, nlps: 15, switchFlag: 0},
  38294. {qe: 0x4801, nmps: 18, nlps: 16, switchFlag: 0},
  38295. {qe: 0x3801, nmps: 19, nlps: 17, switchFlag: 0},
  38296. {qe: 0x3401, nmps: 20, nlps: 18, switchFlag: 0},
  38297. {qe: 0x3001, nmps: 21, nlps: 19, switchFlag: 0},
  38298. {qe: 0x2801, nmps: 22, nlps: 19, switchFlag: 0},
  38299. {qe: 0x2401, nmps: 23, nlps: 20, switchFlag: 0},
  38300. {qe: 0x2201, nmps: 24, nlps: 21, switchFlag: 0},
  38301. {qe: 0x1C01, nmps: 25, nlps: 22, switchFlag: 0},
  38302. {qe: 0x1801, nmps: 26, nlps: 23, switchFlag: 0},
  38303. {qe: 0x1601, nmps: 27, nlps: 24, switchFlag: 0},
  38304. {qe: 0x1401, nmps: 28, nlps: 25, switchFlag: 0},
  38305. {qe: 0x1201, nmps: 29, nlps: 26, switchFlag: 0},
  38306. {qe: 0x1101, nmps: 30, nlps: 27, switchFlag: 0},
  38307. {qe: 0x0AC1, nmps: 31, nlps: 28, switchFlag: 0},
  38308. {qe: 0x09C1, nmps: 32, nlps: 29, switchFlag: 0},
  38309. {qe: 0x08A1, nmps: 33, nlps: 30, switchFlag: 0},
  38310. {qe: 0x0521, nmps: 34, nlps: 31, switchFlag: 0},
  38311. {qe: 0x0441, nmps: 35, nlps: 32, switchFlag: 0},
  38312. {qe: 0x02A1, nmps: 36, nlps: 33, switchFlag: 0},
  38313. {qe: 0x0221, nmps: 37, nlps: 34, switchFlag: 0},
  38314. {qe: 0x0141, nmps: 38, nlps: 35, switchFlag: 0},
  38315. {qe: 0x0111, nmps: 39, nlps: 36, switchFlag: 0},
  38316. {qe: 0x0085, nmps: 40, nlps: 37, switchFlag: 0},
  38317. {qe: 0x0049, nmps: 41, nlps: 38, switchFlag: 0},
  38318. {qe: 0x0025, nmps: 42, nlps: 39, switchFlag: 0},
  38319. {qe: 0x0015, nmps: 43, nlps: 40, switchFlag: 0},
  38320. {qe: 0x0009, nmps: 44, nlps: 41, switchFlag: 0},
  38321. {qe: 0x0005, nmps: 45, nlps: 42, switchFlag: 0},
  38322. {qe: 0x0001, nmps: 45, nlps: 43, switchFlag: 0},
  38323. {qe: 0x5601, nmps: 46, nlps: 46, switchFlag: 0}
  38324. ];
  38325. // C.3.5 Initialisation of the decoder (INITDEC)
  38326. function ArithmeticDecoder(data, start, end) {
  38327. this.data = data;
  38328. this.bp = start;
  38329. this.dataEnd = end;
  38330. this.chigh = data[start];
  38331. this.clow = 0;
  38332. this.byteIn();
  38333. this.chigh = ((this.chigh << 7) & 0xFFFF) | ((this.clow >> 9) & 0x7F);
  38334. this.clow = (this.clow << 7) & 0xFFFF;
  38335. this.ct -= 7;
  38336. this.a = 0x8000;
  38337. }
  38338. ArithmeticDecoder.prototype = {
  38339. // C.3.4 Compressed data input (BYTEIN)
  38340. byteIn: function ArithmeticDecoder_byteIn() {
  38341. var data = this.data;
  38342. var bp = this.bp;
  38343. if (data[bp] === 0xFF) {
  38344. var b1 = data[bp + 1];
  38345. if (b1 > 0x8F) {
  38346. this.clow += 0xFF00;
  38347. this.ct = 8;
  38348. } else {
  38349. bp++;
  38350. this.clow += (data[bp] << 9);
  38351. this.ct = 7;
  38352. this.bp = bp;
  38353. }
  38354. } else {
  38355. bp++;
  38356. this.clow += bp < this.dataEnd ? (data[bp] << 8) : 0xFF00;
  38357. this.ct = 8;
  38358. this.bp = bp;
  38359. }
  38360. if (this.clow > 0xFFFF) {
  38361. this.chigh += (this.clow >> 16);
  38362. this.clow &= 0xFFFF;
  38363. }
  38364. },
  38365. // C.3.2 Decoding a decision (DECODE)
  38366. readBit: function ArithmeticDecoder_readBit(contexts, pos) {
  38367. // contexts are packed into 1 byte:
  38368. // highest 7 bits carry cx.index, lowest bit carries cx.mps
  38369. var cx_index = contexts[pos] >> 1, cx_mps = contexts[pos] & 1;
  38370. var qeTableIcx = QeTable[cx_index];
  38371. var qeIcx = qeTableIcx.qe;
  38372. var d;
  38373. var a = this.a - qeIcx;
  38374. if (this.chigh < qeIcx) {
  38375. // exchangeLps
  38376. if (a < qeIcx) {
  38377. a = qeIcx;
  38378. d = cx_mps;
  38379. cx_index = qeTableIcx.nmps;
  38380. } else {
  38381. a = qeIcx;
  38382. d = 1 ^ cx_mps;
  38383. if (qeTableIcx.switchFlag === 1) {
  38384. cx_mps = d;
  38385. }
  38386. cx_index = qeTableIcx.nlps;
  38387. }
  38388. } else {
  38389. this.chigh -= qeIcx;
  38390. if ((a & 0x8000) !== 0) {
  38391. this.a = a;
  38392. return cx_mps;
  38393. }
  38394. // exchangeMps
  38395. if (a < qeIcx) {
  38396. d = 1 ^ cx_mps;
  38397. if (qeTableIcx.switchFlag === 1) {
  38398. cx_mps = d;
  38399. }
  38400. cx_index = qeTableIcx.nlps;
  38401. } else {
  38402. d = cx_mps;
  38403. cx_index = qeTableIcx.nmps;
  38404. }
  38405. }
  38406. // C.3.3 renormD;
  38407. do {
  38408. if (this.ct === 0) {
  38409. this.byteIn();
  38410. }
  38411. a <<= 1;
  38412. this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1);
  38413. this.clow = (this.clow << 1) & 0xFFFF;
  38414. this.ct--;
  38415. } while ((a & 0x8000) === 0);
  38416. this.a = a;
  38417. contexts[pos] = cx_index << 1 | cx_mps;
  38418. return d;
  38419. }
  38420. };
  38421. return ArithmeticDecoder;
  38422. })();
  38423. var JpegImage = (function jpegImage() {
  38424. var dctZigZag = new Uint8Array([
  38425. 0,
  38426. 1, 8,
  38427. 16, 9, 2,
  38428. 3, 10, 17, 24,
  38429. 32, 25, 18, 11, 4,
  38430. 5, 12, 19, 26, 33, 40,
  38431. 48, 41, 34, 27, 20, 13, 6,
  38432. 7, 14, 21, 28, 35, 42, 49, 56,
  38433. 57, 50, 43, 36, 29, 22, 15,
  38434. 23, 30, 37, 44, 51, 58,
  38435. 59, 52, 45, 38, 31,
  38436. 39, 46, 53, 60,
  38437. 61, 54, 47,
  38438. 55, 62,
  38439. 63
  38440. ]);
  38441. var dctCos1 = 4017; // cos(pi/16)
  38442. var dctSin1 = 799; // sin(pi/16)
  38443. var dctCos3 = 3406; // cos(3*pi/16)
  38444. var dctSin3 = 2276; // sin(3*pi/16)
  38445. var dctCos6 = 1567; // cos(6*pi/16)
  38446. var dctSin6 = 3784; // sin(6*pi/16)
  38447. var dctSqrt2 = 5793; // sqrt(2)
  38448. var dctSqrt1d2 = 2896; // sqrt(2) / 2
  38449. function constructor() {
  38450. }
  38451. function buildHuffmanTable(codeLengths, values) {
  38452. var k = 0, code = [], i, j, length = 16;
  38453. while (length > 0 && !codeLengths[length - 1]) {
  38454. length--;
  38455. }
  38456. code.push({children: [], index: 0});
  38457. var p = code[0], q;
  38458. for (i = 0; i < length; i++) {
  38459. for (j = 0; j < codeLengths[i]; j++) {
  38460. p = code.pop();
  38461. p.children[p.index] = values[k];
  38462. while (p.index > 0) {
  38463. p = code.pop();
  38464. }
  38465. p.index++;
  38466. code.push(p);
  38467. while (code.length <= i) {
  38468. code.push(q = {children: [], index: 0});
  38469. p.children[p.index] = q.children;
  38470. p = q;
  38471. }
  38472. k++;
  38473. }
  38474. if (i + 1 < length) {
  38475. // p here points to last code
  38476. code.push(q = {children: [], index: 0});
  38477. p.children[p.index] = q.children;
  38478. p = q;
  38479. }
  38480. }
  38481. return code[0].children;
  38482. }
  38483. function getBlockBufferOffset(component, row, col) {
  38484. return 64 * ((component.blocksPerLine + 1) * row + col);
  38485. }
  38486. function decodeScan(data, offset, frame, components, resetInterval,
  38487. spectralStart, spectralEnd, successivePrev, successive) {
  38488. var precision = frame.precision;
  38489. var samplesPerLine = frame.samplesPerLine;
  38490. var scanLines = frame.scanLines;
  38491. var mcusPerLine = frame.mcusPerLine;
  38492. var progressive = frame.progressive;
  38493. var maxH = frame.maxH, maxV = frame.maxV;
  38494. var startOffset = offset, bitsData = 0, bitsCount = 0;
  38495. function readBit() {
  38496. if (bitsCount > 0) {
  38497. bitsCount--;
  38498. return (bitsData >> bitsCount) & 1;
  38499. }
  38500. bitsData = data[offset++];
  38501. if (bitsData === 0xFF) {
  38502. var nextByte = data[offset++];
  38503. if (nextByte) {
  38504. throw 'unexpected marker: ' +
  38505. ((bitsData << 8) | nextByte).toString(16);
  38506. }
  38507. // unstuff 0
  38508. }
  38509. bitsCount = 7;
  38510. return bitsData >>> 7;
  38511. }
  38512. function decodeHuffman(tree) {
  38513. var node = tree;
  38514. while (true) {
  38515. node = node[readBit()];
  38516. if (typeof node === 'number') {
  38517. return node;
  38518. }
  38519. if (typeof node !== 'object') {
  38520. throw 'invalid huffman sequence';
  38521. }
  38522. }
  38523. }
  38524. function receive(length) {
  38525. var n = 0;
  38526. while (length > 0) {
  38527. n = (n << 1) | readBit();
  38528. length--;
  38529. }
  38530. return n;
  38531. }
  38532. function receiveAndExtend(length) {
  38533. if (length === 1) {
  38534. return readBit() === 1 ? 1 : -1;
  38535. }
  38536. var n = receive(length);
  38537. if (n >= 1 << (length - 1)) {
  38538. return n;
  38539. }
  38540. return n + (-1 << length) + 1;
  38541. }
  38542. function decodeBaseline(component, offset) {
  38543. var t = decodeHuffman(component.huffmanTableDC);
  38544. var diff = t === 0 ? 0 : receiveAndExtend(t);
  38545. component.blockData[offset] = (component.pred += diff);
  38546. var k = 1;
  38547. while (k < 64) {
  38548. var rs = decodeHuffman(component.huffmanTableAC);
  38549. var s = rs & 15, r = rs >> 4;
  38550. if (s === 0) {
  38551. if (r < 15) {
  38552. break;
  38553. }
  38554. k += 16;
  38555. continue;
  38556. }
  38557. k += r;
  38558. var z = dctZigZag[k];
  38559. component.blockData[offset + z] = receiveAndExtend(s);
  38560. k++;
  38561. }
  38562. }
  38563. function decodeDCFirst(component, offset) {
  38564. var t = decodeHuffman(component.huffmanTableDC);
  38565. var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
  38566. component.blockData[offset] = (component.pred += diff);
  38567. }
  38568. function decodeDCSuccessive(component, offset) {
  38569. component.blockData[offset] |= readBit() << successive;
  38570. }
  38571. var eobrun = 0;
  38572. function decodeACFirst(component, offset) {
  38573. if (eobrun > 0) {
  38574. eobrun--;
  38575. return;
  38576. }
  38577. var k = spectralStart, e = spectralEnd;
  38578. while (k <= e) {
  38579. var rs = decodeHuffman(component.huffmanTableAC);
  38580. var s = rs & 15, r = rs >> 4;
  38581. if (s === 0) {
  38582. if (r < 15) {
  38583. eobrun = receive(r) + (1 << r) - 1;
  38584. break;
  38585. }
  38586. k += 16;
  38587. continue;
  38588. }
  38589. k += r;
  38590. var z = dctZigZag[k];
  38591. component.blockData[offset + z] =
  38592. receiveAndExtend(s) * (1 << successive);
  38593. k++;
  38594. }
  38595. }
  38596. var successiveACState = 0, successiveACNextValue;
  38597. function decodeACSuccessive(component, offset) {
  38598. var k = spectralStart;
  38599. var e = spectralEnd;
  38600. var r = 0;
  38601. var s;
  38602. var rs;
  38603. while (k <= e) {
  38604. var z = dctZigZag[k];
  38605. switch (successiveACState) {
  38606. case 0: // initial state
  38607. rs = decodeHuffman(component.huffmanTableAC);
  38608. s = rs & 15;
  38609. r = rs >> 4;
  38610. if (s === 0) {
  38611. if (r < 15) {
  38612. eobrun = receive(r) + (1 << r);
  38613. successiveACState = 4;
  38614. } else {
  38615. r = 16;
  38616. successiveACState = 1;
  38617. }
  38618. } else {
  38619. if (s !== 1) {
  38620. throw 'invalid ACn encoding';
  38621. }
  38622. successiveACNextValue = receiveAndExtend(s);
  38623. successiveACState = r ? 2 : 3;
  38624. }
  38625. continue;
  38626. case 1: // skipping r zero items
  38627. case 2:
  38628. if (component.blockData[offset + z]) {
  38629. component.blockData[offset + z] += (readBit() << successive);
  38630. } else {
  38631. r--;
  38632. if (r === 0) {
  38633. successiveACState = successiveACState === 2 ? 3 : 0;
  38634. }
  38635. }
  38636. break;
  38637. case 3: // set value for a zero item
  38638. if (component.blockData[offset + z]) {
  38639. component.blockData[offset + z] += (readBit() << successive);
  38640. } else {
  38641. component.blockData[offset + z] =
  38642. successiveACNextValue << successive;
  38643. successiveACState = 0;
  38644. }
  38645. break;
  38646. case 4: // eob
  38647. if (component.blockData[offset + z]) {
  38648. component.blockData[offset + z] += (readBit() << successive);
  38649. }
  38650. break;
  38651. }
  38652. k++;
  38653. }
  38654. if (successiveACState === 4) {
  38655. eobrun--;
  38656. if (eobrun === 0) {
  38657. successiveACState = 0;
  38658. }
  38659. }
  38660. }
  38661. function decodeMcu(component, decode, mcu, row, col) {
  38662. var mcuRow = (mcu / mcusPerLine) | 0;
  38663. var mcuCol = mcu % mcusPerLine;
  38664. var blockRow = mcuRow * component.v + row;
  38665. var blockCol = mcuCol * component.h + col;
  38666. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  38667. decode(component, offset);
  38668. }
  38669. function decodeBlock(component, decode, mcu) {
  38670. var blockRow = (mcu / component.blocksPerLine) | 0;
  38671. var blockCol = mcu % component.blocksPerLine;
  38672. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  38673. decode(component, offset);
  38674. }
  38675. var componentsLength = components.length;
  38676. var component, i, j, k, n;
  38677. var decodeFn;
  38678. if (progressive) {
  38679. if (spectralStart === 0) {
  38680. decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
  38681. } else {
  38682. decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
  38683. }
  38684. } else {
  38685. decodeFn = decodeBaseline;
  38686. }
  38687. var mcu = 0, marker;
  38688. var mcuExpected;
  38689. if (componentsLength === 1) {
  38690. mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
  38691. } else {
  38692. mcuExpected = mcusPerLine * frame.mcusPerColumn;
  38693. }
  38694. if (!resetInterval) {
  38695. resetInterval = mcuExpected;
  38696. }
  38697. var h, v;
  38698. while (mcu < mcuExpected) {
  38699. // reset interval stuff
  38700. for (i = 0; i < componentsLength; i++) {
  38701. components[i].pred = 0;
  38702. }
  38703. eobrun = 0;
  38704. if (componentsLength === 1) {
  38705. component = components[0];
  38706. for (n = 0; n < resetInterval; n++) {
  38707. decodeBlock(component, decodeFn, mcu);
  38708. mcu++;
  38709. }
  38710. } else {
  38711. for (n = 0; n < resetInterval; n++) {
  38712. for (i = 0; i < componentsLength; i++) {
  38713. component = components[i];
  38714. h = component.h;
  38715. v = component.v;
  38716. for (j = 0; j < v; j++) {
  38717. for (k = 0; k < h; k++) {
  38718. decodeMcu(component, decodeFn, mcu, j, k);
  38719. }
  38720. }
  38721. }
  38722. mcu++;
  38723. }
  38724. }
  38725. // find marker
  38726. bitsCount = 0;
  38727. marker = (data[offset] << 8) | data[offset + 1];
  38728. if (marker <= 0xFF00) {
  38729. throw 'marker was not found';
  38730. }
  38731. if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
  38732. offset += 2;
  38733. } else {
  38734. break;
  38735. }
  38736. }
  38737. return offset - startOffset;
  38738. }
  38739. // A port of poppler's IDCT method which in turn is taken from:
  38740. // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
  38741. // 'Practical Fast 1-D DCT Algorithms with 11 Multiplications',
  38742. // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
  38743. // 988-991.
  38744. function quantizeAndInverse(component, blockBufferOffset, p) {
  38745. var qt = component.quantizationTable, blockData = component.blockData;
  38746. var v0, v1, v2, v3, v4, v5, v6, v7;
  38747. var p0, p1, p2, p3, p4, p5, p6, p7;
  38748. var t;
  38749. // inverse DCT on rows
  38750. for (var row = 0; row < 64; row += 8) {
  38751. // gather block data
  38752. p0 = blockData[blockBufferOffset + row];
  38753. p1 = blockData[blockBufferOffset + row + 1];
  38754. p2 = blockData[blockBufferOffset + row + 2];
  38755. p3 = blockData[blockBufferOffset + row + 3];
  38756. p4 = blockData[blockBufferOffset + row + 4];
  38757. p5 = blockData[blockBufferOffset + row + 5];
  38758. p6 = blockData[blockBufferOffset + row + 6];
  38759. p7 = blockData[blockBufferOffset + row + 7];
  38760. // dequant p0
  38761. p0 *= qt[row];
  38762. // check for all-zero AC coefficients
  38763. if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
  38764. t = (dctSqrt2 * p0 + 512) >> 10;
  38765. p[row] = t;
  38766. p[row + 1] = t;
  38767. p[row + 2] = t;
  38768. p[row + 3] = t;
  38769. p[row + 4] = t;
  38770. p[row + 5] = t;
  38771. p[row + 6] = t;
  38772. p[row + 7] = t;
  38773. continue;
  38774. }
  38775. // dequant p1 ... p7
  38776. p1 *= qt[row + 1];
  38777. p2 *= qt[row + 2];
  38778. p3 *= qt[row + 3];
  38779. p4 *= qt[row + 4];
  38780. p5 *= qt[row + 5];
  38781. p6 *= qt[row + 6];
  38782. p7 *= qt[row + 7];
  38783. // stage 4
  38784. v0 = (dctSqrt2 * p0 + 128) >> 8;
  38785. v1 = (dctSqrt2 * p4 + 128) >> 8;
  38786. v2 = p2;
  38787. v3 = p6;
  38788. v4 = (dctSqrt1d2 * (p1 - p7) + 128) >> 8;
  38789. v7 = (dctSqrt1d2 * (p1 + p7) + 128) >> 8;
  38790. v5 = p3 << 4;
  38791. v6 = p5 << 4;
  38792. // stage 3
  38793. v0 = (v0 + v1 + 1) >> 1;
  38794. v1 = v0 - v1;
  38795. t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
  38796. v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
  38797. v3 = t;
  38798. v4 = (v4 + v6 + 1) >> 1;
  38799. v6 = v4 - v6;
  38800. v7 = (v7 + v5 + 1) >> 1;
  38801. v5 = v7 - v5;
  38802. // stage 2
  38803. v0 = (v0 + v3 + 1) >> 1;
  38804. v3 = v0 - v3;
  38805. v1 = (v1 + v2 + 1) >> 1;
  38806. v2 = v1 - v2;
  38807. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  38808. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  38809. v7 = t;
  38810. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  38811. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  38812. v6 = t;
  38813. // stage 1
  38814. p[row] = v0 + v7;
  38815. p[row + 7] = v0 - v7;
  38816. p[row + 1] = v1 + v6;
  38817. p[row + 6] = v1 - v6;
  38818. p[row + 2] = v2 + v5;
  38819. p[row + 5] = v2 - v5;
  38820. p[row + 3] = v3 + v4;
  38821. p[row + 4] = v3 - v4;
  38822. }
  38823. // inverse DCT on columns
  38824. for (var col = 0; col < 8; ++col) {
  38825. p0 = p[col];
  38826. p1 = p[col + 8];
  38827. p2 = p[col + 16];
  38828. p3 = p[col + 24];
  38829. p4 = p[col + 32];
  38830. p5 = p[col + 40];
  38831. p6 = p[col + 48];
  38832. p7 = p[col + 56];
  38833. // check for all-zero AC coefficients
  38834. if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
  38835. t = (dctSqrt2 * p0 + 8192) >> 14;
  38836. // convert to 8 bit
  38837. t = (t < -2040) ? 0 : (t >= 2024) ? 255 : (t + 2056) >> 4;
  38838. blockData[blockBufferOffset + col] = t;
  38839. blockData[blockBufferOffset + col + 8] = t;
  38840. blockData[blockBufferOffset + col + 16] = t;
  38841. blockData[blockBufferOffset + col + 24] = t;
  38842. blockData[blockBufferOffset + col + 32] = t;
  38843. blockData[blockBufferOffset + col + 40] = t;
  38844. blockData[blockBufferOffset + col + 48] = t;
  38845. blockData[blockBufferOffset + col + 56] = t;
  38846. continue;
  38847. }
  38848. // stage 4
  38849. v0 = (dctSqrt2 * p0 + 2048) >> 12;
  38850. v1 = (dctSqrt2 * p4 + 2048) >> 12;
  38851. v2 = p2;
  38852. v3 = p6;
  38853. v4 = (dctSqrt1d2 * (p1 - p7) + 2048) >> 12;
  38854. v7 = (dctSqrt1d2 * (p1 + p7) + 2048) >> 12;
  38855. v5 = p3;
  38856. v6 = p5;
  38857. // stage 3
  38858. // Shift v0 by 128.5 << 5 here, so we don't need to shift p0...p7 when
  38859. // converting to UInt8 range later.
  38860. v0 = ((v0 + v1 + 1) >> 1) + 4112;
  38861. v1 = v0 - v1;
  38862. t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
  38863. v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
  38864. v3 = t;
  38865. v4 = (v4 + v6 + 1) >> 1;
  38866. v6 = v4 - v6;
  38867. v7 = (v7 + v5 + 1) >> 1;
  38868. v5 = v7 - v5;
  38869. // stage 2
  38870. v0 = (v0 + v3 + 1) >> 1;
  38871. v3 = v0 - v3;
  38872. v1 = (v1 + v2 + 1) >> 1;
  38873. v2 = v1 - v2;
  38874. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  38875. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  38876. v7 = t;
  38877. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  38878. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  38879. v6 = t;
  38880. // stage 1
  38881. p0 = v0 + v7;
  38882. p7 = v0 - v7;
  38883. p1 = v1 + v6;
  38884. p6 = v1 - v6;
  38885. p2 = v2 + v5;
  38886. p5 = v2 - v5;
  38887. p3 = v3 + v4;
  38888. p4 = v3 - v4;
  38889. // convert to 8-bit integers
  38890. p0 = (p0 < 16) ? 0 : (p0 >= 4080) ? 255 : p0 >> 4;
  38891. p1 = (p1 < 16) ? 0 : (p1 >= 4080) ? 255 : p1 >> 4;
  38892. p2 = (p2 < 16) ? 0 : (p2 >= 4080) ? 255 : p2 >> 4;
  38893. p3 = (p3 < 16) ? 0 : (p3 >= 4080) ? 255 : p3 >> 4;
  38894. p4 = (p4 < 16) ? 0 : (p4 >= 4080) ? 255 : p4 >> 4;
  38895. p5 = (p5 < 16) ? 0 : (p5 >= 4080) ? 255 : p5 >> 4;
  38896. p6 = (p6 < 16) ? 0 : (p6 >= 4080) ? 255 : p6 >> 4;
  38897. p7 = (p7 < 16) ? 0 : (p7 >= 4080) ? 255 : p7 >> 4;
  38898. // store block data
  38899. blockData[blockBufferOffset + col] = p0;
  38900. blockData[blockBufferOffset + col + 8] = p1;
  38901. blockData[blockBufferOffset + col + 16] = p2;
  38902. blockData[blockBufferOffset + col + 24] = p3;
  38903. blockData[blockBufferOffset + col + 32] = p4;
  38904. blockData[blockBufferOffset + col + 40] = p5;
  38905. blockData[blockBufferOffset + col + 48] = p6;
  38906. blockData[blockBufferOffset + col + 56] = p7;
  38907. }
  38908. }
  38909. function buildComponentData(frame, component) {
  38910. var blocksPerLine = component.blocksPerLine;
  38911. var blocksPerColumn = component.blocksPerColumn;
  38912. var computationBuffer = new Int16Array(64);
  38913. for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
  38914. for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
  38915. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  38916. quantizeAndInverse(component, offset, computationBuffer);
  38917. }
  38918. }
  38919. return component.blockData;
  38920. }
  38921. function clamp0to255(a) {
  38922. return a <= 0 ? 0 : a >= 255 ? 255 : a;
  38923. }
  38924. constructor.prototype = {
  38925. parse: function parse(data) {
  38926. function readUint16() {
  38927. var value = (data[offset] << 8) | data[offset + 1];
  38928. offset += 2;
  38929. return value;
  38930. }
  38931. function readDataBlock() {
  38932. var length = readUint16();
  38933. var array = data.subarray(offset, offset + length - 2);
  38934. offset += array.length;
  38935. return array;
  38936. }
  38937. function prepareComponents(frame) {
  38938. var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH);
  38939. var mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV);
  38940. for (var i = 0; i < frame.components.length; i++) {
  38941. component = frame.components[i];
  38942. var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) *
  38943. component.h / frame.maxH);
  38944. var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) *
  38945. component.v / frame.maxV);
  38946. var blocksPerLineForMcu = mcusPerLine * component.h;
  38947. var blocksPerColumnForMcu = mcusPerColumn * component.v;
  38948. var blocksBufferSize = 64 * blocksPerColumnForMcu *
  38949. (blocksPerLineForMcu + 1);
  38950. component.blockData = new Int16Array(blocksBufferSize);
  38951. component.blocksPerLine = blocksPerLine;
  38952. component.blocksPerColumn = blocksPerColumn;
  38953. }
  38954. frame.mcusPerLine = mcusPerLine;
  38955. frame.mcusPerColumn = mcusPerColumn;
  38956. }
  38957. var offset = 0, length = data.length;
  38958. var jfif = null;
  38959. var adobe = null;
  38960. var pixels = null;
  38961. var frame, resetInterval;
  38962. var quantizationTables = [];
  38963. var huffmanTablesAC = [], huffmanTablesDC = [];
  38964. var fileMarker = readUint16();
  38965. if (fileMarker !== 0xFFD8) { // SOI (Start of Image)
  38966. throw 'SOI not found';
  38967. }
  38968. fileMarker = readUint16();
  38969. while (fileMarker !== 0xFFD9) { // EOI (End of image)
  38970. var i, j, l;
  38971. switch(fileMarker) {
  38972. case 0xFFE0: // APP0 (Application Specific)
  38973. case 0xFFE1: // APP1
  38974. case 0xFFE2: // APP2
  38975. case 0xFFE3: // APP3
  38976. case 0xFFE4: // APP4
  38977. case 0xFFE5: // APP5
  38978. case 0xFFE6: // APP6
  38979. case 0xFFE7: // APP7
  38980. case 0xFFE8: // APP8
  38981. case 0xFFE9: // APP9
  38982. case 0xFFEA: // APP10
  38983. case 0xFFEB: // APP11
  38984. case 0xFFEC: // APP12
  38985. case 0xFFED: // APP13
  38986. case 0xFFEE: // APP14
  38987. case 0xFFEF: // APP15
  38988. case 0xFFFE: // COM (Comment)
  38989. var appData = readDataBlock();
  38990. if (fileMarker === 0xFFE0) {
  38991. if (appData[0] === 0x4A && appData[1] === 0x46 &&
  38992. appData[2] === 0x49 && appData[3] === 0x46 &&
  38993. appData[4] === 0) { // 'JFIF\x00'
  38994. jfif = {
  38995. version: { major: appData[5], minor: appData[6] },
  38996. densityUnits: appData[7],
  38997. xDensity: (appData[8] << 8) | appData[9],
  38998. yDensity: (appData[10] << 8) | appData[11],
  38999. thumbWidth: appData[12],
  39000. thumbHeight: appData[13],
  39001. thumbData: appData.subarray(14, 14 +
  39002. 3 * appData[12] * appData[13])
  39003. };
  39004. }
  39005. }
  39006. // TODO APP1 - Exif
  39007. if (fileMarker === 0xFFEE) {
  39008. if (appData[0] === 0x41 && appData[1] === 0x64 &&
  39009. appData[2] === 0x6F && appData[3] === 0x62 &&
  39010. appData[4] === 0x65) { // 'Adobe'
  39011. adobe = {
  39012. version: (appData[5] << 8) | appData[6],
  39013. flags0: (appData[7] << 8) | appData[8],
  39014. flags1: (appData[9] << 8) | appData[10],
  39015. transformCode: appData[11]
  39016. };
  39017. }
  39018. }
  39019. break;
  39020. case 0xFFDB: // DQT (Define Quantization Tables)
  39021. var quantizationTablesLength = readUint16();
  39022. var quantizationTablesEnd = quantizationTablesLength + offset - 2;
  39023. var z;
  39024. while (offset < quantizationTablesEnd) {
  39025. var quantizationTableSpec = data[offset++];
  39026. var tableData = new Uint16Array(64);
  39027. if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
  39028. for (j = 0; j < 64; j++) {
  39029. z = dctZigZag[j];
  39030. tableData[z] = data[offset++];
  39031. }
  39032. } else if ((quantizationTableSpec >> 4) === 1) { //16 bit
  39033. for (j = 0; j < 64; j++) {
  39034. z = dctZigZag[j];
  39035. tableData[z] = readUint16();
  39036. }
  39037. } else {
  39038. throw 'DQT: invalid table spec';
  39039. }
  39040. quantizationTables[quantizationTableSpec & 15] = tableData;
  39041. }
  39042. break;
  39043. case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
  39044. case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
  39045. case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
  39046. if (frame) {
  39047. throw 'Only single frame JPEGs supported';
  39048. }
  39049. readUint16(); // skip data length
  39050. frame = {};
  39051. frame.extended = (fileMarker === 0xFFC1);
  39052. frame.progressive = (fileMarker === 0xFFC2);
  39053. frame.precision = data[offset++];
  39054. frame.scanLines = readUint16();
  39055. frame.samplesPerLine = readUint16();
  39056. frame.components = [];
  39057. frame.componentIds = {};
  39058. var componentsCount = data[offset++], componentId;
  39059. var maxH = 0, maxV = 0;
  39060. for (i = 0; i < componentsCount; i++) {
  39061. componentId = data[offset];
  39062. var h = data[offset + 1] >> 4;
  39063. var v = data[offset + 1] & 15;
  39064. if (maxH < h) {
  39065. maxH = h;
  39066. }
  39067. if (maxV < v) {
  39068. maxV = v;
  39069. }
  39070. var qId = data[offset + 2];
  39071. l = frame.components.push({
  39072. h: h,
  39073. v: v,
  39074. quantizationTable: quantizationTables[qId]
  39075. });
  39076. frame.componentIds[componentId] = l - 1;
  39077. offset += 3;
  39078. }
  39079. frame.maxH = maxH;
  39080. frame.maxV = maxV;
  39081. prepareComponents(frame);
  39082. break;
  39083. case 0xFFC4: // DHT (Define Huffman Tables)
  39084. var huffmanLength = readUint16();
  39085. for (i = 2; i < huffmanLength;) {
  39086. var huffmanTableSpec = data[offset++];
  39087. var codeLengths = new Uint8Array(16);
  39088. var codeLengthSum = 0;
  39089. for (j = 0; j < 16; j++, offset++) {
  39090. codeLengthSum += (codeLengths[j] = data[offset]);
  39091. }
  39092. var huffmanValues = new Uint8Array(codeLengthSum);
  39093. for (j = 0; j < codeLengthSum; j++, offset++) {
  39094. huffmanValues[j] = data[offset];
  39095. }
  39096. i += 17 + codeLengthSum;
  39097. ((huffmanTableSpec >> 4) === 0 ?
  39098. huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
  39099. buildHuffmanTable(codeLengths, huffmanValues);
  39100. }
  39101. break;
  39102. case 0xFFDD: // DRI (Define Restart Interval)
  39103. readUint16(); // skip data length
  39104. resetInterval = readUint16();
  39105. break;
  39106. case 0xFFDA: // SOS (Start of Scan)
  39107. var scanLength = readUint16();
  39108. var selectorsCount = data[offset++];
  39109. var components = [], component;
  39110. for (i = 0; i < selectorsCount; i++) {
  39111. var componentIndex = frame.componentIds[data[offset++]];
  39112. component = frame.components[componentIndex];
  39113. var tableSpec = data[offset++];
  39114. component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
  39115. component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
  39116. components.push(component);
  39117. }
  39118. var spectralStart = data[offset++];
  39119. var spectralEnd = data[offset++];
  39120. var successiveApproximation = data[offset++];
  39121. var processed = decodeScan(data, offset,
  39122. frame, components, resetInterval,
  39123. spectralStart, spectralEnd,
  39124. successiveApproximation >> 4, successiveApproximation & 15);
  39125. offset += processed;
  39126. break;
  39127. case 0xFFFF: // Fill bytes
  39128. if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
  39129. offset--;
  39130. }
  39131. break;
  39132. default:
  39133. if (data[offset - 3] === 0xFF &&
  39134. data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
  39135. // could be incorrect encoding -- last 0xFF byte of the previous
  39136. // block was eaten by the encoder
  39137. offset -= 3;
  39138. break;
  39139. }
  39140. throw 'unknown JPEG marker ' + fileMarker.toString(16);
  39141. }
  39142. fileMarker = readUint16();
  39143. }
  39144. this.width = frame.samplesPerLine;
  39145. this.height = frame.scanLines;
  39146. this.jfif = jfif;
  39147. this.adobe = adobe;
  39148. this.components = [];
  39149. for (i = 0; i < frame.components.length; i++) {
  39150. component = frame.components[i];
  39151. this.components.push({
  39152. output: buildComponentData(frame, component),
  39153. scaleX: component.h / frame.maxH,
  39154. scaleY: component.v / frame.maxV,
  39155. blocksPerLine: component.blocksPerLine,
  39156. blocksPerColumn: component.blocksPerColumn
  39157. });
  39158. }
  39159. this.numComponents = this.components.length;
  39160. },
  39161. _getLinearizedBlockData: function getLinearizedBlockData(width, height) {
  39162. var scaleX = this.width / width, scaleY = this.height / height;
  39163. var component, componentScaleX, componentScaleY, blocksPerScanline;
  39164. var x, y, i, j, k;
  39165. var index;
  39166. var offset = 0;
  39167. var output;
  39168. var numComponents = this.components.length;
  39169. var dataLength = width * height * numComponents;
  39170. var data = new Uint8Array(dataLength);
  39171. var xScaleBlockOffset = new Uint32Array(width);
  39172. var mask3LSB = 0xfffffff8; // used to clear the 3 LSBs
  39173. for (i = 0; i < numComponents; i++) {
  39174. component = this.components[i];
  39175. componentScaleX = component.scaleX * scaleX;
  39176. componentScaleY = component.scaleY * scaleY;
  39177. offset = i;
  39178. output = component.output;
  39179. blocksPerScanline = (component.blocksPerLine + 1) << 3;
  39180. // precalculate the xScaleBlockOffset
  39181. for (x = 0; x < width; x++) {
  39182. j = 0 | (x * componentScaleX);
  39183. xScaleBlockOffset[x] = ((j & mask3LSB) << 3) | (j & 7);
  39184. }
  39185. // linearize the blocks of the component
  39186. for (y = 0; y < height; y++) {
  39187. j = 0 | (y * componentScaleY);
  39188. index = blocksPerScanline * (j & mask3LSB) | ((j & 7) << 3);
  39189. for (x = 0; x < width; x++) {
  39190. data[offset] = output[index + xScaleBlockOffset[x]];
  39191. offset += numComponents;
  39192. }
  39193. }
  39194. }
  39195. // decodeTransform contains pairs of multiplier (-256..256) and additive
  39196. var transform = this.decodeTransform;
  39197. if (transform) {
  39198. for (i = 0; i < dataLength;) {
  39199. for (j = 0, k = 0; j < numComponents; j++, i++, k += 2) {
  39200. data[i] = ((data[i] * transform[k]) >> 8) + transform[k + 1];
  39201. }
  39202. }
  39203. }
  39204. return data;
  39205. },
  39206. _isColorConversionNeeded: function isColorConversionNeeded() {
  39207. if (this.adobe && this.adobe.transformCode) {
  39208. // The adobe transform marker overrides any previous setting
  39209. return true;
  39210. } else if (this.numComponents === 3) {
  39211. return true;
  39212. } else {
  39213. return false;
  39214. }
  39215. },
  39216. _convertYccToRgb: function convertYccToRgb(data) {
  39217. var Y, Cb, Cr;
  39218. for (var i = 0, length = data.length; i < length; i += 3) {
  39219. Y = data[i ];
  39220. Cb = data[i + 1];
  39221. Cr = data[i + 2];
  39222. data[i ] = clamp0to255(Y - 179.456 + 1.402 * Cr);
  39223. data[i + 1] = clamp0to255(Y + 135.459 - 0.344 * Cb - 0.714 * Cr);
  39224. data[i + 2] = clamp0to255(Y - 226.816 + 1.772 * Cb);
  39225. }
  39226. return data;
  39227. },
  39228. _convertYcckToRgb: function convertYcckToRgb(data) {
  39229. var Y, Cb, Cr, k;
  39230. var offset = 0;
  39231. for (var i = 0, length = data.length; i < length; i += 4) {
  39232. Y = data[i];
  39233. Cb = data[i + 1];
  39234. Cr = data[i + 2];
  39235. k = data[i + 3];
  39236. var r = -122.67195406894 +
  39237. Cb * (-6.60635669420364e-5 * Cb + 0.000437130475926232 * Cr -
  39238. 5.4080610064599e-5 * Y + 0.00048449797120281 * k -
  39239. 0.154362151871126) +
  39240. Cr * (-0.000957964378445773 * Cr + 0.000817076911346625 * Y -
  39241. 0.00477271405408747 * k + 1.53380253221734) +
  39242. Y * (0.000961250184130688 * Y - 0.00266257332283933 * k +
  39243. 0.48357088451265) +
  39244. k * (-0.000336197177618394 * k + 0.484791561490776);
  39245. var g = 107.268039397724 +
  39246. Cb * (2.19927104525741e-5 * Cb - 0.000640992018297945 * Cr +
  39247. 0.000659397001245577 * Y + 0.000426105652938837 * k -
  39248. 0.176491792462875) +
  39249. Cr * (-0.000778269941513683 * Cr + 0.00130872261408275 * Y +
  39250. 0.000770482631801132 * k - 0.151051492775562) +
  39251. Y * (0.00126935368114843 * Y - 0.00265090189010898 * k +
  39252. 0.25802910206845) +
  39253. k * (-0.000318913117588328 * k - 0.213742400323665);
  39254. var b = -20.810012546947 +
  39255. Cb * (-0.000570115196973677 * Cb - 2.63409051004589e-5 * Cr +
  39256. 0.0020741088115012 * Y - 0.00288260236853442 * k +
  39257. 0.814272968359295) +
  39258. Cr * (-1.53496057440975e-5 * Cr - 0.000132689043961446 * Y +
  39259. 0.000560833691242812 * k - 0.195152027534049) +
  39260. Y * (0.00174418132927582 * Y - 0.00255243321439347 * k +
  39261. 0.116935020465145) +
  39262. k * (-0.000343531996510555 * k + 0.24165260232407);
  39263. data[offset++] = clamp0to255(r);
  39264. data[offset++] = clamp0to255(g);
  39265. data[offset++] = clamp0to255(b);
  39266. }
  39267. return data;
  39268. },
  39269. _convertYcckToCmyk: function convertYcckToCmyk(data) {
  39270. var Y, Cb, Cr;
  39271. for (var i = 0, length = data.length; i < length; i += 4) {
  39272. Y = data[i];
  39273. Cb = data[i + 1];
  39274. Cr = data[i + 2];
  39275. data[i ] = clamp0to255(434.456 - Y - 1.402 * Cr);
  39276. data[i + 1] = clamp0to255(119.541 - Y + 0.344 * Cb + 0.714 * Cr);
  39277. data[i + 2] = clamp0to255(481.816 - Y - 1.772 * Cb);
  39278. // K in data[i + 3] is unchanged
  39279. }
  39280. return data;
  39281. },
  39282. _convertCmykToRgb: function convertCmykToRgb(data) {
  39283. var c, m, y, k;
  39284. var offset = 0;
  39285. var min = -255 * 255 * 255;
  39286. var scale = 1 / 255 / 255;
  39287. for (var i = 0, length = data.length; i < length; i += 4) {
  39288. c = data[i];
  39289. m = data[i + 1];
  39290. y = data[i + 2];
  39291. k = data[i + 3];
  39292. var r =
  39293. c * (-4.387332384609988 * c + 54.48615194189176 * m +
  39294. 18.82290502165302 * y + 212.25662451639585 * k -
  39295. 72734.4411664936) +
  39296. m * (1.7149763477362134 * m - 5.6096736904047315 * y -
  39297. 17.873870861415444 * k - 1401.7366389350734) +
  39298. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  39299. 4465.541406466231) -
  39300. k * (21.86122147463605 * k + 48317.86113160301);
  39301. var g =
  39302. c * (8.841041422036149 * c + 60.118027045597366 * m +
  39303. 6.871425592049007 * y + 31.159100130055922 * k -
  39304. 20220.756542821975) +
  39305. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  39306. 131.35250912493976 * k - 48691.05921601825) +
  39307. y * (4.444339102852739 * y + 9.8632861493405 * k -
  39308. 6341.191035517494) -
  39309. k * (20.737325471181034 * k + 47890.15695978492);
  39310. var b =
  39311. c * (0.8842522430003296 * c + 8.078677503112928 * m +
  39312. 30.89978309703729 * y - 0.23883238689178934 * k -
  39313. 3616.812083916688) +
  39314. m * (10.49593273432072 * m + 63.02378494754052 * y +
  39315. 50.606957656360734 * k - 28620.90484698408) +
  39316. y * (0.03296041114873217 * y + 115.60384449646641 * k -
  39317. 49363.43385999684) -
  39318. k * (22.33816807309886 * k + 45932.16563550634);
  39319. data[offset++] = r >= 0 ? 255 : r <= min ? 0 : 255 + r * scale | 0;
  39320. data[offset++] = g >= 0 ? 255 : g <= min ? 0 : 255 + g * scale | 0;
  39321. data[offset++] = b >= 0 ? 255 : b <= min ? 0 : 255 + b * scale | 0;
  39322. }
  39323. return data;
  39324. },
  39325. getData: function getData(width, height, forceRGBoutput) {
  39326. if (this.numComponents > 4) {
  39327. throw 'Unsupported color mode';
  39328. }
  39329. // type of data: Uint8Array(width * height * numComponents)
  39330. var data = this._getLinearizedBlockData(width, height);
  39331. if (this.numComponents === 3) {
  39332. return this._convertYccToRgb(data);
  39333. } else if (this.numComponents === 4) {
  39334. if (this._isColorConversionNeeded()) {
  39335. if (forceRGBoutput) {
  39336. return this._convertYcckToRgb(data);
  39337. } else {
  39338. return this._convertYcckToCmyk(data);
  39339. }
  39340. } else if (forceRGBoutput) {
  39341. return this._convertCmykToRgb(data);
  39342. }
  39343. }
  39344. return data;
  39345. }
  39346. };
  39347. return constructor;
  39348. })();
  39349. var JpxImage = (function JpxImageClosure() {
  39350. // Table E.1
  39351. var SubbandsGainLog2 = {
  39352. 'LL': 0,
  39353. 'LH': 1,
  39354. 'HL': 1,
  39355. 'HH': 2
  39356. };
  39357. function JpxImage() {
  39358. this.failOnCorruptedImage = false;
  39359. }
  39360. JpxImage.prototype = {
  39361. parse: function JpxImage_parse(data) {
  39362. var head = readUint16(data, 0);
  39363. // No box header, immediate start of codestream (SOC)
  39364. if (head === 0xFF4F) {
  39365. this.parseCodestream(data, 0, data.length);
  39366. return;
  39367. }
  39368. var position = 0, length = data.length;
  39369. while (position < length) {
  39370. var headerSize = 8;
  39371. var lbox = readUint32(data, position);
  39372. var tbox = readUint32(data, position + 4);
  39373. position += headerSize;
  39374. if (lbox === 1) {
  39375. // XLBox: read UInt64 according to spec.
  39376. // JavaScript's int precision of 53 bit should be sufficient here.
  39377. lbox = readUint32(data, position) * 4294967296 +
  39378. readUint32(data, position + 4);
  39379. position += 8;
  39380. headerSize += 8;
  39381. }
  39382. if (lbox === 0) {
  39383. lbox = length - position + headerSize;
  39384. }
  39385. if (lbox < headerSize) {
  39386. throw new Error('JPX Error: Invalid box field size');
  39387. }
  39388. var dataLength = lbox - headerSize;
  39389. var jumpDataLength = true;
  39390. switch (tbox) {
  39391. case 0x6A703268: // 'jp2h'
  39392. jumpDataLength = false; // parsing child boxes
  39393. break;
  39394. case 0x636F6C72: // 'colr'
  39395. // Colorspaces are not used, the CS from the PDF is used.
  39396. var method = data[position];
  39397. var precedence = data[position + 1];
  39398. var approximation = data[position + 2];
  39399. if (method === 1) {
  39400. // enumerated colorspace
  39401. var colorspace = readUint32(data, position + 3);
  39402. switch (colorspace) {
  39403. case 16: // this indicates a sRGB colorspace
  39404. case 17: // this indicates a grayscale colorspace
  39405. case 18: // this indicates a YUV colorspace
  39406. break;
  39407. default:
  39408. warn('Unknown colorspace ' + colorspace);
  39409. break;
  39410. }
  39411. } else if (method === 2) {
  39412. info('ICC profile not supported');
  39413. }
  39414. break;
  39415. case 0x6A703263: // 'jp2c'
  39416. this.parseCodestream(data, position, position + dataLength);
  39417. break;
  39418. case 0x6A502020: // 'jP\024\024'
  39419. if (0x0d0a870a !== readUint32(data, position)) {
  39420. warn('Invalid JP2 signature');
  39421. }
  39422. break;
  39423. // The following header types are valid but currently not used:
  39424. case 0x6A501A1A: // 'jP\032\032'
  39425. case 0x66747970: // 'ftyp'
  39426. case 0x72726571: // 'rreq'
  39427. case 0x72657320: // 'res '
  39428. case 0x69686472: // 'ihdr'
  39429. break;
  39430. default:
  39431. var headerType = String.fromCharCode((tbox >> 24) & 0xFF,
  39432. (tbox >> 16) & 0xFF,
  39433. (tbox >> 8) & 0xFF,
  39434. tbox & 0xFF);
  39435. warn('Unsupported header type ' + tbox + ' (' + headerType + ')');
  39436. break;
  39437. }
  39438. if (jumpDataLength) {
  39439. position += dataLength;
  39440. }
  39441. }
  39442. },
  39443. parseImageProperties: function JpxImage_parseImageProperties(stream) {
  39444. var newByte = stream.getByte();
  39445. while (newByte >= 0) {
  39446. var oldByte = newByte;
  39447. newByte = stream.getByte();
  39448. var code = (oldByte << 8) | newByte;
  39449. // Image and tile size (SIZ)
  39450. if (code === 0xFF51) {
  39451. stream.skip(4);
  39452. var Xsiz = stream.getInt32() >>> 0; // Byte 4
  39453. var Ysiz = stream.getInt32() >>> 0; // Byte 8
  39454. var XOsiz = stream.getInt32() >>> 0; // Byte 12
  39455. var YOsiz = stream.getInt32() >>> 0; // Byte 16
  39456. stream.skip(16);
  39457. var Csiz = stream.getUint16(); // Byte 36
  39458. this.width = Xsiz - XOsiz;
  39459. this.height = Ysiz - YOsiz;
  39460. this.componentsCount = Csiz;
  39461. // Results are always returned as Uint8Arrays
  39462. this.bitsPerComponent = 8;
  39463. return;
  39464. }
  39465. }
  39466. throw new Error('JPX Error: No size marker found in JPX stream');
  39467. },
  39468. parseCodestream: function JpxImage_parseCodestream(data, start, end) {
  39469. var context = {};
  39470. try {
  39471. var doNotRecover = false;
  39472. var position = start;
  39473. while (position + 1 < end) {
  39474. var code = readUint16(data, position);
  39475. position += 2;
  39476. var length = 0, j, sqcd, spqcds, spqcdSize, scalarExpounded, tile;
  39477. switch (code) {
  39478. case 0xFF4F: // Start of codestream (SOC)
  39479. context.mainHeader = true;
  39480. break;
  39481. case 0xFFD9: // End of codestream (EOC)
  39482. break;
  39483. case 0xFF51: // Image and tile size (SIZ)
  39484. length = readUint16(data, position);
  39485. var siz = {};
  39486. siz.Xsiz = readUint32(data, position + 4);
  39487. siz.Ysiz = readUint32(data, position + 8);
  39488. siz.XOsiz = readUint32(data, position + 12);
  39489. siz.YOsiz = readUint32(data, position + 16);
  39490. siz.XTsiz = readUint32(data, position + 20);
  39491. siz.YTsiz = readUint32(data, position + 24);
  39492. siz.XTOsiz = readUint32(data, position + 28);
  39493. siz.YTOsiz = readUint32(data, position + 32);
  39494. var componentsCount = readUint16(data, position + 36);
  39495. siz.Csiz = componentsCount;
  39496. var components = [];
  39497. j = position + 38;
  39498. for (var i = 0; i < componentsCount; i++) {
  39499. var component = {
  39500. precision: (data[j] & 0x7F) + 1,
  39501. isSigned: !!(data[j] & 0x80),
  39502. XRsiz: data[j + 1],
  39503. YRsiz: data[j + 1]
  39504. };
  39505. calculateComponentDimensions(component, siz);
  39506. components.push(component);
  39507. }
  39508. context.SIZ = siz;
  39509. context.components = components;
  39510. calculateTileGrids(context, components);
  39511. context.QCC = [];
  39512. context.COC = [];
  39513. break;
  39514. case 0xFF5C: // Quantization default (QCD)
  39515. length = readUint16(data, position);
  39516. var qcd = {};
  39517. j = position + 2;
  39518. sqcd = data[j++];
  39519. switch (sqcd & 0x1F) {
  39520. case 0:
  39521. spqcdSize = 8;
  39522. scalarExpounded = true;
  39523. break;
  39524. case 1:
  39525. spqcdSize = 16;
  39526. scalarExpounded = false;
  39527. break;
  39528. case 2:
  39529. spqcdSize = 16;
  39530. scalarExpounded = true;
  39531. break;
  39532. default:
  39533. throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
  39534. }
  39535. qcd.noQuantization = (spqcdSize === 8);
  39536. qcd.scalarExpounded = scalarExpounded;
  39537. qcd.guardBits = sqcd >> 5;
  39538. spqcds = [];
  39539. while (j < length + position) {
  39540. var spqcd = {};
  39541. if (spqcdSize === 8) {
  39542. spqcd.epsilon = data[j++] >> 3;
  39543. spqcd.mu = 0;
  39544. } else {
  39545. spqcd.epsilon = data[j] >> 3;
  39546. spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
  39547. j += 2;
  39548. }
  39549. spqcds.push(spqcd);
  39550. }
  39551. qcd.SPqcds = spqcds;
  39552. if (context.mainHeader) {
  39553. context.QCD = qcd;
  39554. } else {
  39555. context.currentTile.QCD = qcd;
  39556. context.currentTile.QCC = [];
  39557. }
  39558. break;
  39559. case 0xFF5D: // Quantization component (QCC)
  39560. length = readUint16(data, position);
  39561. var qcc = {};
  39562. j = position + 2;
  39563. var cqcc;
  39564. if (context.SIZ.Csiz < 257) {
  39565. cqcc = data[j++];
  39566. } else {
  39567. cqcc = readUint16(data, j);
  39568. j += 2;
  39569. }
  39570. sqcd = data[j++];
  39571. switch (sqcd & 0x1F) {
  39572. case 0:
  39573. spqcdSize = 8;
  39574. scalarExpounded = true;
  39575. break;
  39576. case 1:
  39577. spqcdSize = 16;
  39578. scalarExpounded = false;
  39579. break;
  39580. case 2:
  39581. spqcdSize = 16;
  39582. scalarExpounded = true;
  39583. break;
  39584. default:
  39585. throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
  39586. }
  39587. qcc.noQuantization = (spqcdSize === 8);
  39588. qcc.scalarExpounded = scalarExpounded;
  39589. qcc.guardBits = sqcd >> 5;
  39590. spqcds = [];
  39591. while (j < (length + position)) {
  39592. spqcd = {};
  39593. if (spqcdSize === 8) {
  39594. spqcd.epsilon = data[j++] >> 3;
  39595. spqcd.mu = 0;
  39596. } else {
  39597. spqcd.epsilon = data[j] >> 3;
  39598. spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
  39599. j += 2;
  39600. }
  39601. spqcds.push(spqcd);
  39602. }
  39603. qcc.SPqcds = spqcds;
  39604. if (context.mainHeader) {
  39605. context.QCC[cqcc] = qcc;
  39606. } else {
  39607. context.currentTile.QCC[cqcc] = qcc;
  39608. }
  39609. break;
  39610. case 0xFF52: // Coding style default (COD)
  39611. length = readUint16(data, position);
  39612. var cod = {};
  39613. j = position + 2;
  39614. var scod = data[j++];
  39615. cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
  39616. cod.sopMarkerUsed = !!(scod & 2);
  39617. cod.ephMarkerUsed = !!(scod & 4);
  39618. cod.progressionOrder = data[j++];
  39619. cod.layersCount = readUint16(data, j);
  39620. j += 2;
  39621. cod.multipleComponentTransform = data[j++];
  39622. cod.decompositionLevelsCount = data[j++];
  39623. cod.xcb = (data[j++] & 0xF) + 2;
  39624. cod.ycb = (data[j++] & 0xF) + 2;
  39625. var blockStyle = data[j++];
  39626. cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
  39627. cod.resetContextProbabilities = !!(blockStyle & 2);
  39628. cod.terminationOnEachCodingPass = !!(blockStyle & 4);
  39629. cod.verticalyStripe = !!(blockStyle & 8);
  39630. cod.predictableTermination = !!(blockStyle & 16);
  39631. cod.segmentationSymbolUsed = !!(blockStyle & 32);
  39632. cod.reversibleTransformation = data[j++];
  39633. if (cod.entropyCoderWithCustomPrecincts) {
  39634. var precinctsSizes = [];
  39635. while (j < length + position) {
  39636. var precinctsSize = data[j++];
  39637. precinctsSizes.push({
  39638. PPx: precinctsSize & 0xF,
  39639. PPy: precinctsSize >> 4
  39640. });
  39641. }
  39642. cod.precinctsSizes = precinctsSizes;
  39643. }
  39644. var unsupported = [];
  39645. if (cod.selectiveArithmeticCodingBypass) {
  39646. unsupported.push('selectiveArithmeticCodingBypass');
  39647. }
  39648. if (cod.resetContextProbabilities) {
  39649. unsupported.push('resetContextProbabilities');
  39650. }
  39651. if (cod.terminationOnEachCodingPass) {
  39652. unsupported.push('terminationOnEachCodingPass');
  39653. }
  39654. if (cod.verticalyStripe) {
  39655. unsupported.push('verticalyStripe');
  39656. }
  39657. if (cod.predictableTermination) {
  39658. unsupported.push('predictableTermination');
  39659. }
  39660. if (unsupported.length > 0) {
  39661. doNotRecover = true;
  39662. throw new Error('JPX Error: Unsupported COD options (' +
  39663. unsupported.join(', ') + ')');
  39664. }
  39665. if (context.mainHeader) {
  39666. context.COD = cod;
  39667. } else {
  39668. context.currentTile.COD = cod;
  39669. context.currentTile.COC = [];
  39670. }
  39671. break;
  39672. case 0xFF90: // Start of tile-part (SOT)
  39673. length = readUint16(data, position);
  39674. tile = {};
  39675. tile.index = readUint16(data, position + 2);
  39676. tile.length = readUint32(data, position + 4);
  39677. tile.dataEnd = tile.length + position - 2;
  39678. tile.partIndex = data[position + 8];
  39679. tile.partsCount = data[position + 9];
  39680. context.mainHeader = false;
  39681. if (tile.partIndex === 0) {
  39682. // reset component specific settings
  39683. tile.COD = context.COD;
  39684. tile.COC = context.COC.slice(0); // clone of the global COC
  39685. tile.QCD = context.QCD;
  39686. tile.QCC = context.QCC.slice(0); // clone of the global COC
  39687. }
  39688. context.currentTile = tile;
  39689. break;
  39690. case 0xFF93: // Start of data (SOD)
  39691. tile = context.currentTile;
  39692. if (tile.partIndex === 0) {
  39693. initializeTile(context, tile.index);
  39694. buildPackets(context);
  39695. }
  39696. // moving to the end of the data
  39697. length = tile.dataEnd - position;
  39698. parseTilePackets(context, data, position, length);
  39699. break;
  39700. case 0xFF55: // Tile-part lengths, main header (TLM)
  39701. case 0xFF57: // Packet length, main header (PLM)
  39702. case 0xFF58: // Packet length, tile-part header (PLT)
  39703. case 0xFF64: // Comment (COM)
  39704. length = readUint16(data, position);
  39705. // skipping content
  39706. break;
  39707. case 0xFF53: // Coding style component (COC)
  39708. throw new Error('JPX Error: Codestream code 0xFF53 (COC) is ' +
  39709. 'not implemented');
  39710. default:
  39711. throw new Error('JPX Error: Unknown codestream code: ' +
  39712. code.toString(16));
  39713. }
  39714. position += length;
  39715. }
  39716. } catch (e) {
  39717. if (doNotRecover || this.failOnCorruptedImage) {
  39718. throw e;
  39719. } else {
  39720. warn('Trying to recover from ' + e.message);
  39721. }
  39722. }
  39723. this.tiles = transformComponents(context);
  39724. this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
  39725. this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
  39726. this.componentsCount = context.SIZ.Csiz;
  39727. }
  39728. };
  39729. function calculateComponentDimensions(component, siz) {
  39730. // Section B.2 Component mapping
  39731. component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
  39732. component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
  39733. component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
  39734. component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
  39735. component.width = component.x1 - component.x0;
  39736. component.height = component.y1 - component.y0;
  39737. }
  39738. function calculateTileGrids(context, components) {
  39739. var siz = context.SIZ;
  39740. // Section B.3 Division into tile and tile-components
  39741. var tile, tiles = [];
  39742. var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
  39743. var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
  39744. for (var q = 0; q < numYtiles; q++) {
  39745. for (var p = 0; p < numXtiles; p++) {
  39746. tile = {};
  39747. tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
  39748. tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
  39749. tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
  39750. tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
  39751. tile.width = tile.tx1 - tile.tx0;
  39752. tile.height = tile.ty1 - tile.ty0;
  39753. tile.components = [];
  39754. tiles.push(tile);
  39755. }
  39756. }
  39757. context.tiles = tiles;
  39758. var componentsCount = siz.Csiz;
  39759. for (var i = 0, ii = componentsCount; i < ii; i++) {
  39760. var component = components[i];
  39761. for (var j = 0, jj = tiles.length; j < jj; j++) {
  39762. var tileComponent = {};
  39763. tile = tiles[j];
  39764. tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
  39765. tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
  39766. tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
  39767. tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
  39768. tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
  39769. tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
  39770. tile.components[i] = tileComponent;
  39771. }
  39772. }
  39773. }
  39774. function getBlocksDimensions(context, component, r) {
  39775. var codOrCoc = component.codingStyleParameters;
  39776. var result = {};
  39777. if (!codOrCoc.entropyCoderWithCustomPrecincts) {
  39778. result.PPx = 15;
  39779. result.PPy = 15;
  39780. } else {
  39781. result.PPx = codOrCoc.precinctsSizes[r].PPx;
  39782. result.PPy = codOrCoc.precinctsSizes[r].PPy;
  39783. }
  39784. // calculate codeblock size as described in section B.7
  39785. result.xcb_ = (r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) :
  39786. Math.min(codOrCoc.xcb, result.PPx));
  39787. result.ycb_ = (r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) :
  39788. Math.min(codOrCoc.ycb, result.PPy));
  39789. return result;
  39790. }
  39791. function buildPrecincts(context, resolution, dimensions) {
  39792. // Section B.6 Division resolution to precincts
  39793. var precinctWidth = 1 << dimensions.PPx;
  39794. var precinctHeight = 1 << dimensions.PPy;
  39795. // Jasper introduces codeblock groups for mapping each subband codeblocks
  39796. // to precincts. Precinct partition divides a resolution according to width
  39797. // and height parameters. The subband that belongs to the resolution level
  39798. // has a different size than the level, unless it is the zero resolution.
  39799. // From Jasper documentation: jpeg2000.pdf, section K: Tier-2 coding:
  39800. // The precinct partitioning for a particular subband is derived from a
  39801. // partitioning of its parent LL band (i.e., the LL band at the next higher
  39802. // resolution level)... The LL band associated with each resolution level is
  39803. // divided into precincts... Each of the resulting precinct regions is then
  39804. // mapped into its child subbands (if any) at the next lower resolution
  39805. // level. This is accomplished by using the coordinate transformation
  39806. // (u, v) = (ceil(x/2), ceil(y/2)) where (x, y) and (u, v) are the
  39807. // coordinates of a point in the LL band and child subband, respectively.
  39808. var isZeroRes = resolution.resLevel === 0;
  39809. var precinctWidthInSubband = 1 << (dimensions.PPx + (isZeroRes ? 0 : -1));
  39810. var precinctHeightInSubband = 1 << (dimensions.PPy + (isZeroRes ? 0 : -1));
  39811. var numprecinctswide = (resolution.trx1 > resolution.trx0 ?
  39812. Math.ceil(resolution.trx1 / precinctWidth) -
  39813. Math.floor(resolution.trx0 / precinctWidth) : 0);
  39814. var numprecinctshigh = (resolution.try1 > resolution.try0 ?
  39815. Math.ceil(resolution.try1 / precinctHeight) -
  39816. Math.floor(resolution.try0 / precinctHeight) : 0);
  39817. var numprecincts = numprecinctswide * numprecinctshigh;
  39818. resolution.precinctParameters = {
  39819. precinctWidth: precinctWidth,
  39820. precinctHeight: precinctHeight,
  39821. numprecinctswide: numprecinctswide,
  39822. numprecinctshigh: numprecinctshigh,
  39823. numprecincts: numprecincts,
  39824. precinctWidthInSubband: precinctWidthInSubband,
  39825. precinctHeightInSubband: precinctHeightInSubband
  39826. };
  39827. }
  39828. function buildCodeblocks(context, subband, dimensions) {
  39829. // Section B.7 Division sub-band into code-blocks
  39830. var xcb_ = dimensions.xcb_;
  39831. var ycb_ = dimensions.ycb_;
  39832. var codeblockWidth = 1 << xcb_;
  39833. var codeblockHeight = 1 << ycb_;
  39834. var cbx0 = subband.tbx0 >> xcb_;
  39835. var cby0 = subband.tby0 >> ycb_;
  39836. var cbx1 = (subband.tbx1 + codeblockWidth - 1) >> xcb_;
  39837. var cby1 = (subband.tby1 + codeblockHeight - 1) >> ycb_;
  39838. var precinctParameters = subband.resolution.precinctParameters;
  39839. var codeblocks = [];
  39840. var precincts = [];
  39841. var i, j, codeblock, precinctNumber;
  39842. for (j = cby0; j < cby1; j++) {
  39843. for (i = cbx0; i < cbx1; i++) {
  39844. codeblock = {
  39845. cbx: i,
  39846. cby: j,
  39847. tbx0: codeblockWidth * i,
  39848. tby0: codeblockHeight * j,
  39849. tbx1: codeblockWidth * (i + 1),
  39850. tby1: codeblockHeight * (j + 1)
  39851. };
  39852. codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
  39853. codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
  39854. codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
  39855. codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
  39856. // Calculate precinct number for this codeblock, codeblock position
  39857. // should be relative to its subband, use actual dimension and position
  39858. // See comment about codeblock group width and height
  39859. var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) /
  39860. precinctParameters.precinctWidthInSubband);
  39861. var pj = Math.floor((codeblock.tby0_ - subband.tby0) /
  39862. precinctParameters.precinctHeightInSubband);
  39863. precinctNumber = pi + (pj * precinctParameters.numprecinctswide);
  39864. codeblock.precinctNumber = precinctNumber;
  39865. codeblock.subbandType = subband.type;
  39866. codeblock.Lblock = 3;
  39867. if (codeblock.tbx1_ <= codeblock.tbx0_ ||
  39868. codeblock.tby1_ <= codeblock.tby0_) {
  39869. continue;
  39870. }
  39871. codeblocks.push(codeblock);
  39872. // building precinct for the sub-band
  39873. var precinct = precincts[precinctNumber];
  39874. if (precinct !== undefined) {
  39875. if (i < precinct.cbxMin) {
  39876. precinct.cbxMin = i;
  39877. } else if (i > precinct.cbxMax) {
  39878. precinct.cbxMax = i;
  39879. }
  39880. if (j < precinct.cbyMin) {
  39881. precinct.cbxMin = j;
  39882. } else if (j > precinct.cbyMax) {
  39883. precinct.cbyMax = j;
  39884. }
  39885. } else {
  39886. precincts[precinctNumber] = precinct = {
  39887. cbxMin: i,
  39888. cbyMin: j,
  39889. cbxMax: i,
  39890. cbyMax: j
  39891. };
  39892. }
  39893. codeblock.precinct = precinct;
  39894. }
  39895. }
  39896. subband.codeblockParameters = {
  39897. codeblockWidth: xcb_,
  39898. codeblockHeight: ycb_,
  39899. numcodeblockwide: cbx1 - cbx0 + 1,
  39900. numcodeblockhigh: cby1 - cby0 + 1
  39901. };
  39902. subband.codeblocks = codeblocks;
  39903. subband.precincts = precincts;
  39904. }
  39905. function createPacket(resolution, precinctNumber, layerNumber) {
  39906. var precinctCodeblocks = [];
  39907. // Section B.10.8 Order of info in packet
  39908. var subbands = resolution.subbands;
  39909. // sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence
  39910. for (var i = 0, ii = subbands.length; i < ii; i++) {
  39911. var subband = subbands[i];
  39912. var codeblocks = subband.codeblocks;
  39913. for (var j = 0, jj = codeblocks.length; j < jj; j++) {
  39914. var codeblock = codeblocks[j];
  39915. if (codeblock.precinctNumber !== precinctNumber) {
  39916. continue;
  39917. }
  39918. precinctCodeblocks.push(codeblock);
  39919. }
  39920. }
  39921. return {
  39922. layerNumber: layerNumber,
  39923. codeblocks: precinctCodeblocks
  39924. };
  39925. }
  39926. function LayerResolutionComponentPositionIterator(context) {
  39927. var siz = context.SIZ;
  39928. var tileIndex = context.currentTile.index;
  39929. var tile = context.tiles[tileIndex];
  39930. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39931. var componentsCount = siz.Csiz;
  39932. var maxDecompositionLevelsCount = 0;
  39933. for (var q = 0; q < componentsCount; q++) {
  39934. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39935. tile.components[q].codingStyleParameters.decompositionLevelsCount);
  39936. }
  39937. var l = 0, r = 0, i = 0, k = 0;
  39938. this.nextPacket = function JpxImage_nextPacket() {
  39939. // Section B.12.1.1 Layer-resolution-component-position
  39940. for (; l < layersCount; l++) {
  39941. for (; r <= maxDecompositionLevelsCount; r++) {
  39942. for (; i < componentsCount; i++) {
  39943. var component = tile.components[i];
  39944. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39945. continue;
  39946. }
  39947. var resolution = component.resolutions[r];
  39948. var numprecincts = resolution.precinctParameters.numprecincts;
  39949. for (; k < numprecincts;) {
  39950. var packet = createPacket(resolution, k, l);
  39951. k++;
  39952. return packet;
  39953. }
  39954. k = 0;
  39955. }
  39956. i = 0;
  39957. }
  39958. r = 0;
  39959. }
  39960. throw new Error('JPX Error: Out of packets');
  39961. };
  39962. }
  39963. function ResolutionLayerComponentPositionIterator(context) {
  39964. var siz = context.SIZ;
  39965. var tileIndex = context.currentTile.index;
  39966. var tile = context.tiles[tileIndex];
  39967. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39968. var componentsCount = siz.Csiz;
  39969. var maxDecompositionLevelsCount = 0;
  39970. for (var q = 0; q < componentsCount; q++) {
  39971. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39972. tile.components[q].codingStyleParameters.decompositionLevelsCount);
  39973. }
  39974. var r = 0, l = 0, i = 0, k = 0;
  39975. this.nextPacket = function JpxImage_nextPacket() {
  39976. // Section B.12.1.2 Resolution-layer-component-position
  39977. for (; r <= maxDecompositionLevelsCount; r++) {
  39978. for (; l < layersCount; l++) {
  39979. for (; i < componentsCount; i++) {
  39980. var component = tile.components[i];
  39981. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39982. continue;
  39983. }
  39984. var resolution = component.resolutions[r];
  39985. var numprecincts = resolution.precinctParameters.numprecincts;
  39986. for (; k < numprecincts;) {
  39987. var packet = createPacket(resolution, k, l);
  39988. k++;
  39989. return packet;
  39990. }
  39991. k = 0;
  39992. }
  39993. i = 0;
  39994. }
  39995. l = 0;
  39996. }
  39997. throw new Error('JPX Error: Out of packets');
  39998. };
  39999. }
  40000. function ResolutionPositionComponentLayerIterator(context) {
  40001. var siz = context.SIZ;
  40002. var tileIndex = context.currentTile.index;
  40003. var tile = context.tiles[tileIndex];
  40004. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  40005. var componentsCount = siz.Csiz;
  40006. var l, r, c, p;
  40007. var maxDecompositionLevelsCount = 0;
  40008. for (c = 0; c < componentsCount; c++) {
  40009. var component = tile.components[c];
  40010. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  40011. component.codingStyleParameters.decompositionLevelsCount);
  40012. }
  40013. var maxNumPrecinctsInLevel = new Int32Array(
  40014. maxDecompositionLevelsCount + 1);
  40015. for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
  40016. var maxNumPrecincts = 0;
  40017. for (c = 0; c < componentsCount; ++c) {
  40018. var resolutions = tile.components[c].resolutions;
  40019. if (r < resolutions.length) {
  40020. maxNumPrecincts = Math.max(maxNumPrecincts,
  40021. resolutions[r].precinctParameters.numprecincts);
  40022. }
  40023. }
  40024. maxNumPrecinctsInLevel[r] = maxNumPrecincts;
  40025. }
  40026. l = 0;
  40027. r = 0;
  40028. c = 0;
  40029. p = 0;
  40030. this.nextPacket = function JpxImage_nextPacket() {
  40031. // Section B.12.1.3 Resolution-position-component-layer
  40032. for (; r <= maxDecompositionLevelsCount; r++) {
  40033. for (; p < maxNumPrecinctsInLevel[r]; p++) {
  40034. for (; c < componentsCount; c++) {
  40035. var component = tile.components[c];
  40036. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  40037. continue;
  40038. }
  40039. var resolution = component.resolutions[r];
  40040. var numprecincts = resolution.precinctParameters.numprecincts;
  40041. if (p >= numprecincts) {
  40042. continue;
  40043. }
  40044. for (; l < layersCount;) {
  40045. var packet = createPacket(resolution, p, l);
  40046. l++;
  40047. return packet;
  40048. }
  40049. l = 0;
  40050. }
  40051. c = 0;
  40052. }
  40053. p = 0;
  40054. }
  40055. throw new Error('JPX Error: Out of packets');
  40056. };
  40057. }
  40058. function PositionComponentResolutionLayerIterator(context) {
  40059. var siz = context.SIZ;
  40060. var tileIndex = context.currentTile.index;
  40061. var tile = context.tiles[tileIndex];
  40062. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  40063. var componentsCount = siz.Csiz;
  40064. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  40065. var precinctsIterationSizes = precinctsSizes;
  40066. var l = 0, r = 0, c = 0, px = 0, py = 0;
  40067. this.nextPacket = function JpxImage_nextPacket() {
  40068. // Section B.12.1.4 Position-component-resolution-layer
  40069. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  40070. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  40071. for (; c < componentsCount; c++) {
  40072. var component = tile.components[c];
  40073. var decompositionLevelsCount =
  40074. component.codingStyleParameters.decompositionLevelsCount;
  40075. for (; r <= decompositionLevelsCount; r++) {
  40076. var resolution = component.resolutions[r];
  40077. var sizeInImageScale =
  40078. precinctsSizes.components[c].resolutions[r];
  40079. var k = getPrecinctIndexIfExist(
  40080. px,
  40081. py,
  40082. sizeInImageScale,
  40083. precinctsIterationSizes,
  40084. resolution);
  40085. if (k === null) {
  40086. continue;
  40087. }
  40088. for (; l < layersCount;) {
  40089. var packet = createPacket(resolution, k, l);
  40090. l++;
  40091. return packet;
  40092. }
  40093. l = 0;
  40094. }
  40095. r = 0;
  40096. }
  40097. c = 0;
  40098. }
  40099. px = 0;
  40100. }
  40101. throw new Error('JPX Error: Out of packets');
  40102. };
  40103. }
  40104. function ComponentPositionResolutionLayerIterator(context) {
  40105. var siz = context.SIZ;
  40106. var tileIndex = context.currentTile.index;
  40107. var tile = context.tiles[tileIndex];
  40108. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  40109. var componentsCount = siz.Csiz;
  40110. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  40111. var l = 0, r = 0, c = 0, px = 0, py = 0;
  40112. this.nextPacket = function JpxImage_nextPacket() {
  40113. // Section B.12.1.5 Component-position-resolution-layer
  40114. for (; c < componentsCount; ++c) {
  40115. var component = tile.components[c];
  40116. var precinctsIterationSizes = precinctsSizes.components[c];
  40117. var decompositionLevelsCount =
  40118. component.codingStyleParameters.decompositionLevelsCount;
  40119. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  40120. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  40121. for (; r <= decompositionLevelsCount; r++) {
  40122. var resolution = component.resolutions[r];
  40123. var sizeInImageScale = precinctsIterationSizes.resolutions[r];
  40124. var k = getPrecinctIndexIfExist(
  40125. px,
  40126. py,
  40127. sizeInImageScale,
  40128. precinctsIterationSizes,
  40129. resolution);
  40130. if (k === null) {
  40131. continue;
  40132. }
  40133. for (; l < layersCount;) {
  40134. var packet = createPacket(resolution, k, l);
  40135. l++;
  40136. return packet;
  40137. }
  40138. l = 0;
  40139. }
  40140. r = 0;
  40141. }
  40142. px = 0;
  40143. }
  40144. py = 0;
  40145. }
  40146. throw new Error('JPX Error: Out of packets');
  40147. };
  40148. }
  40149. function getPrecinctIndexIfExist(
  40150. pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
  40151. var posX = pxIndex * precinctIterationSizes.minWidth;
  40152. var posY = pyIndex * precinctIterationSizes.minHeight;
  40153. if (posX % sizeInImageScale.width !== 0 ||
  40154. posY % sizeInImageScale.height !== 0) {
  40155. return null;
  40156. }
  40157. var startPrecinctRowIndex =
  40158. (posY / sizeInImageScale.width) *
  40159. resolution.precinctParameters.numprecinctswide;
  40160. return (posX / sizeInImageScale.height) + startPrecinctRowIndex;
  40161. }
  40162. function getPrecinctSizesInImageScale(tile) {
  40163. var componentsCount = tile.components.length;
  40164. var minWidth = Number.MAX_VALUE;
  40165. var minHeight = Number.MAX_VALUE;
  40166. var maxNumWide = 0;
  40167. var maxNumHigh = 0;
  40168. var sizePerComponent = new Array(componentsCount);
  40169. for (var c = 0; c < componentsCount; c++) {
  40170. var component = tile.components[c];
  40171. var decompositionLevelsCount =
  40172. component.codingStyleParameters.decompositionLevelsCount;
  40173. var sizePerResolution = new Array(decompositionLevelsCount + 1);
  40174. var minWidthCurrentComponent = Number.MAX_VALUE;
  40175. var minHeightCurrentComponent = Number.MAX_VALUE;
  40176. var maxNumWideCurrentComponent = 0;
  40177. var maxNumHighCurrentComponent = 0;
  40178. var scale = 1;
  40179. for (var r = decompositionLevelsCount; r >= 0; --r) {
  40180. var resolution = component.resolutions[r];
  40181. var widthCurrentResolution =
  40182. scale * resolution.precinctParameters.precinctWidth;
  40183. var heightCurrentResolution =
  40184. scale * resolution.precinctParameters.precinctHeight;
  40185. minWidthCurrentComponent = Math.min(
  40186. minWidthCurrentComponent,
  40187. widthCurrentResolution);
  40188. minHeightCurrentComponent = Math.min(
  40189. minHeightCurrentComponent,
  40190. heightCurrentResolution);
  40191. maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent,
  40192. resolution.precinctParameters.numprecinctswide);
  40193. maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent,
  40194. resolution.precinctParameters.numprecinctshigh);
  40195. sizePerResolution[r] = {
  40196. width: widthCurrentResolution,
  40197. height: heightCurrentResolution
  40198. };
  40199. scale <<= 1;
  40200. }
  40201. minWidth = Math.min(minWidth, minWidthCurrentComponent);
  40202. minHeight = Math.min(minHeight, minHeightCurrentComponent);
  40203. maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
  40204. maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
  40205. sizePerComponent[c] = {
  40206. resolutions: sizePerResolution,
  40207. minWidth: minWidthCurrentComponent,
  40208. minHeight: minHeightCurrentComponent,
  40209. maxNumWide: maxNumWideCurrentComponent,
  40210. maxNumHigh: maxNumHighCurrentComponent
  40211. };
  40212. }
  40213. return {
  40214. components: sizePerComponent,
  40215. minWidth: minWidth,
  40216. minHeight: minHeight,
  40217. maxNumWide: maxNumWide,
  40218. maxNumHigh: maxNumHigh
  40219. };
  40220. }
  40221. function buildPackets(context) {
  40222. var siz = context.SIZ;
  40223. var tileIndex = context.currentTile.index;
  40224. var tile = context.tiles[tileIndex];
  40225. var componentsCount = siz.Csiz;
  40226. // Creating resolutions and sub-bands for each component
  40227. for (var c = 0; c < componentsCount; c++) {
  40228. var component = tile.components[c];
  40229. var decompositionLevelsCount =
  40230. component.codingStyleParameters.decompositionLevelsCount;
  40231. // Section B.5 Resolution levels and sub-bands
  40232. var resolutions = [];
  40233. var subbands = [];
  40234. for (var r = 0; r <= decompositionLevelsCount; r++) {
  40235. var blocksDimensions = getBlocksDimensions(context, component, r);
  40236. var resolution = {};
  40237. var scale = 1 << (decompositionLevelsCount - r);
  40238. resolution.trx0 = Math.ceil(component.tcx0 / scale);
  40239. resolution.try0 = Math.ceil(component.tcy0 / scale);
  40240. resolution.trx1 = Math.ceil(component.tcx1 / scale);
  40241. resolution.try1 = Math.ceil(component.tcy1 / scale);
  40242. resolution.resLevel = r;
  40243. buildPrecincts(context, resolution, blocksDimensions);
  40244. resolutions.push(resolution);
  40245. var subband;
  40246. if (r === 0) {
  40247. // one sub-band (LL) with last decomposition
  40248. subband = {};
  40249. subband.type = 'LL';
  40250. subband.tbx0 = Math.ceil(component.tcx0 / scale);
  40251. subband.tby0 = Math.ceil(component.tcy0 / scale);
  40252. subband.tbx1 = Math.ceil(component.tcx1 / scale);
  40253. subband.tby1 = Math.ceil(component.tcy1 / scale);
  40254. subband.resolution = resolution;
  40255. buildCodeblocks(context, subband, blocksDimensions);
  40256. subbands.push(subband);
  40257. resolution.subbands = [subband];
  40258. } else {
  40259. var bscale = 1 << (decompositionLevelsCount - r + 1);
  40260. var resolutionSubbands = [];
  40261. // three sub-bands (HL, LH and HH) with rest of decompositions
  40262. subband = {};
  40263. subband.type = 'HL';
  40264. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  40265. subband.tby0 = Math.ceil(component.tcy0 / bscale);
  40266. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  40267. subband.tby1 = Math.ceil(component.tcy1 / bscale);
  40268. subband.resolution = resolution;
  40269. buildCodeblocks(context, subband, blocksDimensions);
  40270. subbands.push(subband);
  40271. resolutionSubbands.push(subband);
  40272. subband = {};
  40273. subband.type = 'LH';
  40274. subband.tbx0 = Math.ceil(component.tcx0 / bscale);
  40275. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  40276. subband.tbx1 = Math.ceil(component.tcx1 / bscale);
  40277. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  40278. subband.resolution = resolution;
  40279. buildCodeblocks(context, subband, blocksDimensions);
  40280. subbands.push(subband);
  40281. resolutionSubbands.push(subband);
  40282. subband = {};
  40283. subband.type = 'HH';
  40284. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  40285. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  40286. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  40287. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  40288. subband.resolution = resolution;
  40289. buildCodeblocks(context, subband, blocksDimensions);
  40290. subbands.push(subband);
  40291. resolutionSubbands.push(subband);
  40292. resolution.subbands = resolutionSubbands;
  40293. }
  40294. }
  40295. component.resolutions = resolutions;
  40296. component.subbands = subbands;
  40297. }
  40298. // Generate the packets sequence
  40299. var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
  40300. switch (progressionOrder) {
  40301. case 0:
  40302. tile.packetsIterator =
  40303. new LayerResolutionComponentPositionIterator(context);
  40304. break;
  40305. case 1:
  40306. tile.packetsIterator =
  40307. new ResolutionLayerComponentPositionIterator(context);
  40308. break;
  40309. case 2:
  40310. tile.packetsIterator =
  40311. new ResolutionPositionComponentLayerIterator(context);
  40312. break;
  40313. case 3:
  40314. tile.packetsIterator =
  40315. new PositionComponentResolutionLayerIterator(context);
  40316. break;
  40317. case 4:
  40318. tile.packetsIterator =
  40319. new ComponentPositionResolutionLayerIterator(context);
  40320. break;
  40321. default:
  40322. throw new Error('JPX Error: Unsupported progression order ' +
  40323. progressionOrder);
  40324. }
  40325. }
  40326. function parseTilePackets(context, data, offset, dataLength) {
  40327. var position = 0;
  40328. var buffer, bufferSize = 0, skipNextBit = false;
  40329. function readBits(count) {
  40330. while (bufferSize < count) {
  40331. var b = data[offset + position];
  40332. position++;
  40333. if (skipNextBit) {
  40334. buffer = (buffer << 7) | b;
  40335. bufferSize += 7;
  40336. skipNextBit = false;
  40337. } else {
  40338. buffer = (buffer << 8) | b;
  40339. bufferSize += 8;
  40340. }
  40341. if (b === 0xFF) {
  40342. skipNextBit = true;
  40343. }
  40344. }
  40345. bufferSize -= count;
  40346. return (buffer >>> bufferSize) & ((1 << count) - 1);
  40347. }
  40348. function skipMarkerIfEqual(value) {
  40349. if (data[offset + position - 1] === 0xFF &&
  40350. data[offset + position] === value) {
  40351. skipBytes(1);
  40352. return true;
  40353. } else if (data[offset + position] === 0xFF &&
  40354. data[offset + position + 1] === value) {
  40355. skipBytes(2);
  40356. return true;
  40357. }
  40358. return false;
  40359. }
  40360. function skipBytes(count) {
  40361. position += count;
  40362. }
  40363. function alignToByte() {
  40364. bufferSize = 0;
  40365. if (skipNextBit) {
  40366. position++;
  40367. skipNextBit = false;
  40368. }
  40369. }
  40370. function readCodingpasses() {
  40371. if (readBits(1) === 0) {
  40372. return 1;
  40373. }
  40374. if (readBits(1) === 0) {
  40375. return 2;
  40376. }
  40377. var value = readBits(2);
  40378. if (value < 3) {
  40379. return value + 3;
  40380. }
  40381. value = readBits(5);
  40382. if (value < 31) {
  40383. return value + 6;
  40384. }
  40385. value = readBits(7);
  40386. return value + 37;
  40387. }
  40388. var tileIndex = context.currentTile.index;
  40389. var tile = context.tiles[tileIndex];
  40390. var sopMarkerUsed = context.COD.sopMarkerUsed;
  40391. var ephMarkerUsed = context.COD.ephMarkerUsed;
  40392. var packetsIterator = tile.packetsIterator;
  40393. while (position < dataLength) {
  40394. alignToByte();
  40395. if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
  40396. // Skip also marker segment length and packet sequence ID
  40397. skipBytes(4);
  40398. }
  40399. var packet = packetsIterator.nextPacket();
  40400. if (!readBits(1)) {
  40401. continue;
  40402. }
  40403. var layerNumber = packet.layerNumber;
  40404. var queue = [], codeblock;
  40405. for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
  40406. codeblock = packet.codeblocks[i];
  40407. var precinct = codeblock.precinct;
  40408. var codeblockColumn = codeblock.cbx - precinct.cbxMin;
  40409. var codeblockRow = codeblock.cby - precinct.cbyMin;
  40410. var codeblockIncluded = false;
  40411. var firstTimeInclusion = false;
  40412. var valueReady;
  40413. if (codeblock['included'] !== undefined) {
  40414. codeblockIncluded = !!readBits(1);
  40415. } else {
  40416. // reading inclusion tree
  40417. precinct = codeblock.precinct;
  40418. var inclusionTree, zeroBitPlanesTree;
  40419. if (precinct['inclusionTree'] !== undefined) {
  40420. inclusionTree = precinct.inclusionTree;
  40421. } else {
  40422. // building inclusion and zero bit-planes trees
  40423. var width = precinct.cbxMax - precinct.cbxMin + 1;
  40424. var height = precinct.cbyMax - precinct.cbyMin + 1;
  40425. inclusionTree = new InclusionTree(width, height, layerNumber);
  40426. zeroBitPlanesTree = new TagTree(width, height);
  40427. precinct.inclusionTree = inclusionTree;
  40428. precinct.zeroBitPlanesTree = zeroBitPlanesTree;
  40429. }
  40430. if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
  40431. while (true) {
  40432. if (readBits(1)) {
  40433. valueReady = !inclusionTree.nextLevel();
  40434. if (valueReady) {
  40435. codeblock.included = true;
  40436. codeblockIncluded = firstTimeInclusion = true;
  40437. break;
  40438. }
  40439. } else {
  40440. inclusionTree.incrementValue(layerNumber);
  40441. break;
  40442. }
  40443. }
  40444. }
  40445. }
  40446. if (!codeblockIncluded) {
  40447. continue;
  40448. }
  40449. if (firstTimeInclusion) {
  40450. zeroBitPlanesTree = precinct.zeroBitPlanesTree;
  40451. zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
  40452. while (true) {
  40453. if (readBits(1)) {
  40454. valueReady = !zeroBitPlanesTree.nextLevel();
  40455. if (valueReady) {
  40456. break;
  40457. }
  40458. } else {
  40459. zeroBitPlanesTree.incrementValue();
  40460. }
  40461. }
  40462. codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
  40463. }
  40464. var codingpasses = readCodingpasses();
  40465. while (readBits(1)) {
  40466. codeblock.Lblock++;
  40467. }
  40468. var codingpassesLog2 = log2(codingpasses);
  40469. // rounding down log2
  40470. var bits = ((codingpasses < (1 << codingpassesLog2)) ?
  40471. codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
  40472. var codedDataLength = readBits(bits);
  40473. queue.push({
  40474. codeblock: codeblock,
  40475. codingpasses: codingpasses,
  40476. dataLength: codedDataLength
  40477. });
  40478. }
  40479. alignToByte();
  40480. if (ephMarkerUsed) {
  40481. skipMarkerIfEqual(0x92);
  40482. }
  40483. while (queue.length > 0) {
  40484. var packetItem = queue.shift();
  40485. codeblock = packetItem.codeblock;
  40486. if (codeblock['data'] === undefined) {
  40487. codeblock.data = [];
  40488. }
  40489. codeblock.data.push({
  40490. data: data,
  40491. start: offset + position,
  40492. end: offset + position + packetItem.dataLength,
  40493. codingpasses: packetItem.codingpasses
  40494. });
  40495. position += packetItem.dataLength;
  40496. }
  40497. }
  40498. return position;
  40499. }
  40500. function copyCoefficients(coefficients, levelWidth, levelHeight, subband,
  40501. delta, mb, reversible, segmentationSymbolUsed) {
  40502. var x0 = subband.tbx0;
  40503. var y0 = subband.tby0;
  40504. var width = subband.tbx1 - subband.tbx0;
  40505. var codeblocks = subband.codeblocks;
  40506. var right = subband.type.charAt(0) === 'H' ? 1 : 0;
  40507. var bottom = subband.type.charAt(1) === 'H' ? levelWidth : 0;
  40508. for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
  40509. var codeblock = codeblocks[i];
  40510. var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
  40511. var blockHeight = codeblock.tby1_ - codeblock.tby0_;
  40512. if (blockWidth === 0 || blockHeight === 0) {
  40513. continue;
  40514. }
  40515. if (codeblock['data'] === undefined) {
  40516. continue;
  40517. }
  40518. var bitModel, currentCodingpassType;
  40519. bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType,
  40520. codeblock.zeroBitPlanes, mb);
  40521. currentCodingpassType = 2; // first bit plane starts from cleanup
  40522. // collect data
  40523. var data = codeblock.data, totalLength = 0, codingpasses = 0;
  40524. var j, jj, dataItem;
  40525. for (j = 0, jj = data.length; j < jj; j++) {
  40526. dataItem = data[j];
  40527. totalLength += dataItem.end - dataItem.start;
  40528. codingpasses += dataItem.codingpasses;
  40529. }
  40530. var encodedData = new Uint8Array(totalLength);
  40531. var position = 0;
  40532. for (j = 0, jj = data.length; j < jj; j++) {
  40533. dataItem = data[j];
  40534. var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
  40535. encodedData.set(chunk, position);
  40536. position += chunk.length;
  40537. }
  40538. // decoding the item
  40539. var decoder = new ArithmeticDecoder(encodedData, 0, totalLength);
  40540. bitModel.setDecoder(decoder);
  40541. for (j = 0; j < codingpasses; j++) {
  40542. switch (currentCodingpassType) {
  40543. case 0:
  40544. bitModel.runSignificancePropogationPass();
  40545. break;
  40546. case 1:
  40547. bitModel.runMagnitudeRefinementPass();
  40548. break;
  40549. case 2:
  40550. bitModel.runCleanupPass();
  40551. if (segmentationSymbolUsed) {
  40552. bitModel.checkSegmentationSymbol();
  40553. }
  40554. break;
  40555. }
  40556. currentCodingpassType = (currentCodingpassType + 1) % 3;
  40557. }
  40558. var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width;
  40559. var sign = bitModel.coefficentsSign;
  40560. var magnitude = bitModel.coefficentsMagnitude;
  40561. var bitsDecoded = bitModel.bitsDecoded;
  40562. var magnitudeCorrection = reversible ? 0 : 0.5;
  40563. var k, n, nb;
  40564. position = 0;
  40565. // Do the interleaving of Section F.3.3 here, so we do not need
  40566. // to copy later. LL level is not interleaved, just copied.
  40567. var interleave = (subband.type !== 'LL');
  40568. for (j = 0; j < blockHeight; j++) {
  40569. var row = (offset / width) | 0; // row in the non-interleaved subband
  40570. var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
  40571. for (k = 0; k < blockWidth; k++) {
  40572. n = magnitude[position];
  40573. if (n !== 0) {
  40574. n = (n + magnitudeCorrection) * delta;
  40575. if (sign[position] !== 0) {
  40576. n = -n;
  40577. }
  40578. nb = bitsDecoded[position];
  40579. var pos = interleave ? (levelOffset + (offset << 1)) : offset;
  40580. if (reversible && (nb >= mb)) {
  40581. coefficients[pos] = n;
  40582. } else {
  40583. coefficients[pos] = n * (1 << (mb - nb));
  40584. }
  40585. }
  40586. offset++;
  40587. position++;
  40588. }
  40589. offset += width - blockWidth;
  40590. }
  40591. }
  40592. }
  40593. function transformTile(context, tile, c) {
  40594. var component = tile.components[c];
  40595. var codingStyleParameters = component.codingStyleParameters;
  40596. var quantizationParameters = component.quantizationParameters;
  40597. var decompositionLevelsCount =
  40598. codingStyleParameters.decompositionLevelsCount;
  40599. var spqcds = quantizationParameters.SPqcds;
  40600. var scalarExpounded = quantizationParameters.scalarExpounded;
  40601. var guardBits = quantizationParameters.guardBits;
  40602. var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
  40603. var precision = context.components[c].precision;
  40604. var reversible = codingStyleParameters.reversibleTransformation;
  40605. var transform = (reversible ? new ReversibleTransform() :
  40606. new IrreversibleTransform());
  40607. var subbandCoefficients = [];
  40608. var b = 0;
  40609. for (var i = 0; i <= decompositionLevelsCount; i++) {
  40610. var resolution = component.resolutions[i];
  40611. var width = resolution.trx1 - resolution.trx0;
  40612. var height = resolution.try1 - resolution.try0;
  40613. // Allocate space for the whole sublevel.
  40614. var coefficients = new Float32Array(width * height);
  40615. for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
  40616. var mu, epsilon;
  40617. if (!scalarExpounded) {
  40618. // formula E-5
  40619. mu = spqcds[0].mu;
  40620. epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
  40621. } else {
  40622. mu = spqcds[b].mu;
  40623. epsilon = spqcds[b].epsilon;
  40624. b++;
  40625. }
  40626. var subband = resolution.subbands[j];
  40627. var gainLog2 = SubbandsGainLog2[subband.type];
  40628. // calulate quantization coefficient (Section E.1.1.1)
  40629. var delta = (reversible ? 1 :
  40630. Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048));
  40631. var mb = (guardBits + epsilon - 1);
  40632. // In the first resolution level, copyCoefficients will fill the
  40633. // whole array with coefficients. In the succeding passes,
  40634. // copyCoefficients will consecutively fill in the values that belong
  40635. // to the interleaved positions of the HL, LH, and HH coefficients.
  40636. // The LL coefficients will then be interleaved in Transform.iterate().
  40637. copyCoefficients(coefficients, width, height, subband, delta, mb,
  40638. reversible, segmentationSymbolUsed);
  40639. }
  40640. subbandCoefficients.push({
  40641. width: width,
  40642. height: height,
  40643. items: coefficients
  40644. });
  40645. }
  40646. var result = transform.calculate(subbandCoefficients,
  40647. component.tcx0, component.tcy0);
  40648. return {
  40649. left: component.tcx0,
  40650. top: component.tcy0,
  40651. width: result.width,
  40652. height: result.height,
  40653. items: result.items
  40654. };
  40655. }
  40656. function transformComponents(context) {
  40657. var siz = context.SIZ;
  40658. var components = context.components;
  40659. var componentsCount = siz.Csiz;
  40660. var resultImages = [];
  40661. for (var i = 0, ii = context.tiles.length; i < ii; i++) {
  40662. var tile = context.tiles[i];
  40663. var transformedTiles = [];
  40664. var c;
  40665. for (c = 0; c < componentsCount; c++) {
  40666. transformedTiles[c] = transformTile(context, tile, c);
  40667. }
  40668. var tile0 = transformedTiles[0];
  40669. var out = new Uint8Array(tile0.items.length * componentsCount);
  40670. var result = {
  40671. left: tile0.left,
  40672. top: tile0.top,
  40673. width: tile0.width,
  40674. height: tile0.height,
  40675. items: out
  40676. };
  40677. // Section G.2.2 Inverse multi component transform
  40678. var shift, offset, max, min, maxK;
  40679. var pos = 0, j, jj, y0, y1, y2, r, g, b, k, val;
  40680. if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
  40681. var fourComponents = componentsCount === 4;
  40682. var y0items = transformedTiles[0].items;
  40683. var y1items = transformedTiles[1].items;
  40684. var y2items = transformedTiles[2].items;
  40685. var y3items = fourComponents ? transformedTiles[3].items : null;
  40686. // HACK: The multiple component transform formulas below assume that
  40687. // all components have the same precision. With this in mind, we
  40688. // compute shift and offset only once.
  40689. shift = components[0].precision - 8;
  40690. offset = (128 << shift) + 0.5;
  40691. max = 255 * (1 << shift);
  40692. maxK = max * 0.5;
  40693. min = -maxK;
  40694. var component0 = tile.components[0];
  40695. var alpha01 = componentsCount - 3;
  40696. jj = y0items.length;
  40697. if (!component0.codingStyleParameters.reversibleTransformation) {
  40698. // inverse irreversible multiple component transform
  40699. for (j = 0; j < jj; j++, pos += alpha01) {
  40700. y0 = y0items[j] + offset;
  40701. y1 = y1items[j];
  40702. y2 = y2items[j];
  40703. r = y0 + 1.402 * y2;
  40704. g = y0 - 0.34413 * y1 - 0.71414 * y2;
  40705. b = y0 + 1.772 * y1;
  40706. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  40707. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  40708. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  40709. }
  40710. } else {
  40711. // inverse reversible multiple component transform
  40712. for (j = 0; j < jj; j++, pos += alpha01) {
  40713. y0 = y0items[j] + offset;
  40714. y1 = y1items[j];
  40715. y2 = y2items[j];
  40716. g = y0 - ((y2 + y1) >> 2);
  40717. r = g + y2;
  40718. b = g + y1;
  40719. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  40720. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  40721. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  40722. }
  40723. }
  40724. if (fourComponents) {
  40725. for (j = 0, pos = 3; j < jj; j++, pos += 4) {
  40726. k = y3items[j];
  40727. out[pos] = k <= min ? 0 : k >= maxK ? 255 : (k + offset) >> shift;
  40728. }
  40729. }
  40730. } else { // no multi-component transform
  40731. for (c = 0; c < componentsCount; c++) {
  40732. var items = transformedTiles[c].items;
  40733. shift = components[c].precision - 8;
  40734. offset = (128 << shift) + 0.5;
  40735. max = (127.5 * (1 << shift));
  40736. min = -max;
  40737. for (pos = c, j = 0, jj = items.length; j < jj; j++) {
  40738. val = items[j];
  40739. out[pos] = val <= min ? 0 :
  40740. val >= max ? 255 : (val + offset) >> shift;
  40741. pos += componentsCount;
  40742. }
  40743. }
  40744. }
  40745. resultImages.push(result);
  40746. }
  40747. return resultImages;
  40748. }
  40749. function initializeTile(context, tileIndex) {
  40750. var siz = context.SIZ;
  40751. var componentsCount = siz.Csiz;
  40752. var tile = context.tiles[tileIndex];
  40753. for (var c = 0; c < componentsCount; c++) {
  40754. var component = tile.components[c];
  40755. var qcdOrQcc = (context.currentTile.QCC[c] !== undefined ?
  40756. context.currentTile.QCC[c] : context.currentTile.QCD);
  40757. component.quantizationParameters = qcdOrQcc;
  40758. var codOrCoc = (context.currentTile.COC[c] !== undefined ?
  40759. context.currentTile.COC[c] : context.currentTile.COD);
  40760. component.codingStyleParameters = codOrCoc;
  40761. }
  40762. tile.codingStyleDefaultParameters = context.currentTile.COD;
  40763. }
  40764. // Section B.10.2 Tag trees
  40765. var TagTree = (function TagTreeClosure() {
  40766. function TagTree(width, height) {
  40767. var levelsLength = log2(Math.max(width, height)) + 1;
  40768. this.levels = [];
  40769. for (var i = 0; i < levelsLength; i++) {
  40770. var level = {
  40771. width: width,
  40772. height: height,
  40773. items: []
  40774. };
  40775. this.levels.push(level);
  40776. width = Math.ceil(width / 2);
  40777. height = Math.ceil(height / 2);
  40778. }
  40779. }
  40780. TagTree.prototype = {
  40781. reset: function TagTree_reset(i, j) {
  40782. var currentLevel = 0, value = 0, level;
  40783. while (currentLevel < this.levels.length) {
  40784. level = this.levels[currentLevel];
  40785. var index = i + j * level.width;
  40786. if (level.items[index] !== undefined) {
  40787. value = level.items[index];
  40788. break;
  40789. }
  40790. level.index = index;
  40791. i >>= 1;
  40792. j >>= 1;
  40793. currentLevel++;
  40794. }
  40795. currentLevel--;
  40796. level = this.levels[currentLevel];
  40797. level.items[level.index] = value;
  40798. this.currentLevel = currentLevel;
  40799. delete this.value;
  40800. },
  40801. incrementValue: function TagTree_incrementValue() {
  40802. var level = this.levels[this.currentLevel];
  40803. level.items[level.index]++;
  40804. },
  40805. nextLevel: function TagTree_nextLevel() {
  40806. var currentLevel = this.currentLevel;
  40807. var level = this.levels[currentLevel];
  40808. var value = level.items[level.index];
  40809. currentLevel--;
  40810. if (currentLevel < 0) {
  40811. this.value = value;
  40812. return false;
  40813. }
  40814. this.currentLevel = currentLevel;
  40815. level = this.levels[currentLevel];
  40816. level.items[level.index] = value;
  40817. return true;
  40818. }
  40819. };
  40820. return TagTree;
  40821. })();
  40822. var InclusionTree = (function InclusionTreeClosure() {
  40823. function InclusionTree(width, height, defaultValue) {
  40824. var levelsLength = log2(Math.max(width, height)) + 1;
  40825. this.levels = [];
  40826. for (var i = 0; i < levelsLength; i++) {
  40827. var items = new Uint8Array(width * height);
  40828. for (var j = 0, jj = items.length; j < jj; j++) {
  40829. items[j] = defaultValue;
  40830. }
  40831. var level = {
  40832. width: width,
  40833. height: height,
  40834. items: items
  40835. };
  40836. this.levels.push(level);
  40837. width = Math.ceil(width / 2);
  40838. height = Math.ceil(height / 2);
  40839. }
  40840. }
  40841. InclusionTree.prototype = {
  40842. reset: function InclusionTree_reset(i, j, stopValue) {
  40843. var currentLevel = 0;
  40844. while (currentLevel < this.levels.length) {
  40845. var level = this.levels[currentLevel];
  40846. var index = i + j * level.width;
  40847. level.index = index;
  40848. var value = level.items[index];
  40849. if (value === 0xFF) {
  40850. break;
  40851. }
  40852. if (value > stopValue) {
  40853. this.currentLevel = currentLevel;
  40854. // already know about this one, propagating the value to top levels
  40855. this.propagateValues();
  40856. return false;
  40857. }
  40858. i >>= 1;
  40859. j >>= 1;
  40860. currentLevel++;
  40861. }
  40862. this.currentLevel = currentLevel - 1;
  40863. return true;
  40864. },
  40865. incrementValue: function InclusionTree_incrementValue(stopValue) {
  40866. var level = this.levels[this.currentLevel];
  40867. level.items[level.index] = stopValue + 1;
  40868. this.propagateValues();
  40869. },
  40870. propagateValues: function InclusionTree_propagateValues() {
  40871. var levelIndex = this.currentLevel;
  40872. var level = this.levels[levelIndex];
  40873. var currentValue = level.items[level.index];
  40874. while (--levelIndex >= 0) {
  40875. level = this.levels[levelIndex];
  40876. level.items[level.index] = currentValue;
  40877. }
  40878. },
  40879. nextLevel: function InclusionTree_nextLevel() {
  40880. var currentLevel = this.currentLevel;
  40881. var level = this.levels[currentLevel];
  40882. var value = level.items[level.index];
  40883. level.items[level.index] = 0xFF;
  40884. currentLevel--;
  40885. if (currentLevel < 0) {
  40886. return false;
  40887. }
  40888. this.currentLevel = currentLevel;
  40889. level = this.levels[currentLevel];
  40890. level.items[level.index] = value;
  40891. return true;
  40892. }
  40893. };
  40894. return InclusionTree;
  40895. })();
  40896. // Section D. Coefficient bit modeling
  40897. var BitModel = (function BitModelClosure() {
  40898. var UNIFORM_CONTEXT = 17;
  40899. var RUNLENGTH_CONTEXT = 18;
  40900. // Table D-1
  40901. // The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4),
  40902. // vv - sum of Vi (0..2), and hh - sum of Hi (0..2)
  40903. var LLAndLHContextsLabel = new Uint8Array([
  40904. 0, 5, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 1, 6, 8, 0, 3, 7, 8, 0, 4,
  40905. 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6,
  40906. 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8
  40907. ]);
  40908. var HLContextLabel = new Uint8Array([
  40909. 0, 3, 4, 0, 5, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 1, 3, 4, 0, 6, 7, 7, 0, 8,
  40910. 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3,
  40911. 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8
  40912. ]);
  40913. var HHContextLabel = new Uint8Array([
  40914. 0, 1, 2, 0, 1, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 3, 4, 5, 0, 4, 5, 5, 0, 5,
  40915. 5, 5, 0, 0, 0, 0, 0, 6, 7, 7, 0, 7, 7, 7, 0, 7, 7, 7, 0, 0, 0, 0, 0, 8, 8,
  40916. 8, 0, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8
  40917. ]);
  40918. function BitModel(width, height, subband, zeroBitPlanes, mb) {
  40919. this.width = width;
  40920. this.height = height;
  40921. this.contextLabelTable = (subband === 'HH' ? HHContextLabel :
  40922. (subband === 'HL' ? HLContextLabel : LLAndLHContextsLabel));
  40923. var coefficientCount = width * height;
  40924. // coefficients outside the encoding region treated as insignificant
  40925. // add border state cells for significanceState
  40926. this.neighborsSignificance = new Uint8Array(coefficientCount);
  40927. this.coefficentsSign = new Uint8Array(coefficientCount);
  40928. this.coefficentsMagnitude = mb > 14 ? new Uint32Array(coefficientCount) :
  40929. mb > 6 ? new Uint16Array(coefficientCount) :
  40930. new Uint8Array(coefficientCount);
  40931. this.processingFlags = new Uint8Array(coefficientCount);
  40932. var bitsDecoded = new Uint8Array(coefficientCount);
  40933. if (zeroBitPlanes !== 0) {
  40934. for (var i = 0; i < coefficientCount; i++) {
  40935. bitsDecoded[i] = zeroBitPlanes;
  40936. }
  40937. }
  40938. this.bitsDecoded = bitsDecoded;
  40939. this.reset();
  40940. }
  40941. BitModel.prototype = {
  40942. setDecoder: function BitModel_setDecoder(decoder) {
  40943. this.decoder = decoder;
  40944. },
  40945. reset: function BitModel_reset() {
  40946. // We have 17 contexts that are accessed via context labels,
  40947. // plus the uniform and runlength context.
  40948. this.contexts = new Int8Array(19);
  40949. // Contexts are packed into 1 byte:
  40950. // highest 7 bits carry the index, lowest bit carries mps
  40951. this.contexts[0] = (4 << 1) | 0;
  40952. this.contexts[UNIFORM_CONTEXT] = (46 << 1) | 0;
  40953. this.contexts[RUNLENGTH_CONTEXT] = (3 << 1) | 0;
  40954. },
  40955. setNeighborsSignificance:
  40956. function BitModel_setNeighborsSignificance(row, column, index) {
  40957. var neighborsSignificance = this.neighborsSignificance;
  40958. var width = this.width, height = this.height;
  40959. var left = (column > 0);
  40960. var right = (column + 1 < width);
  40961. var i;
  40962. if (row > 0) {
  40963. i = index - width;
  40964. if (left) {
  40965. neighborsSignificance[i - 1] += 0x10;
  40966. }
  40967. if (right) {
  40968. neighborsSignificance[i + 1] += 0x10;
  40969. }
  40970. neighborsSignificance[i] += 0x04;
  40971. }
  40972. if (row + 1 < height) {
  40973. i = index + width;
  40974. if (left) {
  40975. neighborsSignificance[i - 1] += 0x10;
  40976. }
  40977. if (right) {
  40978. neighborsSignificance[i + 1] += 0x10;
  40979. }
  40980. neighborsSignificance[i] += 0x04;
  40981. }
  40982. if (left) {
  40983. neighborsSignificance[index - 1] += 0x01;
  40984. }
  40985. if (right) {
  40986. neighborsSignificance[index + 1] += 0x01;
  40987. }
  40988. neighborsSignificance[index] |= 0x80;
  40989. },
  40990. runSignificancePropogationPass:
  40991. function BitModel_runSignificancePropogationPass() {
  40992. var decoder = this.decoder;
  40993. var width = this.width, height = this.height;
  40994. var coefficentsMagnitude = this.coefficentsMagnitude;
  40995. var coefficentsSign = this.coefficentsSign;
  40996. var neighborsSignificance = this.neighborsSignificance;
  40997. var processingFlags = this.processingFlags;
  40998. var contexts = this.contexts;
  40999. var labels = this.contextLabelTable;
  41000. var bitsDecoded = this.bitsDecoded;
  41001. var processedInverseMask = ~1;
  41002. var processedMask = 1;
  41003. var firstMagnitudeBitMask = 2;
  41004. for (var i0 = 0; i0 < height; i0 += 4) {
  41005. for (var j = 0; j < width; j++) {
  41006. var index = i0 * width + j;
  41007. for (var i1 = 0; i1 < 4; i1++, index += width) {
  41008. var i = i0 + i1;
  41009. if (i >= height) {
  41010. break;
  41011. }
  41012. // clear processed flag first
  41013. processingFlags[index] &= processedInverseMask;
  41014. if (coefficentsMagnitude[index] ||
  41015. !neighborsSignificance[index]) {
  41016. continue;
  41017. }
  41018. var contextLabel = labels[neighborsSignificance[index]];
  41019. var decision = decoder.readBit(contexts, contextLabel);
  41020. if (decision) {
  41021. var sign = this.decodeSignBit(i, j, index);
  41022. coefficentsSign[index] = sign;
  41023. coefficentsMagnitude[index] = 1;
  41024. this.setNeighborsSignificance(i, j, index);
  41025. processingFlags[index] |= firstMagnitudeBitMask;
  41026. }
  41027. bitsDecoded[index]++;
  41028. processingFlags[index] |= processedMask;
  41029. }
  41030. }
  41031. }
  41032. },
  41033. decodeSignBit: function BitModel_decodeSignBit(row, column, index) {
  41034. var width = this.width, height = this.height;
  41035. var coefficentsMagnitude = this.coefficentsMagnitude;
  41036. var coefficentsSign = this.coefficentsSign;
  41037. var contribution, sign0, sign1, significance1;
  41038. var contextLabel, decoded;
  41039. // calculate horizontal contribution
  41040. significance1 = (column > 0 && coefficentsMagnitude[index - 1] !== 0);
  41041. if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
  41042. sign1 = coefficentsSign[index + 1];
  41043. if (significance1) {
  41044. sign0 = coefficentsSign[index - 1];
  41045. contribution = 1 - sign1 - sign0;
  41046. } else {
  41047. contribution = 1 - sign1 - sign1;
  41048. }
  41049. } else if (significance1) {
  41050. sign0 = coefficentsSign[index - 1];
  41051. contribution = 1 - sign0 - sign0;
  41052. } else {
  41053. contribution = 0;
  41054. }
  41055. var horizontalContribution = 3 * contribution;
  41056. // calculate vertical contribution and combine with the horizontal
  41057. significance1 = (row > 0 && coefficentsMagnitude[index - width] !== 0);
  41058. if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
  41059. sign1 = coefficentsSign[index + width];
  41060. if (significance1) {
  41061. sign0 = coefficentsSign[index - width];
  41062. contribution = 1 - sign1 - sign0 + horizontalContribution;
  41063. } else {
  41064. contribution = 1 - sign1 - sign1 + horizontalContribution;
  41065. }
  41066. } else if (significance1) {
  41067. sign0 = coefficentsSign[index - width];
  41068. contribution = 1 - sign0 - sign0 + horizontalContribution;
  41069. } else {
  41070. contribution = horizontalContribution;
  41071. }
  41072. if (contribution >= 0) {
  41073. contextLabel = 9 + contribution;
  41074. decoded = this.decoder.readBit(this.contexts, contextLabel);
  41075. } else {
  41076. contextLabel = 9 - contribution;
  41077. decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
  41078. }
  41079. return decoded;
  41080. },
  41081. runMagnitudeRefinementPass:
  41082. function BitModel_runMagnitudeRefinementPass() {
  41083. var decoder = this.decoder;
  41084. var width = this.width, height = this.height;
  41085. var coefficentsMagnitude = this.coefficentsMagnitude;
  41086. var neighborsSignificance = this.neighborsSignificance;
  41087. var contexts = this.contexts;
  41088. var bitsDecoded = this.bitsDecoded;
  41089. var processingFlags = this.processingFlags;
  41090. var processedMask = 1;
  41091. var firstMagnitudeBitMask = 2;
  41092. var length = width * height;
  41093. var width4 = width * 4;
  41094. for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {
  41095. indexNext = Math.min(length, index0 + width4);
  41096. for (var j = 0; j < width; j++) {
  41097. for (var index = index0 + j; index < indexNext; index += width) {
  41098. // significant but not those that have just become
  41099. if (!coefficentsMagnitude[index] ||
  41100. (processingFlags[index] & processedMask) !== 0) {
  41101. continue;
  41102. }
  41103. var contextLabel = 16;
  41104. if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
  41105. processingFlags[index] ^= firstMagnitudeBitMask;
  41106. // first refinement
  41107. var significance = neighborsSignificance[index] & 127;
  41108. contextLabel = significance === 0 ? 15 : 14;
  41109. }
  41110. var bit = decoder.readBit(contexts, contextLabel);
  41111. coefficentsMagnitude[index] =
  41112. (coefficentsMagnitude[index] << 1) | bit;
  41113. bitsDecoded[index]++;
  41114. processingFlags[index] |= processedMask;
  41115. }
  41116. }
  41117. }
  41118. },
  41119. runCleanupPass: function BitModel_runCleanupPass() {
  41120. var decoder = this.decoder;
  41121. var width = this.width, height = this.height;
  41122. var neighborsSignificance = this.neighborsSignificance;
  41123. var coefficentsMagnitude = this.coefficentsMagnitude;
  41124. var coefficentsSign = this.coefficentsSign;
  41125. var contexts = this.contexts;
  41126. var labels = this.contextLabelTable;
  41127. var bitsDecoded = this.bitsDecoded;
  41128. var processingFlags = this.processingFlags;
  41129. var processedMask = 1;
  41130. var firstMagnitudeBitMask = 2;
  41131. var oneRowDown = width;
  41132. var twoRowsDown = width * 2;
  41133. var threeRowsDown = width * 3;
  41134. var iNext;
  41135. for (var i0 = 0; i0 < height; i0 = iNext) {
  41136. iNext = Math.min(i0 + 4, height);
  41137. var indexBase = i0 * width;
  41138. var checkAllEmpty = i0 + 3 < height;
  41139. for (var j = 0; j < width; j++) {
  41140. var index0 = indexBase + j;
  41141. // using the property: labels[neighborsSignificance[index]] === 0
  41142. // when neighborsSignificance[index] === 0
  41143. var allEmpty = (checkAllEmpty &&
  41144. processingFlags[index0] === 0 &&
  41145. processingFlags[index0 + oneRowDown] === 0 &&
  41146. processingFlags[index0 + twoRowsDown] === 0 &&
  41147. processingFlags[index0 + threeRowsDown] === 0 &&
  41148. neighborsSignificance[index0] === 0 &&
  41149. neighborsSignificance[index0 + oneRowDown] === 0 &&
  41150. neighborsSignificance[index0 + twoRowsDown] === 0 &&
  41151. neighborsSignificance[index0 + threeRowsDown] === 0);
  41152. var i1 = 0, index = index0;
  41153. var i = i0, sign;
  41154. if (allEmpty) {
  41155. var hasSignificantCoefficent =
  41156. decoder.readBit(contexts, RUNLENGTH_CONTEXT);
  41157. if (!hasSignificantCoefficent) {
  41158. bitsDecoded[index0]++;
  41159. bitsDecoded[index0 + oneRowDown]++;
  41160. bitsDecoded[index0 + twoRowsDown]++;
  41161. bitsDecoded[index0 + threeRowsDown]++;
  41162. continue; // next column
  41163. }
  41164. i1 = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
  41165. decoder.readBit(contexts, UNIFORM_CONTEXT);
  41166. if (i1 !== 0) {
  41167. i = i0 + i1;
  41168. index += i1 * width;
  41169. }
  41170. sign = this.decodeSignBit(i, j, index);
  41171. coefficentsSign[index] = sign;
  41172. coefficentsMagnitude[index] = 1;
  41173. this.setNeighborsSignificance(i, j, index);
  41174. processingFlags[index] |= firstMagnitudeBitMask;
  41175. index = index0;
  41176. for (var i2 = i0; i2 <= i; i2++, index += width) {
  41177. bitsDecoded[index]++;
  41178. }
  41179. i1++;
  41180. }
  41181. for (i = i0 + i1; i < iNext; i++, index += width) {
  41182. if (coefficentsMagnitude[index] ||
  41183. (processingFlags[index] & processedMask) !== 0) {
  41184. continue;
  41185. }
  41186. var contextLabel = labels[neighborsSignificance[index]];
  41187. var decision = decoder.readBit(contexts, contextLabel);
  41188. if (decision === 1) {
  41189. sign = this.decodeSignBit(i, j, index);
  41190. coefficentsSign[index] = sign;
  41191. coefficentsMagnitude[index] = 1;
  41192. this.setNeighborsSignificance(i, j, index);
  41193. processingFlags[index] |= firstMagnitudeBitMask;
  41194. }
  41195. bitsDecoded[index]++;
  41196. }
  41197. }
  41198. }
  41199. },
  41200. checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {
  41201. var decoder = this.decoder;
  41202. var contexts = this.contexts;
  41203. var symbol = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 3) |
  41204. (decoder.readBit(contexts, UNIFORM_CONTEXT) << 2) |
  41205. (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
  41206. decoder.readBit(contexts, UNIFORM_CONTEXT);
  41207. if (symbol !== 0xA) {
  41208. throw new Error('JPX Error: Invalid segmentation symbol');
  41209. }
  41210. }
  41211. };
  41212. return BitModel;
  41213. })();
  41214. // Section F, Discrete wavelet transformation
  41215. var Transform = (function TransformClosure() {
  41216. function Transform() {}
  41217. Transform.prototype.calculate =
  41218. function transformCalculate(subbands, u0, v0) {
  41219. var ll = subbands[0];
  41220. for (var i = 1, ii = subbands.length; i < ii; i++) {
  41221. ll = this.iterate(ll, subbands[i], u0, v0);
  41222. }
  41223. return ll;
  41224. };
  41225. Transform.prototype.extend = function extend(buffer, offset, size) {
  41226. // Section F.3.7 extending... using max extension of 4
  41227. var i1 = offset - 1, j1 = offset + 1;
  41228. var i2 = offset + size - 2, j2 = offset + size;
  41229. buffer[i1--] = buffer[j1++];
  41230. buffer[j2++] = buffer[i2--];
  41231. buffer[i1--] = buffer[j1++];
  41232. buffer[j2++] = buffer[i2--];
  41233. buffer[i1--] = buffer[j1++];
  41234. buffer[j2++] = buffer[i2--];
  41235. buffer[i1] = buffer[j1];
  41236. buffer[j2] = buffer[i2];
  41237. };
  41238. Transform.prototype.iterate = function Transform_iterate(ll, hl_lh_hh,
  41239. u0, v0) {
  41240. var llWidth = ll.width, llHeight = ll.height, llItems = ll.items;
  41241. var width = hl_lh_hh.width;
  41242. var height = hl_lh_hh.height;
  41243. var items = hl_lh_hh.items;
  41244. var i, j, k, l, u, v;
  41245. // Interleave LL according to Section F.3.3
  41246. for (k = 0, i = 0; i < llHeight; i++) {
  41247. l = i * 2 * width;
  41248. for (j = 0; j < llWidth; j++, k++, l += 2) {
  41249. items[l] = llItems[k];
  41250. }
  41251. }
  41252. // The LL band is not needed anymore.
  41253. llItems = ll.items = null;
  41254. var bufferPadding = 4;
  41255. var rowBuffer = new Float32Array(width + 2 * bufferPadding);
  41256. // Section F.3.4 HOR_SR
  41257. if (width === 1) {
  41258. // if width = 1, when u0 even keep items as is, when odd divide by 2
  41259. if ((u0 & 1) !== 0) {
  41260. for (v = 0, k = 0; v < height; v++, k += width) {
  41261. items[k] *= 0.5;
  41262. }
  41263. }
  41264. } else {
  41265. for (v = 0, k = 0; v < height; v++, k += width) {
  41266. rowBuffer.set(items.subarray(k, k + width), bufferPadding);
  41267. this.extend(rowBuffer, bufferPadding, width);
  41268. this.filter(rowBuffer, bufferPadding, width);
  41269. items.set(
  41270. rowBuffer.subarray(bufferPadding, bufferPadding + width),
  41271. k);
  41272. }
  41273. }
  41274. // Accesses to the items array can take long, because it may not fit into
  41275. // CPU cache and has to be fetched from main memory. Since subsequent
  41276. // accesses to the items array are not local when reading columns, we
  41277. // have a cache miss every time. To reduce cache misses, get up to
  41278. // 'numBuffers' items at a time and store them into the individual
  41279. // buffers. The colBuffers should be small enough to fit into CPU cache.
  41280. var numBuffers = 16;
  41281. var colBuffers = [];
  41282. for (i = 0; i < numBuffers; i++) {
  41283. colBuffers.push(new Float32Array(height + 2 * bufferPadding));
  41284. }
  41285. var b, currentBuffer = 0;
  41286. ll = bufferPadding + height;
  41287. // Section F.3.5 VER_SR
  41288. if (height === 1) {
  41289. // if height = 1, when v0 even keep items as is, when odd divide by 2
  41290. if ((v0 & 1) !== 0) {
  41291. for (u = 0; u < width; u++) {
  41292. items[u] *= 0.5;
  41293. }
  41294. }
  41295. } else {
  41296. for (u = 0; u < width; u++) {
  41297. // if we ran out of buffers, copy several image columns at once
  41298. if (currentBuffer === 0) {
  41299. numBuffers = Math.min(width - u, numBuffers);
  41300. for (k = u, l = bufferPadding; l < ll; k += width, l++) {
  41301. for (b = 0; b < numBuffers; b++) {
  41302. colBuffers[b][l] = items[k + b];
  41303. }
  41304. }
  41305. currentBuffer = numBuffers;
  41306. }
  41307. currentBuffer--;
  41308. var buffer = colBuffers[currentBuffer];
  41309. this.extend(buffer, bufferPadding, height);
  41310. this.filter(buffer, bufferPadding, height);
  41311. // If this is last buffer in this group of buffers, flush all buffers.
  41312. if (currentBuffer === 0) {
  41313. k = u - numBuffers + 1;
  41314. for (l = bufferPadding; l < ll; k += width, l++) {
  41315. for (b = 0; b < numBuffers; b++) {
  41316. items[k + b] = colBuffers[b][l];
  41317. }
  41318. }
  41319. }
  41320. }
  41321. }
  41322. return {
  41323. width: width,
  41324. height: height,
  41325. items: items
  41326. };
  41327. };
  41328. return Transform;
  41329. })();
  41330. // Section 3.8.2 Irreversible 9-7 filter
  41331. var IrreversibleTransform = (function IrreversibleTransformClosure() {
  41332. function IrreversibleTransform() {
  41333. Transform.call(this);
  41334. }
  41335. IrreversibleTransform.prototype = Object.create(Transform.prototype);
  41336. IrreversibleTransform.prototype.filter =
  41337. function irreversibleTransformFilter(x, offset, length) {
  41338. var len = length >> 1;
  41339. offset = offset | 0;
  41340. var j, n, current, next;
  41341. var alpha = -1.586134342059924;
  41342. var beta = -0.052980118572961;
  41343. var gamma = 0.882911075530934;
  41344. var delta = 0.443506852043971;
  41345. var K = 1.230174104914001;
  41346. var K_ = 1 / K;
  41347. // step 1 is combined with step 3
  41348. // step 2
  41349. j = offset - 3;
  41350. for (n = len + 4; n--; j += 2) {
  41351. x[j] *= K_;
  41352. }
  41353. // step 1 & 3
  41354. j = offset - 2;
  41355. current = delta * x[j -1];
  41356. for (n = len + 3; n--; j += 2) {
  41357. next = delta * x[j + 1];
  41358. x[j] = K * x[j] - current - next;
  41359. if (n--) {
  41360. j += 2;
  41361. current = delta * x[j + 1];
  41362. x[j] = K * x[j] - current - next;
  41363. } else {
  41364. break;
  41365. }
  41366. }
  41367. // step 4
  41368. j = offset - 1;
  41369. current = gamma * x[j - 1];
  41370. for (n = len + 2; n--; j += 2) {
  41371. next = gamma * x[j + 1];
  41372. x[j] -= current + next;
  41373. if (n--) {
  41374. j += 2;
  41375. current = gamma * x[j + 1];
  41376. x[j] -= current + next;
  41377. } else {
  41378. break;
  41379. }
  41380. }
  41381. // step 5
  41382. j = offset;
  41383. current = beta * x[j - 1];
  41384. for (n = len + 1; n--; j += 2) {
  41385. next = beta * x[j + 1];
  41386. x[j] -= current + next;
  41387. if (n--) {
  41388. j += 2;
  41389. current = beta * x[j + 1];
  41390. x[j] -= current + next;
  41391. } else {
  41392. break;
  41393. }
  41394. }
  41395. // step 6
  41396. if (len !== 0) {
  41397. j = offset + 1;
  41398. current = alpha * x[j - 1];
  41399. for (n = len; n--; j += 2) {
  41400. next = alpha * x[j + 1];
  41401. x[j] -= current + next;
  41402. if (n--) {
  41403. j += 2;
  41404. current = alpha * x[j + 1];
  41405. x[j] -= current + next;
  41406. } else {
  41407. break;
  41408. }
  41409. }
  41410. }
  41411. };
  41412. return IrreversibleTransform;
  41413. })();
  41414. // Section 3.8.1 Reversible 5-3 filter
  41415. var ReversibleTransform = (function ReversibleTransformClosure() {
  41416. function ReversibleTransform() {
  41417. Transform.call(this);
  41418. }
  41419. ReversibleTransform.prototype = Object.create(Transform.prototype);
  41420. ReversibleTransform.prototype.filter =
  41421. function reversibleTransformFilter(x, offset, length) {
  41422. var len = length >> 1;
  41423. offset = offset | 0;
  41424. var j, n;
  41425. for (j = offset, n = len + 1; n--; j += 2) {
  41426. x[j] -= (x[j - 1] + x[j + 1] + 2) >> 2;
  41427. }
  41428. for (j = offset + 1, n = len; n--; j += 2) {
  41429. x[j] += (x[j - 1] + x[j + 1]) >> 1;
  41430. }
  41431. };
  41432. return ReversibleTransform;
  41433. })();
  41434. return JpxImage;
  41435. })();
  41436. var Jbig2Image = (function Jbig2ImageClosure() {
  41437. // Utility data structures
  41438. function ContextCache() {}
  41439. ContextCache.prototype = {
  41440. getContexts: function(id) {
  41441. if (id in this) {
  41442. return this[id];
  41443. }
  41444. return (this[id] = new Int8Array(1 << 16));
  41445. }
  41446. };
  41447. function DecodingContext(data, start, end) {
  41448. this.data = data;
  41449. this.start = start;
  41450. this.end = end;
  41451. }
  41452. DecodingContext.prototype = {
  41453. get decoder() {
  41454. var decoder = new ArithmeticDecoder(this.data, this.start, this.end);
  41455. return shadow(this, 'decoder', decoder);
  41456. },
  41457. get contextCache() {
  41458. var cache = new ContextCache();
  41459. return shadow(this, 'contextCache', cache);
  41460. }
  41461. };
  41462. // Annex A. Arithmetic Integer Decoding Procedure
  41463. // A.2 Procedure for decoding values
  41464. function decodeInteger(contextCache, procedure, decoder) {
  41465. var contexts = contextCache.getContexts(procedure);
  41466. var prev = 1;
  41467. function readBits(length) {
  41468. var v = 0;
  41469. for (var i = 0; i < length; i++) {
  41470. var bit = decoder.readBit(contexts, prev);
  41471. prev = (prev < 256 ? (prev << 1) | bit :
  41472. (((prev << 1) | bit) & 511) | 256);
  41473. v = (v << 1) | bit;
  41474. }
  41475. return v >>> 0;
  41476. }
  41477. var sign = readBits(1);
  41478. var value = readBits(1) ?
  41479. (readBits(1) ?
  41480. (readBits(1) ?
  41481. (readBits(1) ?
  41482. (readBits(1) ?
  41483. (readBits(32) + 4436) :
  41484. readBits(12) + 340) :
  41485. readBits(8) + 84) :
  41486. readBits(6) + 20) :
  41487. readBits(4) + 4) :
  41488. readBits(2);
  41489. return (sign === 0 ? value : (value > 0 ? -value : null));
  41490. }
  41491. // A.3 The IAID decoding procedure
  41492. function decodeIAID(contextCache, decoder, codeLength) {
  41493. var contexts = contextCache.getContexts('IAID');
  41494. var prev = 1;
  41495. for (var i = 0; i < codeLength; i++) {
  41496. var bit = decoder.readBit(contexts, prev);
  41497. prev = (prev << 1) | bit;
  41498. }
  41499. if (codeLength < 31) {
  41500. return prev & ((1 << codeLength) - 1);
  41501. }
  41502. return prev & 0x7FFFFFFF;
  41503. }
  41504. // 7.3 Segment types
  41505. var SegmentTypes = [
  41506. 'SymbolDictionary', null, null, null, 'IntermediateTextRegion', null,
  41507. 'ImmediateTextRegion', 'ImmediateLosslessTextRegion', null, null, null,
  41508. null, null, null, null, null, 'patternDictionary', null, null, null,
  41509. 'IntermediateHalftoneRegion', null, 'ImmediateHalftoneRegion',
  41510. 'ImmediateLosslessHalftoneRegion', null, null, null, null, null, null, null,
  41511. null, null, null, null, null, 'IntermediateGenericRegion', null,
  41512. 'ImmediateGenericRegion', 'ImmediateLosslessGenericRegion',
  41513. 'IntermediateGenericRefinementRegion', null,
  41514. 'ImmediateGenericRefinementRegion',
  41515. 'ImmediateLosslessGenericRefinementRegion', null, null, null, null,
  41516. 'PageInformation', 'EndOfPage', 'EndOfStripe', 'EndOfFile', 'Profiles',
  41517. 'Tables', null, null, null, null, null, null, null, null,
  41518. 'Extension'
  41519. ];
  41520. var CodingTemplates = [
  41521. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: -2, y: -1},
  41522. {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: 2, y: -1},
  41523. {x: -4, y: 0}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}],
  41524. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: 2, y: -2},
  41525. {x: -2, y: -1}, {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1},
  41526. {x: 2, y: -1}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}],
  41527. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: -2, y: -1},
  41528. {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: -2, y: 0},
  41529. {x: -1, y: 0}],
  41530. [{x: -3, y: -1}, {x: -2, y: -1}, {x: -1, y: -1}, {x: 0, y: -1},
  41531. {x: 1, y: -1}, {x: -4, y: 0}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}]
  41532. ];
  41533. var RefinementTemplates = [
  41534. {
  41535. coding: [{x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}],
  41536. reference: [{x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}, {x: 0, y: 0},
  41537. {x: 1, y: 0}, {x: -1, y: 1}, {x: 0, y: 1}, {x: 1, y: 1}]
  41538. },
  41539. {
  41540. coding: [{x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}],
  41541. reference: [{x: 0, y: -1}, {x: -1, y: 0}, {x: 0, y: 0}, {x: 1, y: 0},
  41542. {x: 0, y: 1}, {x: 1, y: 1}]
  41543. }
  41544. ];
  41545. // See 6.2.5.7 Decoding the bitmap.
  41546. var ReusedContexts = [
  41547. 0x9B25, // 10011 0110010 0101
  41548. 0x0795, // 0011 110010 101
  41549. 0x00E5, // 001 11001 01
  41550. 0x0195 // 011001 0101
  41551. ];
  41552. var RefinementReusedContexts = [
  41553. 0x0020, // '000' + '0' (coding) + '00010000' + '0' (reference)
  41554. 0x0008 // '0000' + '001000'
  41555. ];
  41556. function decodeBitmapTemplate0(width, height, decodingContext) {
  41557. var decoder = decodingContext.decoder;
  41558. var contexts = decodingContext.contextCache.getContexts('GB');
  41559. var contextLabel, i, j, pixel, row, row1, row2, bitmap = [];
  41560. // ...ooooo....
  41561. // ..ooooooo... Context template for current pixel (X)
  41562. // .ooooX...... (concatenate values of 'o'-pixels to get contextLabel)
  41563. var OLD_PIXEL_MASK = 0x7BF7; // 01111 0111111 0111
  41564. for (i = 0; i < height; i++) {
  41565. row = bitmap[i] = new Uint8Array(width);
  41566. row1 = (i < 1) ? row : bitmap[i - 1];
  41567. row2 = (i < 2) ? row : bitmap[i - 2];
  41568. // At the beginning of each row:
  41569. // Fill contextLabel with pixels that are above/right of (X)
  41570. contextLabel = (row2[0] << 13) | (row2[1] << 12) | (row2[2] << 11) |
  41571. (row1[0] << 7) | (row1[1] << 6) | (row1[2] << 5) |
  41572. (row1[3] << 4);
  41573. for (j = 0; j < width; j++) {
  41574. row[j] = pixel = decoder.readBit(contexts, contextLabel);
  41575. // At each pixel: Clear contextLabel pixels that are shifted
  41576. // out of the context, then add new ones.
  41577. contextLabel = ((contextLabel & OLD_PIXEL_MASK) << 1) |
  41578. (j + 3 < width ? row2[j + 3] << 11 : 0) |
  41579. (j + 4 < width ? row1[j + 4] << 4 : 0) | pixel;
  41580. }
  41581. }
  41582. return bitmap;
  41583. }
  41584. // 6.2 Generic Region Decoding Procedure
  41585. function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at,
  41586. decodingContext) {
  41587. if (mmr) {
  41588. error('JBIG2 error: MMR encoding is not supported');
  41589. }
  41590. // Use optimized version for the most common case
  41591. if (templateIndex === 0 && !skip && !prediction && at.length === 4 &&
  41592. at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 &&
  41593. at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) {
  41594. return decodeBitmapTemplate0(width, height, decodingContext);
  41595. }
  41596. var useskip = !!skip;
  41597. var template = CodingTemplates[templateIndex].concat(at);
  41598. // Sorting is non-standard, and it is not required. But sorting increases
  41599. // the number of template bits that can be reused from the previous
  41600. // contextLabel in the main loop.
  41601. template.sort(function (a, b) {
  41602. return (a.y - b.y) || (a.x - b.x);
  41603. });
  41604. var templateLength = template.length;
  41605. var templateX = new Int8Array(templateLength);
  41606. var templateY = new Int8Array(templateLength);
  41607. var changingTemplateEntries = [];
  41608. var reuseMask = 0, minX = 0, maxX = 0, minY = 0;
  41609. var c, k;
  41610. for (k = 0; k < templateLength; k++) {
  41611. templateX[k] = template[k].x;
  41612. templateY[k] = template[k].y;
  41613. minX = Math.min(minX, template[k].x);
  41614. maxX = Math.max(maxX, template[k].x);
  41615. minY = Math.min(minY, template[k].y);
  41616. // Check if the template pixel appears in two consecutive context labels,
  41617. // so it can be reused. Otherwise, we add it to the list of changing
  41618. // template entries.
  41619. if (k < templateLength - 1 &&
  41620. template[k].y === template[k + 1].y &&
  41621. template[k].x === template[k + 1].x - 1) {
  41622. reuseMask |= 1 << (templateLength - 1 - k);
  41623. } else {
  41624. changingTemplateEntries.push(k);
  41625. }
  41626. }
  41627. var changingEntriesLength = changingTemplateEntries.length;
  41628. var changingTemplateX = new Int8Array(changingEntriesLength);
  41629. var changingTemplateY = new Int8Array(changingEntriesLength);
  41630. var changingTemplateBit = new Uint16Array(changingEntriesLength);
  41631. for (c = 0; c < changingEntriesLength; c++) {
  41632. k = changingTemplateEntries[c];
  41633. changingTemplateX[c] = template[k].x;
  41634. changingTemplateY[c] = template[k].y;
  41635. changingTemplateBit[c] = 1 << (templateLength - 1 - k);
  41636. }
  41637. // Get the safe bounding box edges from the width, height, minX, maxX, minY
  41638. var sbb_left = -minX;
  41639. var sbb_top = -minY;
  41640. var sbb_right = width - maxX;
  41641. var pseudoPixelContext = ReusedContexts[templateIndex];
  41642. var row = new Uint8Array(width);
  41643. var bitmap = [];
  41644. var decoder = decodingContext.decoder;
  41645. var contexts = decodingContext.contextCache.getContexts('GB');
  41646. var ltp = 0, j, i0, j0, contextLabel = 0, bit, shift;
  41647. for (var i = 0; i < height; i++) {
  41648. if (prediction) {
  41649. var sltp = decoder.readBit(contexts, pseudoPixelContext);
  41650. ltp ^= sltp;
  41651. if (ltp) {
  41652. bitmap.push(row); // duplicate previous row
  41653. continue;
  41654. }
  41655. }
  41656. row = new Uint8Array(row);
  41657. bitmap.push(row);
  41658. for (j = 0; j < width; j++) {
  41659. if (useskip && skip[i][j]) {
  41660. row[j] = 0;
  41661. continue;
  41662. }
  41663. // Are we in the middle of a scanline, so we can reuse contextLabel
  41664. // bits?
  41665. if (j >= sbb_left && j < sbb_right && i >= sbb_top) {
  41666. // If yes, we can just shift the bits that are reusable and only
  41667. // fetch the remaining ones.
  41668. contextLabel = (contextLabel << 1) & reuseMask;
  41669. for (k = 0; k < changingEntriesLength; k++) {
  41670. i0 = i + changingTemplateY[k];
  41671. j0 = j + changingTemplateX[k];
  41672. bit = bitmap[i0][j0];
  41673. if (bit) {
  41674. bit = changingTemplateBit[k];
  41675. contextLabel |= bit;
  41676. }
  41677. }
  41678. } else {
  41679. // compute the contextLabel from scratch
  41680. contextLabel = 0;
  41681. shift = templateLength - 1;
  41682. for (k = 0; k < templateLength; k++, shift--) {
  41683. j0 = j + templateX[k];
  41684. if (j0 >= 0 && j0 < width) {
  41685. i0 = i + templateY[k];
  41686. if (i0 >= 0) {
  41687. bit = bitmap[i0][j0];
  41688. if (bit) {
  41689. contextLabel |= bit << shift;
  41690. }
  41691. }
  41692. }
  41693. }
  41694. }
  41695. var pixel = decoder.readBit(contexts, contextLabel);
  41696. row[j] = pixel;
  41697. }
  41698. }
  41699. return bitmap;
  41700. }
  41701. // 6.3.2 Generic Refinement Region Decoding Procedure
  41702. function decodeRefinement(width, height, templateIndex, referenceBitmap,
  41703. offsetX, offsetY, prediction, at,
  41704. decodingContext) {
  41705. var codingTemplate = RefinementTemplates[templateIndex].coding;
  41706. if (templateIndex === 0) {
  41707. codingTemplate = codingTemplate.concat([at[0]]);
  41708. }
  41709. var codingTemplateLength = codingTemplate.length;
  41710. var codingTemplateX = new Int32Array(codingTemplateLength);
  41711. var codingTemplateY = new Int32Array(codingTemplateLength);
  41712. var k;
  41713. for (k = 0; k < codingTemplateLength; k++) {
  41714. codingTemplateX[k] = codingTemplate[k].x;
  41715. codingTemplateY[k] = codingTemplate[k].y;
  41716. }
  41717. var referenceTemplate = RefinementTemplates[templateIndex].reference;
  41718. if (templateIndex === 0) {
  41719. referenceTemplate = referenceTemplate.concat([at[1]]);
  41720. }
  41721. var referenceTemplateLength = referenceTemplate.length;
  41722. var referenceTemplateX = new Int32Array(referenceTemplateLength);
  41723. var referenceTemplateY = new Int32Array(referenceTemplateLength);
  41724. for (k = 0; k < referenceTemplateLength; k++) {
  41725. referenceTemplateX[k] = referenceTemplate[k].x;
  41726. referenceTemplateY[k] = referenceTemplate[k].y;
  41727. }
  41728. var referenceWidth = referenceBitmap[0].length;
  41729. var referenceHeight = referenceBitmap.length;
  41730. var pseudoPixelContext = RefinementReusedContexts[templateIndex];
  41731. var bitmap = [];
  41732. var decoder = decodingContext.decoder;
  41733. var contexts = decodingContext.contextCache.getContexts('GR');
  41734. var ltp = 0;
  41735. for (var i = 0; i < height; i++) {
  41736. if (prediction) {
  41737. var sltp = decoder.readBit(contexts, pseudoPixelContext);
  41738. ltp ^= sltp;
  41739. if (ltp) {
  41740. error('JBIG2 error: prediction is not supported');
  41741. }
  41742. }
  41743. var row = new Uint8Array(width);
  41744. bitmap.push(row);
  41745. for (var j = 0; j < width; j++) {
  41746. var i0, j0;
  41747. var contextLabel = 0;
  41748. for (k = 0; k < codingTemplateLength; k++) {
  41749. i0 = i + codingTemplateY[k];
  41750. j0 = j + codingTemplateX[k];
  41751. if (i0 < 0 || j0 < 0 || j0 >= width) {
  41752. contextLabel <<= 1; // out of bound pixel
  41753. } else {
  41754. contextLabel = (contextLabel << 1) | bitmap[i0][j0];
  41755. }
  41756. }
  41757. for (k = 0; k < referenceTemplateLength; k++) {
  41758. i0 = i + referenceTemplateY[k] + offsetY;
  41759. j0 = j + referenceTemplateX[k] + offsetX;
  41760. if (i0 < 0 || i0 >= referenceHeight || j0 < 0 ||
  41761. j0 >= referenceWidth) {
  41762. contextLabel <<= 1; // out of bound pixel
  41763. } else {
  41764. contextLabel = (contextLabel << 1) | referenceBitmap[i0][j0];
  41765. }
  41766. }
  41767. var pixel = decoder.readBit(contexts, contextLabel);
  41768. row[j] = pixel;
  41769. }
  41770. }
  41771. return bitmap;
  41772. }
  41773. // 6.5.5 Decoding the symbol dictionary
  41774. function decodeSymbolDictionary(huffman, refinement, symbols,
  41775. numberOfNewSymbols, numberOfExportedSymbols,
  41776. huffmanTables, templateIndex, at,
  41777. refinementTemplateIndex, refinementAt,
  41778. decodingContext) {
  41779. if (huffman) {
  41780. error('JBIG2 error: huffman is not supported');
  41781. }
  41782. var newSymbols = [];
  41783. var currentHeight = 0;
  41784. var symbolCodeLength = log2(symbols.length + numberOfNewSymbols);
  41785. var decoder = decodingContext.decoder;
  41786. var contextCache = decodingContext.contextCache;
  41787. while (newSymbols.length < numberOfNewSymbols) {
  41788. var deltaHeight = decodeInteger(contextCache, 'IADH', decoder); // 6.5.6
  41789. currentHeight += deltaHeight;
  41790. var currentWidth = 0;
  41791. var totalWidth = 0;
  41792. while (true) {
  41793. var deltaWidth = decodeInteger(contextCache, 'IADW', decoder); // 6.5.7
  41794. if (deltaWidth === null) {
  41795. break; // OOB
  41796. }
  41797. currentWidth += deltaWidth;
  41798. totalWidth += currentWidth;
  41799. var bitmap;
  41800. if (refinement) {
  41801. // 6.5.8.2 Refinement/aggregate-coded symbol bitmap
  41802. var numberOfInstances = decodeInteger(contextCache, 'IAAI', decoder);
  41803. if (numberOfInstances > 1) {
  41804. bitmap = decodeTextRegion(huffman, refinement,
  41805. currentWidth, currentHeight, 0,
  41806. numberOfInstances, 1, //strip size
  41807. symbols.concat(newSymbols),
  41808. symbolCodeLength,
  41809. 0, //transposed
  41810. 0, //ds offset
  41811. 1, //top left 7.4.3.1.1
  41812. 0, //OR operator
  41813. huffmanTables,
  41814. refinementTemplateIndex, refinementAt,
  41815. decodingContext);
  41816. } else {
  41817. var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  41818. var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3
  41819. var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4
  41820. var symbol = (symbolId < symbols.length ? symbols[symbolId] :
  41821. newSymbols[symbolId - symbols.length]);
  41822. bitmap = decodeRefinement(currentWidth, currentHeight,
  41823. refinementTemplateIndex, symbol, rdx, rdy, false, refinementAt,
  41824. decodingContext);
  41825. }
  41826. } else {
  41827. // 6.5.8.1 Direct-coded symbol bitmap
  41828. bitmap = decodeBitmap(false, currentWidth, currentHeight,
  41829. templateIndex, false, null, at, decodingContext);
  41830. }
  41831. newSymbols.push(bitmap);
  41832. }
  41833. }
  41834. // 6.5.10 Exported symbols
  41835. var exportedSymbols = [];
  41836. var flags = [], currentFlag = false;
  41837. var totalSymbolsLength = symbols.length + numberOfNewSymbols;
  41838. while (flags.length < totalSymbolsLength) {
  41839. var runLength = decodeInteger(contextCache, 'IAEX', decoder);
  41840. while (runLength--) {
  41841. flags.push(currentFlag);
  41842. }
  41843. currentFlag = !currentFlag;
  41844. }
  41845. for (var i = 0, ii = symbols.length; i < ii; i++) {
  41846. if (flags[i]) {
  41847. exportedSymbols.push(symbols[i]);
  41848. }
  41849. }
  41850. for (var j = 0; j < numberOfNewSymbols; i++, j++) {
  41851. if (flags[i]) {
  41852. exportedSymbols.push(newSymbols[j]);
  41853. }
  41854. }
  41855. return exportedSymbols;
  41856. }
  41857. function decodeTextRegion(huffman, refinement, width, height,
  41858. defaultPixelValue, numberOfSymbolInstances,
  41859. stripSize, inputSymbols, symbolCodeLength,
  41860. transposed, dsOffset, referenceCorner,
  41861. combinationOperator, huffmanTables,
  41862. refinementTemplateIndex, refinementAt,
  41863. decodingContext) {
  41864. if (huffman) {
  41865. error('JBIG2 error: huffman is not supported');
  41866. }
  41867. // Prepare bitmap
  41868. var bitmap = [];
  41869. var i, row;
  41870. for (i = 0; i < height; i++) {
  41871. row = new Uint8Array(width);
  41872. if (defaultPixelValue) {
  41873. for (var j = 0; j < width; j++) {
  41874. row[j] = defaultPixelValue;
  41875. }
  41876. }
  41877. bitmap.push(row);
  41878. }
  41879. var decoder = decodingContext.decoder;
  41880. var contextCache = decodingContext.contextCache;
  41881. var stripT = -decodeInteger(contextCache, 'IADT', decoder); // 6.4.6
  41882. var firstS = 0;
  41883. i = 0;
  41884. while (i < numberOfSymbolInstances) {
  41885. var deltaT = decodeInteger(contextCache, 'IADT', decoder); // 6.4.6
  41886. stripT += deltaT;
  41887. var deltaFirstS = decodeInteger(contextCache, 'IAFS', decoder); // 6.4.7
  41888. firstS += deltaFirstS;
  41889. var currentS = firstS;
  41890. do {
  41891. var currentT = (stripSize === 1 ? 0 :
  41892. decodeInteger(contextCache, 'IAIT', decoder)); // 6.4.9
  41893. var t = stripSize * stripT + currentT;
  41894. var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  41895. var applyRefinement = (refinement &&
  41896. decodeInteger(contextCache, 'IARI', decoder));
  41897. var symbolBitmap = inputSymbols[symbolId];
  41898. var symbolWidth = symbolBitmap[0].length;
  41899. var symbolHeight = symbolBitmap.length;
  41900. if (applyRefinement) {
  41901. var rdw = decodeInteger(contextCache, 'IARDW', decoder); // 6.4.11.1
  41902. var rdh = decodeInteger(contextCache, 'IARDH', decoder); // 6.4.11.2
  41903. var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3
  41904. var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4
  41905. symbolWidth += rdw;
  41906. symbolHeight += rdh;
  41907. symbolBitmap = decodeRefinement(symbolWidth, symbolHeight,
  41908. refinementTemplateIndex, symbolBitmap, (rdw >> 1) + rdx,
  41909. (rdh >> 1) + rdy, false, refinementAt,
  41910. decodingContext);
  41911. }
  41912. var offsetT = t - ((referenceCorner & 1) ? 0 : symbolHeight);
  41913. var offsetS = currentS - ((referenceCorner & 2) ? symbolWidth : 0);
  41914. var s2, t2, symbolRow;
  41915. if (transposed) {
  41916. // Place Symbol Bitmap from T1,S1
  41917. for (s2 = 0; s2 < symbolHeight; s2++) {
  41918. row = bitmap[offsetS + s2];
  41919. if (!row) {
  41920. continue;
  41921. }
  41922. symbolRow = symbolBitmap[s2];
  41923. // To ignore Parts of Symbol bitmap which goes
  41924. // outside bitmap region
  41925. var maxWidth = Math.min(width - offsetT, symbolWidth);
  41926. switch (combinationOperator) {
  41927. case 0: // OR
  41928. for (t2 = 0; t2 < maxWidth; t2++) {
  41929. row[offsetT + t2] |= symbolRow[t2];
  41930. }
  41931. break;
  41932. case 2: // XOR
  41933. for (t2 = 0; t2 < maxWidth; t2++) {
  41934. row[offsetT + t2] ^= symbolRow[t2];
  41935. }
  41936. break;
  41937. default:
  41938. error('JBIG2 error: operator ' + combinationOperator +
  41939. ' is not supported');
  41940. }
  41941. }
  41942. currentS += symbolHeight - 1;
  41943. } else {
  41944. for (t2 = 0; t2 < symbolHeight; t2++) {
  41945. row = bitmap[offsetT + t2];
  41946. if (!row) {
  41947. continue;
  41948. }
  41949. symbolRow = symbolBitmap[t2];
  41950. switch (combinationOperator) {
  41951. case 0: // OR
  41952. for (s2 = 0; s2 < symbolWidth; s2++) {
  41953. row[offsetS + s2] |= symbolRow[s2];
  41954. }
  41955. break;
  41956. case 2: // XOR
  41957. for (s2 = 0; s2 < symbolWidth; s2++) {
  41958. row[offsetS + s2] ^= symbolRow[s2];
  41959. }
  41960. break;
  41961. default:
  41962. error('JBIG2 error: operator ' + combinationOperator +
  41963. ' is not supported');
  41964. }
  41965. }
  41966. currentS += symbolWidth - 1;
  41967. }
  41968. i++;
  41969. var deltaS = decodeInteger(contextCache, 'IADS', decoder); // 6.4.8
  41970. if (deltaS === null) {
  41971. break; // OOB
  41972. }
  41973. currentS += deltaS + dsOffset;
  41974. } while (true);
  41975. }
  41976. return bitmap;
  41977. }
  41978. function readSegmentHeader(data, start) {
  41979. var segmentHeader = {};
  41980. segmentHeader.number = readUint32(data, start);
  41981. var flags = data[start + 4];
  41982. var segmentType = flags & 0x3F;
  41983. if (!SegmentTypes[segmentType]) {
  41984. error('JBIG2 error: invalid segment type: ' + segmentType);
  41985. }
  41986. segmentHeader.type = segmentType;
  41987. segmentHeader.typeName = SegmentTypes[segmentType];
  41988. segmentHeader.deferredNonRetain = !!(flags & 0x80);
  41989. var pageAssociationFieldSize = !!(flags & 0x40);
  41990. var referredFlags = data[start + 5];
  41991. var referredToCount = (referredFlags >> 5) & 7;
  41992. var retainBits = [referredFlags & 31];
  41993. var position = start + 6;
  41994. if (referredFlags === 7) {
  41995. referredToCount = readUint32(data, position - 1) & 0x1FFFFFFF;
  41996. position += 3;
  41997. var bytes = (referredToCount + 7) >> 3;
  41998. retainBits[0] = data[position++];
  41999. while (--bytes > 0) {
  42000. retainBits.push(data[position++]);
  42001. }
  42002. } else if (referredFlags === 5 || referredFlags === 6) {
  42003. error('JBIG2 error: invalid referred-to flags');
  42004. }
  42005. segmentHeader.retainBits = retainBits;
  42006. var referredToSegmentNumberSize = (segmentHeader.number <= 256 ? 1 :
  42007. (segmentHeader.number <= 65536 ? 2 : 4));
  42008. var referredTo = [];
  42009. var i, ii;
  42010. for (i = 0; i < referredToCount; i++) {
  42011. var number = (referredToSegmentNumberSize === 1 ? data[position] :
  42012. (referredToSegmentNumberSize === 2 ? readUint16(data, position) :
  42013. readUint32(data, position)));
  42014. referredTo.push(number);
  42015. position += referredToSegmentNumberSize;
  42016. }
  42017. segmentHeader.referredTo = referredTo;
  42018. if (!pageAssociationFieldSize) {
  42019. segmentHeader.pageAssociation = data[position++];
  42020. } else {
  42021. segmentHeader.pageAssociation = readUint32(data, position);
  42022. position += 4;
  42023. }
  42024. segmentHeader.length = readUint32(data, position);
  42025. position += 4;
  42026. if (segmentHeader.length === 0xFFFFFFFF) {
  42027. // 7.2.7 Segment data length, unknown segment length
  42028. if (segmentType === 38) { // ImmediateGenericRegion
  42029. var genericRegionInfo = readRegionSegmentInformation(data, position);
  42030. var genericRegionSegmentFlags = data[position +
  42031. RegionSegmentInformationFieldLength];
  42032. var genericRegionMmr = !!(genericRegionSegmentFlags & 1);
  42033. // searching for the segment end
  42034. var searchPatternLength = 6;
  42035. var searchPattern = new Uint8Array(searchPatternLength);
  42036. if (!genericRegionMmr) {
  42037. searchPattern[0] = 0xFF;
  42038. searchPattern[1] = 0xAC;
  42039. }
  42040. searchPattern[2] = (genericRegionInfo.height >>> 24) & 0xFF;
  42041. searchPattern[3] = (genericRegionInfo.height >> 16) & 0xFF;
  42042. searchPattern[4] = (genericRegionInfo.height >> 8) & 0xFF;
  42043. searchPattern[5] = genericRegionInfo.height & 0xFF;
  42044. for (i = position, ii = data.length; i < ii; i++) {
  42045. var j = 0;
  42046. while (j < searchPatternLength && searchPattern[j] === data[i + j]) {
  42047. j++;
  42048. }
  42049. if (j === searchPatternLength) {
  42050. segmentHeader.length = i + searchPatternLength;
  42051. break;
  42052. }
  42053. }
  42054. if (segmentHeader.length === 0xFFFFFFFF) {
  42055. error('JBIG2 error: segment end was not found');
  42056. }
  42057. } else {
  42058. error('JBIG2 error: invalid unknown segment length');
  42059. }
  42060. }
  42061. segmentHeader.headerEnd = position;
  42062. return segmentHeader;
  42063. }
  42064. function readSegments(header, data, start, end) {
  42065. var segments = [];
  42066. var position = start;
  42067. while (position < end) {
  42068. var segmentHeader = readSegmentHeader(data, position);
  42069. position = segmentHeader.headerEnd;
  42070. var segment = {
  42071. header: segmentHeader,
  42072. data: data
  42073. };
  42074. if (!header.randomAccess) {
  42075. segment.start = position;
  42076. position += segmentHeader.length;
  42077. segment.end = position;
  42078. }
  42079. segments.push(segment);
  42080. if (segmentHeader.type === 51) {
  42081. break; // end of file is found
  42082. }
  42083. }
  42084. if (header.randomAccess) {
  42085. for (var i = 0, ii = segments.length; i < ii; i++) {
  42086. segments[i].start = position;
  42087. position += segments[i].header.length;
  42088. segments[i].end = position;
  42089. }
  42090. }
  42091. return segments;
  42092. }
  42093. // 7.4.1 Region segment information field
  42094. function readRegionSegmentInformation(data, start) {
  42095. return {
  42096. width: readUint32(data, start),
  42097. height: readUint32(data, start + 4),
  42098. x: readUint32(data, start + 8),
  42099. y: readUint32(data, start + 12),
  42100. combinationOperator: data[start + 16] & 7
  42101. };
  42102. }
  42103. var RegionSegmentInformationFieldLength = 17;
  42104. function processSegment(segment, visitor) {
  42105. var header = segment.header;
  42106. var data = segment.data, position = segment.start, end = segment.end;
  42107. var args, at, i, atLength;
  42108. switch (header.type) {
  42109. case 0: // SymbolDictionary
  42110. // 7.4.2 Symbol dictionary segment syntax
  42111. var dictionary = {};
  42112. var dictionaryFlags = readUint16(data, position); // 7.4.2.1.1
  42113. dictionary.huffman = !!(dictionaryFlags & 1);
  42114. dictionary.refinement = !!(dictionaryFlags & 2);
  42115. dictionary.huffmanDHSelector = (dictionaryFlags >> 2) & 3;
  42116. dictionary.huffmanDWSelector = (dictionaryFlags >> 4) & 3;
  42117. dictionary.bitmapSizeSelector = (dictionaryFlags >> 6) & 1;
  42118. dictionary.aggregationInstancesSelector = (dictionaryFlags >> 7) & 1;
  42119. dictionary.bitmapCodingContextUsed = !!(dictionaryFlags & 256);
  42120. dictionary.bitmapCodingContextRetained = !!(dictionaryFlags & 512);
  42121. dictionary.template = (dictionaryFlags >> 10) & 3;
  42122. dictionary.refinementTemplate = (dictionaryFlags >> 12) & 1;
  42123. position += 2;
  42124. if (!dictionary.huffman) {
  42125. atLength = dictionary.template === 0 ? 4 : 1;
  42126. at = [];
  42127. for (i = 0; i < atLength; i++) {
  42128. at.push({
  42129. x: readInt8(data, position),
  42130. y: readInt8(data, position + 1)
  42131. });
  42132. position += 2;
  42133. }
  42134. dictionary.at = at;
  42135. }
  42136. if (dictionary.refinement && !dictionary.refinementTemplate) {
  42137. at = [];
  42138. for (i = 0; i < 2; i++) {
  42139. at.push({
  42140. x: readInt8(data, position),
  42141. y: readInt8(data, position + 1)
  42142. });
  42143. position += 2;
  42144. }
  42145. dictionary.refinementAt = at;
  42146. }
  42147. dictionary.numberOfExportedSymbols = readUint32(data, position);
  42148. position += 4;
  42149. dictionary.numberOfNewSymbols = readUint32(data, position);
  42150. position += 4;
  42151. args = [dictionary, header.number, header.referredTo,
  42152. data, position, end];
  42153. break;
  42154. case 6: // ImmediateTextRegion
  42155. case 7: // ImmediateLosslessTextRegion
  42156. var textRegion = {};
  42157. textRegion.info = readRegionSegmentInformation(data, position);
  42158. position += RegionSegmentInformationFieldLength;
  42159. var textRegionSegmentFlags = readUint16(data, position);
  42160. position += 2;
  42161. textRegion.huffman = !!(textRegionSegmentFlags & 1);
  42162. textRegion.refinement = !!(textRegionSegmentFlags & 2);
  42163. textRegion.stripSize = 1 << ((textRegionSegmentFlags >> 2) & 3);
  42164. textRegion.referenceCorner = (textRegionSegmentFlags >> 4) & 3;
  42165. textRegion.transposed = !!(textRegionSegmentFlags & 64);
  42166. textRegion.combinationOperator = (textRegionSegmentFlags >> 7) & 3;
  42167. textRegion.defaultPixelValue = (textRegionSegmentFlags >> 9) & 1;
  42168. textRegion.dsOffset = (textRegionSegmentFlags << 17) >> 27;
  42169. textRegion.refinementTemplate = (textRegionSegmentFlags >> 15) & 1;
  42170. if (textRegion.huffman) {
  42171. var textRegionHuffmanFlags = readUint16(data, position);
  42172. position += 2;
  42173. textRegion.huffmanFS = (textRegionHuffmanFlags) & 3;
  42174. textRegion.huffmanDS = (textRegionHuffmanFlags >> 2) & 3;
  42175. textRegion.huffmanDT = (textRegionHuffmanFlags >> 4) & 3;
  42176. textRegion.huffmanRefinementDW = (textRegionHuffmanFlags >> 6) & 3;
  42177. textRegion.huffmanRefinementDH = (textRegionHuffmanFlags >> 8) & 3;
  42178. textRegion.huffmanRefinementDX = (textRegionHuffmanFlags >> 10) & 3;
  42179. textRegion.huffmanRefinementDY = (textRegionHuffmanFlags >> 12) & 3;
  42180. textRegion.huffmanRefinementSizeSelector =
  42181. !!(textRegionHuffmanFlags & 14);
  42182. }
  42183. if (textRegion.refinement && !textRegion.refinementTemplate) {
  42184. at = [];
  42185. for (i = 0; i < 2; i++) {
  42186. at.push({
  42187. x: readInt8(data, position),
  42188. y: readInt8(data, position + 1)
  42189. });
  42190. position += 2;
  42191. }
  42192. textRegion.refinementAt = at;
  42193. }
  42194. textRegion.numberOfSymbolInstances = readUint32(data, position);
  42195. position += 4;
  42196. // TODO 7.4.3.1.7 Symbol ID Huffman table decoding
  42197. if (textRegion.huffman) {
  42198. error('JBIG2 error: huffman is not supported');
  42199. }
  42200. args = [textRegion, header.referredTo, data, position, end];
  42201. break;
  42202. case 38: // ImmediateGenericRegion
  42203. case 39: // ImmediateLosslessGenericRegion
  42204. var genericRegion = {};
  42205. genericRegion.info = readRegionSegmentInformation(data, position);
  42206. position += RegionSegmentInformationFieldLength;
  42207. var genericRegionSegmentFlags = data[position++];
  42208. genericRegion.mmr = !!(genericRegionSegmentFlags & 1);
  42209. genericRegion.template = (genericRegionSegmentFlags >> 1) & 3;
  42210. genericRegion.prediction = !!(genericRegionSegmentFlags & 8);
  42211. if (!genericRegion.mmr) {
  42212. atLength = genericRegion.template === 0 ? 4 : 1;
  42213. at = [];
  42214. for (i = 0; i < atLength; i++) {
  42215. at.push({
  42216. x: readInt8(data, position),
  42217. y: readInt8(data, position + 1)
  42218. });
  42219. position += 2;
  42220. }
  42221. genericRegion.at = at;
  42222. }
  42223. args = [genericRegion, data, position, end];
  42224. break;
  42225. case 48: // PageInformation
  42226. var pageInfo = {
  42227. width: readUint32(data, position),
  42228. height: readUint32(data, position + 4),
  42229. resolutionX: readUint32(data, position + 8),
  42230. resolutionY: readUint32(data, position + 12)
  42231. };
  42232. if (pageInfo.height === 0xFFFFFFFF) {
  42233. delete pageInfo.height;
  42234. }
  42235. var pageSegmentFlags = data[position + 16];
  42236. var pageStripingInformatiom = readUint16(data, position + 17);
  42237. pageInfo.lossless = !!(pageSegmentFlags & 1);
  42238. pageInfo.refinement = !!(pageSegmentFlags & 2);
  42239. pageInfo.defaultPixelValue = (pageSegmentFlags >> 2) & 1;
  42240. pageInfo.combinationOperator = (pageSegmentFlags >> 3) & 3;
  42241. pageInfo.requiresBuffer = !!(pageSegmentFlags & 32);
  42242. pageInfo.combinationOperatorOverride = !!(pageSegmentFlags & 64);
  42243. args = [pageInfo];
  42244. break;
  42245. case 49: // EndOfPage
  42246. break;
  42247. case 50: // EndOfStripe
  42248. break;
  42249. case 51: // EndOfFile
  42250. break;
  42251. case 62: // 7.4.15 defines 2 extension types which
  42252. // are comments and can be ignored.
  42253. break;
  42254. default:
  42255. error('JBIG2 error: segment type ' + header.typeName + '(' +
  42256. header.type + ') is not implemented');
  42257. }
  42258. var callbackName = 'on' + header.typeName;
  42259. if (callbackName in visitor) {
  42260. visitor[callbackName].apply(visitor, args);
  42261. }
  42262. }
  42263. function processSegments(segments, visitor) {
  42264. for (var i = 0, ii = segments.length; i < ii; i++) {
  42265. processSegment(segments[i], visitor);
  42266. }
  42267. }
  42268. function parseJbig2(data, start, end) {
  42269. var position = start;
  42270. if (data[position] !== 0x97 || data[position + 1] !== 0x4A ||
  42271. data[position + 2] !== 0x42 || data[position + 3] !== 0x32 ||
  42272. data[position + 4] !== 0x0D || data[position + 5] !== 0x0A ||
  42273. data[position + 6] !== 0x1A || data[position + 7] !== 0x0A) {
  42274. error('JBIG2 error: invalid header');
  42275. }
  42276. var header = {};
  42277. position += 8;
  42278. var flags = data[position++];
  42279. header.randomAccess = !(flags & 1);
  42280. if (!(flags & 2)) {
  42281. header.numberOfPages = readUint32(data, position);
  42282. position += 4;
  42283. }
  42284. var segments = readSegments(header, data, position, end);
  42285. error('Not implemented');
  42286. // processSegments(segments, new SimpleSegmentVisitor());
  42287. }
  42288. function parseJbig2Chunks(chunks) {
  42289. var visitor = new SimpleSegmentVisitor();
  42290. for (var i = 0, ii = chunks.length; i < ii; i++) {
  42291. var chunk = chunks[i];
  42292. var segments = readSegments({}, chunk.data, chunk.start, chunk.end);
  42293. processSegments(segments, visitor);
  42294. }
  42295. return visitor.buffer;
  42296. }
  42297. function SimpleSegmentVisitor() {}
  42298. SimpleSegmentVisitor.prototype = {
  42299. onPageInformation: function SimpleSegmentVisitor_onPageInformation(info) {
  42300. this.currentPageInfo = info;
  42301. var rowSize = (info.width + 7) >> 3;
  42302. var buffer = new Uint8Array(rowSize * info.height);
  42303. // The contents of ArrayBuffers are initialized to 0.
  42304. // Fill the buffer with 0xFF only if info.defaultPixelValue is set
  42305. if (info.defaultPixelValue) {
  42306. for (var i = 0, ii = buffer.length; i < ii; i++) {
  42307. buffer[i] = 0xFF;
  42308. }
  42309. }
  42310. this.buffer = buffer;
  42311. },
  42312. drawBitmap: function SimpleSegmentVisitor_drawBitmap(regionInfo, bitmap) {
  42313. var pageInfo = this.currentPageInfo;
  42314. var width = regionInfo.width, height = regionInfo.height;
  42315. var rowSize = (pageInfo.width + 7) >> 3;
  42316. var combinationOperator = pageInfo.combinationOperatorOverride ?
  42317. regionInfo.combinationOperator : pageInfo.combinationOperator;
  42318. var buffer = this.buffer;
  42319. var mask0 = 128 >> (regionInfo.x & 7);
  42320. var offset0 = regionInfo.y * rowSize + (regionInfo.x >> 3);
  42321. var i, j, mask, offset;
  42322. switch (combinationOperator) {
  42323. case 0: // OR
  42324. for (i = 0; i < height; i++) {
  42325. mask = mask0;
  42326. offset = offset0;
  42327. for (j = 0; j < width; j++) {
  42328. if (bitmap[i][j]) {
  42329. buffer[offset] |= mask;
  42330. }
  42331. mask >>= 1;
  42332. if (!mask) {
  42333. mask = 128;
  42334. offset++;
  42335. }
  42336. }
  42337. offset0 += rowSize;
  42338. }
  42339. break;
  42340. case 2: // XOR
  42341. for (i = 0; i < height; i++) {
  42342. mask = mask0;
  42343. offset = offset0;
  42344. for (j = 0; j < width; j++) {
  42345. if (bitmap[i][j]) {
  42346. buffer[offset] ^= mask;
  42347. }
  42348. mask >>= 1;
  42349. if (!mask) {
  42350. mask = 128;
  42351. offset++;
  42352. }
  42353. }
  42354. offset0 += rowSize;
  42355. }
  42356. break;
  42357. default:
  42358. error('JBIG2 error: operator ' + combinationOperator +
  42359. ' is not supported');
  42360. }
  42361. },
  42362. onImmediateGenericRegion:
  42363. function SimpleSegmentVisitor_onImmediateGenericRegion(region, data,
  42364. start, end) {
  42365. var regionInfo = region.info;
  42366. var decodingContext = new DecodingContext(data, start, end);
  42367. var bitmap = decodeBitmap(region.mmr, regionInfo.width, regionInfo.height,
  42368. region.template, region.prediction, null,
  42369. region.at, decodingContext);
  42370. this.drawBitmap(regionInfo, bitmap);
  42371. },
  42372. onImmediateLosslessGenericRegion:
  42373. function SimpleSegmentVisitor_onImmediateLosslessGenericRegion() {
  42374. this.onImmediateGenericRegion.apply(this, arguments);
  42375. },
  42376. onSymbolDictionary:
  42377. function SimpleSegmentVisitor_onSymbolDictionary(dictionary,
  42378. currentSegment,
  42379. referredSegments,
  42380. data, start, end) {
  42381. var huffmanTables;
  42382. if (dictionary.huffman) {
  42383. error('JBIG2 error: huffman is not supported');
  42384. }
  42385. // Combines exported symbols from all referred segments
  42386. var symbols = this.symbols;
  42387. if (!symbols) {
  42388. this.symbols = symbols = {};
  42389. }
  42390. var inputSymbols = [];
  42391. for (var i = 0, ii = referredSegments.length; i < ii; i++) {
  42392. inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
  42393. }
  42394. var decodingContext = new DecodingContext(data, start, end);
  42395. symbols[currentSegment] = decodeSymbolDictionary(dictionary.huffman,
  42396. dictionary.refinement, inputSymbols, dictionary.numberOfNewSymbols,
  42397. dictionary.numberOfExportedSymbols, huffmanTables,
  42398. dictionary.template, dictionary.at,
  42399. dictionary.refinementTemplate, dictionary.refinementAt,
  42400. decodingContext);
  42401. },
  42402. onImmediateTextRegion:
  42403. function SimpleSegmentVisitor_onImmediateTextRegion(region,
  42404. referredSegments,
  42405. data, start, end) {
  42406. var regionInfo = region.info;
  42407. var huffmanTables;
  42408. // Combines exported symbols from all referred segments
  42409. var symbols = this.symbols;
  42410. var inputSymbols = [];
  42411. for (var i = 0, ii = referredSegments.length; i < ii; i++) {
  42412. inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
  42413. }
  42414. var symbolCodeLength = log2(inputSymbols.length);
  42415. var decodingContext = new DecodingContext(data, start, end);
  42416. var bitmap = decodeTextRegion(region.huffman, region.refinement,
  42417. regionInfo.width, regionInfo.height, region.defaultPixelValue,
  42418. region.numberOfSymbolInstances, region.stripSize, inputSymbols,
  42419. symbolCodeLength, region.transposed, region.dsOffset,
  42420. region.referenceCorner, region.combinationOperator, huffmanTables,
  42421. region.refinementTemplate, region.refinementAt, decodingContext);
  42422. this.drawBitmap(regionInfo, bitmap);
  42423. },
  42424. onImmediateLosslessTextRegion:
  42425. function SimpleSegmentVisitor_onImmediateLosslessTextRegion() {
  42426. this.onImmediateTextRegion.apply(this, arguments);
  42427. }
  42428. };
  42429. function Jbig2Image() {}
  42430. Jbig2Image.prototype = {
  42431. parseChunks: function Jbig2Image_parseChunks(chunks) {
  42432. return parseJbig2Chunks(chunks);
  42433. }
  42434. };
  42435. return Jbig2Image;
  42436. })();
  42437. var bidi = PDFJS.bidi = (function bidiClosure() {
  42438. // Character types for symbols from 0000 to 00FF.
  42439. var baseTypes = [
  42440. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS',
  42441. 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  42442. 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON',
  42443. 'ON', 'ON', 'ON', 'ON', 'ON', 'CS', 'ON', 'CS', 'ON', 'EN', 'EN', 'EN',
  42444. 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'ON', 'ON', 'ON', 'ON', 'ON',
  42445. 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42446. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON',
  42447. 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42448. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42449. 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN',
  42450. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  42451. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  42452. 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON',
  42453. 'ON', 'ON', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON',
  42454. 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42455. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42456. 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42457. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42458. 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'
  42459. ];
  42460. // Character types for symbols from 0600 to 06FF
  42461. var arabicTypes = [
  42462. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42463. 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL',
  42464. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42465. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42466. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42467. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42468. 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
  42469. 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL',
  42470. 'AL', 'AL', 'AL', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN',
  42471. 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL',
  42472. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42473. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42474. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42475. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42476. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42477. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42478. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42479. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42480. 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
  42481. 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'ON', 'NSM',
  42482. 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42483. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL'
  42484. ];
  42485. function isOdd(i) {
  42486. return (i & 1) !== 0;
  42487. }
  42488. function isEven(i) {
  42489. return (i & 1) === 0;
  42490. }
  42491. function findUnequal(arr, start, value) {
  42492. for (var j = start, jj = arr.length; j < jj; ++j) {
  42493. if (arr[j] !== value) {
  42494. return j;
  42495. }
  42496. }
  42497. return j;
  42498. }
  42499. function setValues(arr, start, end, value) {
  42500. for (var j = start; j < end; ++j) {
  42501. arr[j] = value;
  42502. }
  42503. }
  42504. function reverseValues(arr, start, end) {
  42505. for (var i = start, j = end - 1; i < j; ++i, --j) {
  42506. var temp = arr[i];
  42507. arr[i] = arr[j];
  42508. arr[j] = temp;
  42509. }
  42510. }
  42511. function createBidiText(str, isLTR, vertical) {
  42512. return {
  42513. str: str,
  42514. dir: (vertical ? 'ttb' : (isLTR ? 'ltr' : 'rtl'))
  42515. };
  42516. }
  42517. // These are used in bidi(), which is called frequently. We re-use them on
  42518. // each call to avoid unnecessary allocations.
  42519. var chars = [];
  42520. var types = [];
  42521. function bidi(str, startLevel, vertical) {
  42522. var isLTR = true;
  42523. var strLength = str.length;
  42524. if (strLength === 0 || vertical) {
  42525. return createBidiText(str, isLTR, vertical);
  42526. }
  42527. // Get types and fill arrays
  42528. chars.length = strLength;
  42529. types.length = strLength;
  42530. var numBidi = 0;
  42531. var i, ii;
  42532. for (i = 0; i < strLength; ++i) {
  42533. chars[i] = str.charAt(i);
  42534. var charCode = str.charCodeAt(i);
  42535. var charType = 'L';
  42536. if (charCode <= 0x00ff) {
  42537. charType = baseTypes[charCode];
  42538. } else if (0x0590 <= charCode && charCode <= 0x05f4) {
  42539. charType = 'R';
  42540. } else if (0x0600 <= charCode && charCode <= 0x06ff) {
  42541. charType = arabicTypes[charCode & 0xff];
  42542. } else if (0x0700 <= charCode && charCode <= 0x08AC) {
  42543. charType = 'AL';
  42544. }
  42545. if (charType === 'R' || charType === 'AL' || charType === 'AN') {
  42546. numBidi++;
  42547. }
  42548. types[i] = charType;
  42549. }
  42550. // Detect the bidi method
  42551. // - If there are no rtl characters then no bidi needed
  42552. // - If less than 30% chars are rtl then string is primarily ltr
  42553. // - If more than 30% chars are rtl then string is primarily rtl
  42554. if (numBidi === 0) {
  42555. isLTR = true;
  42556. return createBidiText(str, isLTR);
  42557. }
  42558. if (startLevel === -1) {
  42559. if ((strLength / numBidi) < 0.3) {
  42560. isLTR = true;
  42561. startLevel = 0;
  42562. } else {
  42563. isLTR = false;
  42564. startLevel = 1;
  42565. }
  42566. }
  42567. var levels = [];
  42568. for (i = 0; i < strLength; ++i) {
  42569. levels[i] = startLevel;
  42570. }
  42571. /*
  42572. X1-X10: skip most of this, since we are NOT doing the embeddings.
  42573. */
  42574. var e = (isOdd(startLevel) ? 'R' : 'L');
  42575. var sor = e;
  42576. var eor = sor;
  42577. /*
  42578. W1. Examine each non-spacing mark (NSM) in the level run, and change the
  42579. type of the NSM to the type of the previous character. If the NSM is at the
  42580. start of the level run, it will get the type of sor.
  42581. */
  42582. var lastType = sor;
  42583. for (i = 0; i < strLength; ++i) {
  42584. if (types[i] === 'NSM') {
  42585. types[i] = lastType;
  42586. } else {
  42587. lastType = types[i];
  42588. }
  42589. }
  42590. /*
  42591. W2. Search backwards from each instance of a European number until the
  42592. first strong type (R, L, AL, or sor) is found. If an AL is found, change
  42593. the type of the European number to Arabic number.
  42594. */
  42595. lastType = sor;
  42596. var t;
  42597. for (i = 0; i < strLength; ++i) {
  42598. t = types[i];
  42599. if (t === 'EN') {
  42600. types[i] = (lastType === 'AL') ? 'AN' : 'EN';
  42601. } else if (t === 'R' || t === 'L' || t === 'AL') {
  42602. lastType = t;
  42603. }
  42604. }
  42605. /*
  42606. W3. Change all ALs to R.
  42607. */
  42608. for (i = 0; i < strLength; ++i) {
  42609. t = types[i];
  42610. if (t === 'AL') {
  42611. types[i] = 'R';
  42612. }
  42613. }
  42614. /*
  42615. W4. A single European separator between two European numbers changes to a
  42616. European number. A single common separator between two numbers of the same
  42617. type changes to that type:
  42618. */
  42619. for (i = 1; i < strLength - 1; ++i) {
  42620. if (types[i] === 'ES' && types[i - 1] === 'EN' && types[i + 1] === 'EN') {
  42621. types[i] = 'EN';
  42622. }
  42623. if (types[i] === 'CS' &&
  42624. (types[i - 1] === 'EN' || types[i - 1] === 'AN') &&
  42625. types[i + 1] === types[i - 1]) {
  42626. types[i] = types[i - 1];
  42627. }
  42628. }
  42629. /*
  42630. W5. A sequence of European terminators adjacent to European numbers changes
  42631. to all European numbers:
  42632. */
  42633. for (i = 0; i < strLength; ++i) {
  42634. if (types[i] === 'EN') {
  42635. // do before
  42636. var j;
  42637. for (j = i - 1; j >= 0; --j) {
  42638. if (types[j] !== 'ET') {
  42639. break;
  42640. }
  42641. types[j] = 'EN';
  42642. }
  42643. // do after
  42644. for (j = i + 1; j < strLength; --j) {
  42645. if (types[j] !== 'ET') {
  42646. break;
  42647. }
  42648. types[j] = 'EN';
  42649. }
  42650. }
  42651. }
  42652. /*
  42653. W6. Otherwise, separators and terminators change to Other Neutral:
  42654. */
  42655. for (i = 0; i < strLength; ++i) {
  42656. t = types[i];
  42657. if (t === 'WS' || t === 'ES' || t === 'ET' || t === 'CS') {
  42658. types[i] = 'ON';
  42659. }
  42660. }
  42661. /*
  42662. W7. Search backwards from each instance of a European number until the
  42663. first strong type (R, L, or sor) is found. If an L is found, then change
  42664. the type of the European number to L.
  42665. */
  42666. lastType = sor;
  42667. for (i = 0; i < strLength; ++i) {
  42668. t = types[i];
  42669. if (t === 'EN') {
  42670. types[i] = ((lastType === 'L') ? 'L' : 'EN');
  42671. } else if (t === 'R' || t === 'L') {
  42672. lastType = t;
  42673. }
  42674. }
  42675. /*
  42676. N1. A sequence of neutrals takes the direction of the surrounding strong
  42677. text if the text on both sides has the same direction. European and Arabic
  42678. numbers are treated as though they were R. Start-of-level-run (sor) and
  42679. end-of-level-run (eor) are used at level run boundaries.
  42680. */
  42681. for (i = 0; i < strLength; ++i) {
  42682. if (types[i] === 'ON') {
  42683. var end = findUnequal(types, i + 1, 'ON');
  42684. var before = sor;
  42685. if (i > 0) {
  42686. before = types[i - 1];
  42687. }
  42688. var after = eor;
  42689. if (end + 1 < strLength) {
  42690. after = types[end + 1];
  42691. }
  42692. if (before !== 'L') {
  42693. before = 'R';
  42694. }
  42695. if (after !== 'L') {
  42696. after = 'R';
  42697. }
  42698. if (before === after) {
  42699. setValues(types, i, end, before);
  42700. }
  42701. i = end - 1; // reset to end (-1 so next iteration is ok)
  42702. }
  42703. }
  42704. /*
  42705. N2. Any remaining neutrals take the embedding direction.
  42706. */
  42707. for (i = 0; i < strLength; ++i) {
  42708. if (types[i] === 'ON') {
  42709. types[i] = e;
  42710. }
  42711. }
  42712. /*
  42713. I1. For all characters with an even (left-to-right) embedding direction,
  42714. those of type R go up one level and those of type AN or EN go up two
  42715. levels.
  42716. I2. For all characters with an odd (right-to-left) embedding direction,
  42717. those of type L, EN or AN go up one level.
  42718. */
  42719. for (i = 0; i < strLength; ++i) {
  42720. t = types[i];
  42721. if (isEven(levels[i])) {
  42722. if (t === 'R') {
  42723. levels[i] += 1;
  42724. } else if (t === 'AN' || t === 'EN') {
  42725. levels[i] += 2;
  42726. }
  42727. } else { // isOdd
  42728. if (t === 'L' || t === 'AN' || t === 'EN') {
  42729. levels[i] += 1;
  42730. }
  42731. }
  42732. }
  42733. /*
  42734. L1. On each line, reset the embedding level of the following characters to
  42735. the paragraph embedding level:
  42736. segment separators,
  42737. paragraph separators,
  42738. any sequence of whitespace characters preceding a segment separator or
  42739. paragraph separator, and any sequence of white space characters at the end
  42740. of the line.
  42741. */
  42742. // don't bother as text is only single line
  42743. /*
  42744. L2. From the highest level found in the text to the lowest odd level on
  42745. each line, reverse any contiguous sequence of characters that are at that
  42746. level or higher.
  42747. */
  42748. // find highest level & lowest odd level
  42749. var highestLevel = -1;
  42750. var lowestOddLevel = 99;
  42751. var level;
  42752. for (i = 0, ii = levels.length; i < ii; ++i) {
  42753. level = levels[i];
  42754. if (highestLevel < level) {
  42755. highestLevel = level;
  42756. }
  42757. if (lowestOddLevel > level && isOdd(level)) {
  42758. lowestOddLevel = level;
  42759. }
  42760. }
  42761. // now reverse between those limits
  42762. for (level = highestLevel; level >= lowestOddLevel; --level) {
  42763. // find segments to reverse
  42764. var start = -1;
  42765. for (i = 0, ii = levels.length; i < ii; ++i) {
  42766. if (levels[i] < level) {
  42767. if (start >= 0) {
  42768. reverseValues(chars, start, i);
  42769. start = -1;
  42770. }
  42771. } else if (start < 0) {
  42772. start = i;
  42773. }
  42774. }
  42775. if (start >= 0) {
  42776. reverseValues(chars, start, levels.length);
  42777. }
  42778. }
  42779. /*
  42780. L3. Combining marks applied to a right-to-left base character will at this
  42781. point precede their base character. If the rendering engine expects them to
  42782. follow the base characters in the final display process, then the ordering
  42783. of the marks and the base character must be reversed.
  42784. */
  42785. // don't bother for now
  42786. /*
  42787. L4. A character that possesses the mirrored property as specified by
  42788. Section 4.7, Mirrored, must be depicted by a mirrored glyph if the resolved
  42789. directionality of that character is R.
  42790. */
  42791. // don't mirror as characters are already mirrored in the pdf
  42792. // Finally, return string
  42793. for (i = 0, ii = chars.length; i < ii; ++i) {
  42794. var ch = chars[i];
  42795. if (ch === '<' || ch === '>') {
  42796. chars[i] = '';
  42797. }
  42798. }
  42799. return createBidiText(chars.join(''), isLTR);
  42800. }
  42801. return bidi;
  42802. })();
  42803. var MurmurHash3_64 = (function MurmurHash3_64Closure (seed) {
  42804. // Workaround for missing math precison in JS.
  42805. var MASK_HIGH = 0xffff0000;
  42806. var MASK_LOW = 0xffff;
  42807. function MurmurHash3_64 (seed) {
  42808. var SEED = 0xc3d2e1f0;
  42809. this.h1 = seed ? seed & 0xffffffff : SEED;
  42810. this.h2 = seed ? seed & 0xffffffff : SEED;
  42811. }
  42812. var alwaysUseUint32ArrayView = false;
  42813. // old webkits have issues with non-aligned arrays
  42814. try {
  42815. new Uint32Array(new Uint8Array(5).buffer, 0, 1);
  42816. } catch (e) {
  42817. alwaysUseUint32ArrayView = true;
  42818. }
  42819. MurmurHash3_64.prototype = {
  42820. update: function MurmurHash3_64_update(input) {
  42821. var useUint32ArrayView = alwaysUseUint32ArrayView;
  42822. var i;
  42823. if (typeof input === 'string') {
  42824. var data = new Uint8Array(input.length * 2);
  42825. var length = 0;
  42826. for (i = 0; i < input.length; i++) {
  42827. var code = input.charCodeAt(i);
  42828. if (code <= 0xff) {
  42829. data[length++] = code;
  42830. }
  42831. else {
  42832. data[length++] = code >>> 8;
  42833. data[length++] = code & 0xff;
  42834. }
  42835. }
  42836. } else if (input instanceof Uint8Array) {
  42837. data = input;
  42838. length = data.length;
  42839. } else if (typeof input === 'object' && ('length' in input)) {
  42840. // processing regular arrays as well, e.g. for IE9
  42841. data = input;
  42842. length = data.length;
  42843. useUint32ArrayView = true;
  42844. } else {
  42845. throw new Error('Wrong data format in MurmurHash3_64_update. ' +
  42846. 'Input must be a string or array.');
  42847. }
  42848. var blockCounts = length >> 2;
  42849. var tailLength = length - blockCounts * 4;
  42850. // we don't care about endianness here
  42851. var dataUint32 = useUint32ArrayView ?
  42852. new Uint32ArrayView(data, blockCounts) :
  42853. new Uint32Array(data.buffer, 0, blockCounts);
  42854. var k1 = 0;
  42855. var k2 = 0;
  42856. var h1 = this.h1;
  42857. var h2 = this.h2;
  42858. var C1 = 0xcc9e2d51;
  42859. var C2 = 0x1b873593;
  42860. var C1_LOW = C1 & MASK_LOW;
  42861. var C2_LOW = C2 & MASK_LOW;
  42862. for (i = 0; i < blockCounts; i++) {
  42863. if (i & 1) {
  42864. k1 = dataUint32[i];
  42865. k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);
  42866. k1 = k1 << 15 | k1 >>> 17;
  42867. k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);
  42868. h1 ^= k1;
  42869. h1 = h1 << 13 | h1 >>> 19;
  42870. h1 = h1 * 5 + 0xe6546b64;
  42871. } else {
  42872. k2 = dataUint32[i];
  42873. k2 = (k2 * C1 & MASK_HIGH) | (k2 * C1_LOW & MASK_LOW);
  42874. k2 = k2 << 15 | k2 >>> 17;
  42875. k2 = (k2 * C2 & MASK_HIGH) | (k2 * C2_LOW & MASK_LOW);
  42876. h2 ^= k2;
  42877. h2 = h2 << 13 | h2 >>> 19;
  42878. h2 = h2 * 5 + 0xe6546b64;
  42879. }
  42880. }
  42881. k1 = 0;
  42882. switch (tailLength) {
  42883. case 3:
  42884. k1 ^= data[blockCounts * 4 + 2] << 16;
  42885. /* falls through */
  42886. case 2:
  42887. k1 ^= data[blockCounts * 4 + 1] << 8;
  42888. /* falls through */
  42889. case 1:
  42890. k1 ^= data[blockCounts * 4];
  42891. /* falls through */
  42892. k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);
  42893. k1 = k1 << 15 | k1 >>> 17;
  42894. k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);
  42895. if (blockCounts & 1) {
  42896. h1 ^= k1;
  42897. } else {
  42898. h2 ^= k1;
  42899. }
  42900. }
  42901. this.h1 = h1;
  42902. this.h2 = h2;
  42903. return this;
  42904. },
  42905. hexdigest: function MurmurHash3_64_hexdigest () {
  42906. var h1 = this.h1;
  42907. var h2 = this.h2;
  42908. h1 ^= h2 >>> 1;
  42909. h1 = (h1 * 0xed558ccd & MASK_HIGH) | (h1 * 0x8ccd & MASK_LOW);
  42910. h2 = (h2 * 0xff51afd7 & MASK_HIGH) |
  42911. (((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16);
  42912. h1 ^= h2 >>> 1;
  42913. h1 = (h1 * 0x1a85ec53 & MASK_HIGH) | (h1 * 0xec53 & MASK_LOW);
  42914. h2 = (h2 * 0xc4ceb9fe & MASK_HIGH) |
  42915. (((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16);
  42916. h1 ^= h2 >>> 1;
  42917. for (var i = 0, arr = [h1, h2], str = ''; i < arr.length; i++) {
  42918. var hex = (arr[i] >>> 0).toString(16);
  42919. while (hex.length < 8) {
  42920. hex = '0' + hex;
  42921. }
  42922. str += hex;
  42923. }
  42924. return str;
  42925. }
  42926. };
  42927. return MurmurHash3_64;
  42928. })();
  42929. }).call((typeof window === 'undefined') ? this : window);
  42930. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  42931. // workerSrc is not set -- using last script url to define default location
  42932. PDFJS.workerSrc = (function () {
  42933. 'use strict';
  42934. var scriptTagContainer = document.body ||
  42935. document.getElementsByTagName('head')[0];
  42936. var pdfjsSrc = scriptTagContainer.lastChild.src;
  42937. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  42938. })();
  42939. }