pdf.combined.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021
  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.280';
  24. PDFJS.build = '7d4303b';
  25. (function pdfjsWrapper() {
  26. // Use strict in our context only - users might not want it
  27. 'use strict';
  28. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  29. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  30. /* Copyright 2012 Mozilla Foundation
  31. *
  32. * Licensed under the Apache License, Version 2.0 (the "License");
  33. * you may not use this file except in compliance with the License.
  34. * You may obtain a copy of the License at
  35. *
  36. * http://www.apache.org/licenses/LICENSE-2.0
  37. *
  38. * Unless required by applicable law or agreed to in writing, software
  39. * distributed under the License is distributed on an "AS IS" BASIS,
  40. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41. * See the License for the specific language governing permissions and
  42. * limitations under the License.
  43. */
  44. /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
  45. Promise */
  46. 'use strict';
  47. var globalScope = (typeof window === 'undefined') ? this : window;
  48. var isWorker = (typeof window === 'undefined');
  49. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  50. var TextRenderingMode = {
  51. FILL: 0,
  52. STROKE: 1,
  53. FILL_STROKE: 2,
  54. INVISIBLE: 3,
  55. FILL_ADD_TO_PATH: 4,
  56. STROKE_ADD_TO_PATH: 5,
  57. FILL_STROKE_ADD_TO_PATH: 6,
  58. ADD_TO_PATH: 7,
  59. FILL_STROKE_MASK: 3,
  60. ADD_TO_PATH_FLAG: 4
  61. };
  62. var ImageKind = {
  63. GRAYSCALE_1BPP: 1,
  64. RGB_24BPP: 2,
  65. RGBA_32BPP: 3
  66. };
  67. var AnnotationType = {
  68. WIDGET: 1,
  69. TEXT: 2,
  70. LINK: 3
  71. };
  72. var AnnotationBorderStyleType = {
  73. SOLID: 1,
  74. DASHED: 2,
  75. BEVELED: 3,
  76. INSET: 4,
  77. UNDERLINE: 5
  78. };
  79. var StreamType = {
  80. UNKNOWN: 0,
  81. FLATE: 1,
  82. LZW: 2,
  83. DCT: 3,
  84. JPX: 4,
  85. JBIG: 5,
  86. A85: 6,
  87. AHX: 7,
  88. CCF: 8,
  89. RL: 9
  90. };
  91. var FontType = {
  92. UNKNOWN: 0,
  93. TYPE1: 1,
  94. TYPE1C: 2,
  95. CIDFONTTYPE0: 3,
  96. CIDFONTTYPE0C: 4,
  97. TRUETYPE: 5,
  98. CIDFONTTYPE2: 6,
  99. TYPE3: 7,
  100. OPENTYPE: 8,
  101. TYPE0: 9,
  102. MMTYPE1: 10
  103. };
  104. // The global PDFJS object exposes the API
  105. // In production, it will be declared outside a global wrapper
  106. // In development, it will be declared here
  107. if (!globalScope.PDFJS) {
  108. globalScope.PDFJS = {};
  109. }
  110. globalScope.PDFJS.pdfBug = false;
  111. PDFJS.VERBOSITY_LEVELS = {
  112. errors: 0,
  113. warnings: 1,
  114. infos: 5
  115. };
  116. // All the possible operations for an operator list.
  117. var OPS = PDFJS.OPS = {
  118. // Intentionally start from 1 so it is easy to spot bad operators that will be
  119. // 0's.
  120. dependency: 1,
  121. setLineWidth: 2,
  122. setLineCap: 3,
  123. setLineJoin: 4,
  124. setMiterLimit: 5,
  125. setDash: 6,
  126. setRenderingIntent: 7,
  127. setFlatness: 8,
  128. setGState: 9,
  129. save: 10,
  130. restore: 11,
  131. transform: 12,
  132. moveTo: 13,
  133. lineTo: 14,
  134. curveTo: 15,
  135. curveTo2: 16,
  136. curveTo3: 17,
  137. closePath: 18,
  138. rectangle: 19,
  139. stroke: 20,
  140. closeStroke: 21,
  141. fill: 22,
  142. eoFill: 23,
  143. fillStroke: 24,
  144. eoFillStroke: 25,
  145. closeFillStroke: 26,
  146. closeEOFillStroke: 27,
  147. endPath: 28,
  148. clip: 29,
  149. eoClip: 30,
  150. beginText: 31,
  151. endText: 32,
  152. setCharSpacing: 33,
  153. setWordSpacing: 34,
  154. setHScale: 35,
  155. setLeading: 36,
  156. setFont: 37,
  157. setTextRenderingMode: 38,
  158. setTextRise: 39,
  159. moveText: 40,
  160. setLeadingMoveText: 41,
  161. setTextMatrix: 42,
  162. nextLine: 43,
  163. showText: 44,
  164. showSpacedText: 45,
  165. nextLineShowText: 46,
  166. nextLineSetSpacingShowText: 47,
  167. setCharWidth: 48,
  168. setCharWidthAndBounds: 49,
  169. setStrokeColorSpace: 50,
  170. setFillColorSpace: 51,
  171. setStrokeColor: 52,
  172. setStrokeColorN: 53,
  173. setFillColor: 54,
  174. setFillColorN: 55,
  175. setStrokeGray: 56,
  176. setFillGray: 57,
  177. setStrokeRGBColor: 58,
  178. setFillRGBColor: 59,
  179. setStrokeCMYKColor: 60,
  180. setFillCMYKColor: 61,
  181. shadingFill: 62,
  182. beginInlineImage: 63,
  183. beginImageData: 64,
  184. endInlineImage: 65,
  185. paintXObject: 66,
  186. markPoint: 67,
  187. markPointProps: 68,
  188. beginMarkedContent: 69,
  189. beginMarkedContentProps: 70,
  190. endMarkedContent: 71,
  191. beginCompat: 72,
  192. endCompat: 73,
  193. paintFormXObjectBegin: 74,
  194. paintFormXObjectEnd: 75,
  195. beginGroup: 76,
  196. endGroup: 77,
  197. beginAnnotations: 78,
  198. endAnnotations: 79,
  199. beginAnnotation: 80,
  200. endAnnotation: 81,
  201. paintJpegXObject: 82,
  202. paintImageMaskXObject: 83,
  203. paintImageMaskXObjectGroup: 84,
  204. paintImageXObject: 85,
  205. paintInlineImageXObject: 86,
  206. paintInlineImageXObjectGroup: 87,
  207. paintImageXObjectRepeat: 88,
  208. paintImageMaskXObjectRepeat: 89,
  209. paintSolidColorImageMask: 90,
  210. constructPath: 91
  211. };
  212. // A notice for devs. These are good for things that are helpful to devs, such
  213. // as warning that Workers were disabled, which is important to devs but not
  214. // end users.
  215. function info(msg) {
  216. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
  217. console.log('Info: ' + msg);
  218. }
  219. }
  220. // Non-fatal warnings.
  221. function warn(msg) {
  222. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
  223. console.log('Warning: ' + msg);
  224. }
  225. }
  226. // Fatal errors that should trigger the fallback UI and halt execution by
  227. // throwing an exception.
  228. function error(msg) {
  229. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) {
  230. console.log('Error: ' + msg);
  231. console.log(backtrace());
  232. }
  233. UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
  234. throw new Error(msg);
  235. }
  236. function backtrace() {
  237. try {
  238. throw new Error();
  239. } catch (e) {
  240. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  241. }
  242. }
  243. function assert(cond, msg) {
  244. if (!cond) {
  245. error(msg);
  246. }
  247. }
  248. var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
  249. unknown: 'unknown',
  250. forms: 'forms',
  251. javaScript: 'javaScript',
  252. smask: 'smask',
  253. shadingPattern: 'shadingPattern',
  254. font: 'font'
  255. };
  256. var UnsupportedManager = PDFJS.UnsupportedManager =
  257. (function UnsupportedManagerClosure() {
  258. var listeners = [];
  259. return {
  260. listen: function (cb) {
  261. listeners.push(cb);
  262. },
  263. notify: function (featureId) {
  264. warn('Unsupported feature "' + featureId + '"');
  265. for (var i = 0, ii = listeners.length; i < ii; i++) {
  266. listeners[i](featureId);
  267. }
  268. }
  269. };
  270. })();
  271. // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
  272. // absolute URL, it will be returned as is.
  273. function combineUrl(baseUrl, url) {
  274. if (!url) {
  275. return baseUrl;
  276. }
  277. if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
  278. return url;
  279. }
  280. var i;
  281. if (url.charAt(0) === '/') {
  282. // absolute path
  283. i = baseUrl.indexOf('://');
  284. if (url.charAt(1) === '/') {
  285. ++i;
  286. } else {
  287. i = baseUrl.indexOf('/', i + 3);
  288. }
  289. return baseUrl.substring(0, i) + url;
  290. } else {
  291. // relative path
  292. var pathLength = baseUrl.length;
  293. i = baseUrl.lastIndexOf('#');
  294. pathLength = i >= 0 ? i : pathLength;
  295. i = baseUrl.lastIndexOf('?', pathLength);
  296. pathLength = i >= 0 ? i : pathLength;
  297. var prefixLength = baseUrl.lastIndexOf('/', pathLength);
  298. return baseUrl.substring(0, prefixLength + 1) + url;
  299. }
  300. }
  301. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  302. function isValidUrl(url, allowRelative) {
  303. if (!url) {
  304. return false;
  305. }
  306. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  307. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  308. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  309. if (!protocol) {
  310. return allowRelative;
  311. }
  312. protocol = protocol[0].toLowerCase();
  313. switch (protocol) {
  314. case 'http':
  315. case 'https':
  316. case 'ftp':
  317. case 'mailto':
  318. case 'tel':
  319. return true;
  320. default:
  321. return false;
  322. }
  323. }
  324. PDFJS.isValidUrl = isValidUrl;
  325. function shadow(obj, prop, value) {
  326. Object.defineProperty(obj, prop, { value: value,
  327. enumerable: true,
  328. configurable: true,
  329. writable: false });
  330. return value;
  331. }
  332. PDFJS.shadow = shadow;
  333. var PasswordResponses = PDFJS.PasswordResponses = {
  334. NEED_PASSWORD: 1,
  335. INCORRECT_PASSWORD: 2
  336. };
  337. var PasswordException = (function PasswordExceptionClosure() {
  338. function PasswordException(msg, code) {
  339. this.name = 'PasswordException';
  340. this.message = msg;
  341. this.code = code;
  342. }
  343. PasswordException.prototype = new Error();
  344. PasswordException.constructor = PasswordException;
  345. return PasswordException;
  346. })();
  347. PDFJS.PasswordException = PasswordException;
  348. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  349. function UnknownErrorException(msg, details) {
  350. this.name = 'UnknownErrorException';
  351. this.message = msg;
  352. this.details = details;
  353. }
  354. UnknownErrorException.prototype = new Error();
  355. UnknownErrorException.constructor = UnknownErrorException;
  356. return UnknownErrorException;
  357. })();
  358. PDFJS.UnknownErrorException = UnknownErrorException;
  359. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  360. function InvalidPDFException(msg) {
  361. this.name = 'InvalidPDFException';
  362. this.message = msg;
  363. }
  364. InvalidPDFException.prototype = new Error();
  365. InvalidPDFException.constructor = InvalidPDFException;
  366. return InvalidPDFException;
  367. })();
  368. PDFJS.InvalidPDFException = InvalidPDFException;
  369. var MissingPDFException = (function MissingPDFExceptionClosure() {
  370. function MissingPDFException(msg) {
  371. this.name = 'MissingPDFException';
  372. this.message = msg;
  373. }
  374. MissingPDFException.prototype = new Error();
  375. MissingPDFException.constructor = MissingPDFException;
  376. return MissingPDFException;
  377. })();
  378. PDFJS.MissingPDFException = MissingPDFException;
  379. var UnexpectedResponseException =
  380. (function UnexpectedResponseExceptionClosure() {
  381. function UnexpectedResponseException(msg, status) {
  382. this.name = 'UnexpectedResponseException';
  383. this.message = msg;
  384. this.status = status;
  385. }
  386. UnexpectedResponseException.prototype = new Error();
  387. UnexpectedResponseException.constructor = UnexpectedResponseException;
  388. return UnexpectedResponseException;
  389. })();
  390. PDFJS.UnexpectedResponseException = UnexpectedResponseException;
  391. var NotImplementedException = (function NotImplementedExceptionClosure() {
  392. function NotImplementedException(msg) {
  393. this.message = msg;
  394. }
  395. NotImplementedException.prototype = new Error();
  396. NotImplementedException.prototype.name = 'NotImplementedException';
  397. NotImplementedException.constructor = NotImplementedException;
  398. return NotImplementedException;
  399. })();
  400. var MissingDataException = (function MissingDataExceptionClosure() {
  401. function MissingDataException(begin, end) {
  402. this.begin = begin;
  403. this.end = end;
  404. this.message = 'Missing data [' + begin + ', ' + end + ')';
  405. }
  406. MissingDataException.prototype = new Error();
  407. MissingDataException.prototype.name = 'MissingDataException';
  408. MissingDataException.constructor = MissingDataException;
  409. return MissingDataException;
  410. })();
  411. var XRefParseException = (function XRefParseExceptionClosure() {
  412. function XRefParseException(msg) {
  413. this.message = msg;
  414. }
  415. XRefParseException.prototype = new Error();
  416. XRefParseException.prototype.name = 'XRefParseException';
  417. XRefParseException.constructor = XRefParseException;
  418. return XRefParseException;
  419. })();
  420. function bytesToString(bytes) {
  421. assert(bytes !== null && typeof bytes === 'object' &&
  422. bytes.length !== undefined, 'Invalid argument for bytesToString');
  423. var length = bytes.length;
  424. var MAX_ARGUMENT_COUNT = 8192;
  425. if (length < MAX_ARGUMENT_COUNT) {
  426. return String.fromCharCode.apply(null, bytes);
  427. }
  428. var strBuf = [];
  429. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  430. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  431. var chunk = bytes.subarray(i, chunkEnd);
  432. strBuf.push(String.fromCharCode.apply(null, chunk));
  433. }
  434. return strBuf.join('');
  435. }
  436. function stringToBytes(str) {
  437. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  438. var length = str.length;
  439. var bytes = new Uint8Array(length);
  440. for (var i = 0; i < length; ++i) {
  441. bytes[i] = str.charCodeAt(i) & 0xFF;
  442. }
  443. return bytes;
  444. }
  445. function string32(value) {
  446. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  447. (value >> 8) & 0xff, value & 0xff);
  448. }
  449. function log2(x) {
  450. var n = 1, i = 0;
  451. while (x > n) {
  452. n <<= 1;
  453. i++;
  454. }
  455. return i;
  456. }
  457. function readInt8(data, start) {
  458. return (data[start] << 24) >> 24;
  459. }
  460. function readUint16(data, offset) {
  461. return (data[offset] << 8) | data[offset + 1];
  462. }
  463. function readUint32(data, offset) {
  464. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  465. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  466. }
  467. // Lazy test the endianness of the platform
  468. // NOTE: This will be 'true' for simulated TypedArrays
  469. function isLittleEndian() {
  470. var buffer8 = new Uint8Array(2);
  471. buffer8[0] = 1;
  472. var buffer16 = new Uint16Array(buffer8.buffer);
  473. return (buffer16[0] === 1);
  474. }
  475. Object.defineProperty(PDFJS, 'isLittleEndian', {
  476. configurable: true,
  477. get: function PDFJS_isLittleEndian() {
  478. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  479. }
  480. });
  481. // Lazy test if the userAgent support CanvasTypedArrays
  482. function hasCanvasTypedArrays() {
  483. var canvas = document.createElement('canvas');
  484. canvas.width = canvas.height = 1;
  485. var ctx = canvas.getContext('2d');
  486. var imageData = ctx.createImageData(1, 1);
  487. return (typeof imageData.data.buffer !== 'undefined');
  488. }
  489. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  490. configurable: true,
  491. get: function PDFJS_hasCanvasTypedArrays() {
  492. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  493. }
  494. });
  495. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  496. function Uint32ArrayView(buffer, length) {
  497. this.buffer = buffer;
  498. this.byteLength = buffer.length;
  499. this.length = length === undefined ? (this.byteLength >> 2) : length;
  500. ensureUint32ArrayViewProps(this.length);
  501. }
  502. Uint32ArrayView.prototype = Object.create(null);
  503. var uint32ArrayViewSetters = 0;
  504. function createUint32ArrayProp(index) {
  505. return {
  506. get: function () {
  507. var buffer = this.buffer, offset = index << 2;
  508. return (buffer[offset] | (buffer[offset + 1] << 8) |
  509. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  510. },
  511. set: function (value) {
  512. var buffer = this.buffer, offset = index << 2;
  513. buffer[offset] = value & 255;
  514. buffer[offset + 1] = (value >> 8) & 255;
  515. buffer[offset + 2] = (value >> 16) & 255;
  516. buffer[offset + 3] = (value >>> 24) & 255;
  517. }
  518. };
  519. }
  520. function ensureUint32ArrayViewProps(length) {
  521. while (uint32ArrayViewSetters < length) {
  522. Object.defineProperty(Uint32ArrayView.prototype,
  523. uint32ArrayViewSetters,
  524. createUint32ArrayProp(uint32ArrayViewSetters));
  525. uint32ArrayViewSetters++;
  526. }
  527. }
  528. return Uint32ArrayView;
  529. })();
  530. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  531. var Util = PDFJS.Util = (function UtilClosure() {
  532. function Util() {}
  533. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  534. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  535. // creating many intermediate strings.
  536. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  537. rgbBuf[1] = r;
  538. rgbBuf[3] = g;
  539. rgbBuf[5] = b;
  540. return rgbBuf.join('');
  541. };
  542. // Concatenates two transformation matrices together and returns the result.
  543. Util.transform = function Util_transform(m1, m2) {
  544. return [
  545. m1[0] * m2[0] + m1[2] * m2[1],
  546. m1[1] * m2[0] + m1[3] * m2[1],
  547. m1[0] * m2[2] + m1[2] * m2[3],
  548. m1[1] * m2[2] + m1[3] * m2[3],
  549. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  550. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  551. ];
  552. };
  553. // For 2d affine transforms
  554. Util.applyTransform = function Util_applyTransform(p, m) {
  555. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  556. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  557. return [xt, yt];
  558. };
  559. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  560. var d = m[0] * m[3] - m[1] * m[2];
  561. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  562. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  563. return [xt, yt];
  564. };
  565. // Applies the transform to the rectangle and finds the minimum axially
  566. // aligned bounding box.
  567. Util.getAxialAlignedBoundingBox =
  568. function Util_getAxialAlignedBoundingBox(r, m) {
  569. var p1 = Util.applyTransform(r, m);
  570. var p2 = Util.applyTransform(r.slice(2, 4), m);
  571. var p3 = Util.applyTransform([r[0], r[3]], m);
  572. var p4 = Util.applyTransform([r[2], r[1]], m);
  573. return [
  574. Math.min(p1[0], p2[0], p3[0], p4[0]),
  575. Math.min(p1[1], p2[1], p3[1], p4[1]),
  576. Math.max(p1[0], p2[0], p3[0], p4[0]),
  577. Math.max(p1[1], p2[1], p3[1], p4[1])
  578. ];
  579. };
  580. Util.inverseTransform = function Util_inverseTransform(m) {
  581. var d = m[0] * m[3] - m[1] * m[2];
  582. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  583. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  584. };
  585. // Apply a generic 3d matrix M on a 3-vector v:
  586. // | a b c | | X |
  587. // | d e f | x | Y |
  588. // | g h i | | Z |
  589. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  590. // with v as [X,Y,Z]
  591. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  592. return [
  593. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  594. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  595. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  596. ];
  597. };
  598. // This calculation uses Singular Value Decomposition.
  599. // The SVD can be represented with formula A = USV. We are interested in the
  600. // matrix S here because it represents the scale values.
  601. Util.singularValueDecompose2dScale =
  602. function Util_singularValueDecompose2dScale(m) {
  603. var transpose = [m[0], m[2], m[1], m[3]];
  604. // Multiply matrix m with its transpose.
  605. var a = m[0] * transpose[0] + m[1] * transpose[2];
  606. var b = m[0] * transpose[1] + m[1] * transpose[3];
  607. var c = m[2] * transpose[0] + m[3] * transpose[2];
  608. var d = m[2] * transpose[1] + m[3] * transpose[3];
  609. // Solve the second degree polynomial to get roots.
  610. var first = (a + d) / 2;
  611. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  612. var sx = first + second || 1;
  613. var sy = first - second || 1;
  614. // Scale values are the square roots of the eigenvalues.
  615. return [Math.sqrt(sx), Math.sqrt(sy)];
  616. };
  617. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  618. // For coordinate systems whose origin lies in the bottom-left, this
  619. // means normalization to (BL,TR) ordering. For systems with origin in the
  620. // top-left, this means (TL,BR) ordering.
  621. Util.normalizeRect = function Util_normalizeRect(rect) {
  622. var r = rect.slice(0); // clone rect
  623. if (rect[0] > rect[2]) {
  624. r[0] = rect[2];
  625. r[2] = rect[0];
  626. }
  627. if (rect[1] > rect[3]) {
  628. r[1] = rect[3];
  629. r[3] = rect[1];
  630. }
  631. return r;
  632. };
  633. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  634. // intersection of rect1 and rect2. If no intersection, returns 'false'
  635. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  636. Util.intersect = function Util_intersect(rect1, rect2) {
  637. function compare(a, b) {
  638. return a - b;
  639. }
  640. // Order points along the axes
  641. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  642. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  643. result = [];
  644. rect1 = Util.normalizeRect(rect1);
  645. rect2 = Util.normalizeRect(rect2);
  646. // X: first and second points belong to different rectangles?
  647. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  648. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  649. // Intersection must be between second and third points
  650. result[0] = orderedX[1];
  651. result[2] = orderedX[2];
  652. } else {
  653. return false;
  654. }
  655. // Y: first and second points belong to different rectangles?
  656. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  657. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  658. // Intersection must be between second and third points
  659. result[1] = orderedY[1];
  660. result[3] = orderedY[2];
  661. } else {
  662. return false;
  663. }
  664. return result;
  665. };
  666. Util.sign = function Util_sign(num) {
  667. return num < 0 ? -1 : 1;
  668. };
  669. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  670. Array.prototype.push.apply(arr1, arr2);
  671. };
  672. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  673. Array.prototype.unshift.apply(arr1, arr2);
  674. };
  675. Util.extendObj = function extendObj(obj1, obj2) {
  676. for (var key in obj2) {
  677. obj1[key] = obj2[key];
  678. }
  679. };
  680. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  681. name) {
  682. while (dict && !dict.has(name)) {
  683. dict = dict.get('Parent');
  684. }
  685. if (!dict) {
  686. return null;
  687. }
  688. return dict.get(name);
  689. };
  690. Util.inherit = function Util_inherit(sub, base, prototype) {
  691. sub.prototype = Object.create(base.prototype);
  692. sub.prototype.constructor = sub;
  693. for (var prop in prototype) {
  694. sub.prototype[prop] = prototype[prop];
  695. }
  696. };
  697. Util.loadScript = function Util_loadScript(src, callback) {
  698. var script = document.createElement('script');
  699. var loaded = false;
  700. script.setAttribute('src', src);
  701. if (callback) {
  702. script.onload = function() {
  703. if (!loaded) {
  704. callback();
  705. }
  706. loaded = true;
  707. };
  708. }
  709. document.getElementsByTagName('head')[0].appendChild(script);
  710. };
  711. return Util;
  712. })();
  713. /**
  714. * PDF page viewport created based on scale, rotation and offset.
  715. * @class
  716. * @alias PDFJS.PageViewport
  717. */
  718. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  719. /**
  720. * @constructor
  721. * @private
  722. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  723. * @param scale {number} scale of the viewport.
  724. * @param rotation {number} rotations of the viewport in degrees.
  725. * @param offsetX {number} offset X
  726. * @param offsetY {number} offset Y
  727. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  728. */
  729. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  730. this.viewBox = viewBox;
  731. this.scale = scale;
  732. this.rotation = rotation;
  733. this.offsetX = offsetX;
  734. this.offsetY = offsetY;
  735. // creating transform to convert pdf coordinate system to the normal
  736. // canvas like coordinates taking in account scale and rotation
  737. var centerX = (viewBox[2] + viewBox[0]) / 2;
  738. var centerY = (viewBox[3] + viewBox[1]) / 2;
  739. var rotateA, rotateB, rotateC, rotateD;
  740. rotation = rotation % 360;
  741. rotation = rotation < 0 ? rotation + 360 : rotation;
  742. switch (rotation) {
  743. case 180:
  744. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  745. break;
  746. case 90:
  747. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  748. break;
  749. case 270:
  750. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  751. break;
  752. //case 0:
  753. default:
  754. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  755. break;
  756. }
  757. if (dontFlip) {
  758. rotateC = -rotateC; rotateD = -rotateD;
  759. }
  760. var offsetCanvasX, offsetCanvasY;
  761. var width, height;
  762. if (rotateA === 0) {
  763. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  764. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  765. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  766. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  767. } else {
  768. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  769. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  770. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  771. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  772. }
  773. // creating transform for the following operations:
  774. // translate(-centerX, -centerY), rotate and flip vertically,
  775. // scale, and translate(offsetCanvasX, offsetCanvasY)
  776. this.transform = [
  777. rotateA * scale,
  778. rotateB * scale,
  779. rotateC * scale,
  780. rotateD * scale,
  781. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  782. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  783. ];
  784. this.width = width;
  785. this.height = height;
  786. this.fontScale = scale;
  787. }
  788. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  789. /**
  790. * Clones viewport with additional properties.
  791. * @param args {Object} (optional) If specified, may contain the 'scale' or
  792. * 'rotation' properties to override the corresponding properties in
  793. * the cloned viewport.
  794. * @returns {PDFJS.PageViewport} Cloned viewport.
  795. */
  796. clone: function PageViewPort_clone(args) {
  797. args = args || {};
  798. var scale = 'scale' in args ? args.scale : this.scale;
  799. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  800. return new PageViewport(this.viewBox.slice(), scale, rotation,
  801. this.offsetX, this.offsetY, args.dontFlip);
  802. },
  803. /**
  804. * Converts PDF point to the viewport coordinates. For examples, useful for
  805. * converting PDF location into canvas pixel coordinates.
  806. * @param x {number} X coordinate.
  807. * @param y {number} Y coordinate.
  808. * @returns {Object} Object that contains 'x' and 'y' properties of the
  809. * point in the viewport coordinate space.
  810. * @see {@link convertToPdfPoint}
  811. * @see {@link convertToViewportRectangle}
  812. */
  813. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  814. return Util.applyTransform([x, y], this.transform);
  815. },
  816. /**
  817. * Converts PDF rectangle to the viewport coordinates.
  818. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  819. * @returns {Array} Contains corresponding coordinates of the rectangle
  820. * in the viewport coordinate space.
  821. * @see {@link convertToViewportPoint}
  822. */
  823. convertToViewportRectangle:
  824. function PageViewport_convertToViewportRectangle(rect) {
  825. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  826. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  827. return [tl[0], tl[1], br[0], br[1]];
  828. },
  829. /**
  830. * Converts viewport coordinates to the PDF location. For examples, useful
  831. * for converting canvas pixel location into PDF one.
  832. * @param x {number} X coordinate.
  833. * @param y {number} Y coordinate.
  834. * @returns {Object} Object that contains 'x' and 'y' properties of the
  835. * point in the PDF coordinate space.
  836. * @see {@link convertToViewportPoint}
  837. */
  838. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  839. return Util.applyInverseTransform([x, y], this.transform);
  840. }
  841. };
  842. return PageViewport;
  843. })();
  844. var PDFStringTranslateTable = [
  845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  846. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  847. 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,
  848. 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,
  849. 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,
  850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  851. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  852. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  853. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  854. ];
  855. function stringToPDFString(str) {
  856. var i, n = str.length, strBuf = [];
  857. if (str[0] === '\xFE' && str[1] === '\xFF') {
  858. // UTF16BE BOM
  859. for (i = 2; i < n; i += 2) {
  860. strBuf.push(String.fromCharCode(
  861. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  862. }
  863. } else {
  864. for (i = 0; i < n; ++i) {
  865. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  866. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  867. }
  868. }
  869. return strBuf.join('');
  870. }
  871. function stringToUTF8String(str) {
  872. return decodeURIComponent(escape(str));
  873. }
  874. function utf8StringToString(str) {
  875. return unescape(encodeURIComponent(str));
  876. }
  877. function isEmptyObj(obj) {
  878. for (var key in obj) {
  879. return false;
  880. }
  881. return true;
  882. }
  883. function isBool(v) {
  884. return typeof v === 'boolean';
  885. }
  886. function isInt(v) {
  887. return typeof v === 'number' && ((v | 0) === v);
  888. }
  889. function isNum(v) {
  890. return typeof v === 'number';
  891. }
  892. function isString(v) {
  893. return typeof v === 'string';
  894. }
  895. function isName(v) {
  896. return v instanceof Name;
  897. }
  898. function isCmd(v, cmd) {
  899. return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
  900. }
  901. function isDict(v, type) {
  902. if (!(v instanceof Dict)) {
  903. return false;
  904. }
  905. if (!type) {
  906. return true;
  907. }
  908. var dictType = v.get('Type');
  909. return isName(dictType) && dictType.name === type;
  910. }
  911. function isArray(v) {
  912. return v instanceof Array;
  913. }
  914. function isStream(v) {
  915. return typeof v === 'object' && v !== null && v.getBytes !== undefined;
  916. }
  917. function isArrayBuffer(v) {
  918. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  919. }
  920. function isRef(v) {
  921. return v instanceof Ref;
  922. }
  923. /**
  924. * Promise Capability object.
  925. *
  926. * @typedef {Object} PromiseCapability
  927. * @property {Promise} promise - A promise object.
  928. * @property {function} resolve - Fullfills the promise.
  929. * @property {function} reject - Rejects the promise.
  930. */
  931. /**
  932. * Creates a promise capability object.
  933. * @alias PDFJS.createPromiseCapability
  934. *
  935. * @return {PromiseCapability} A capability object contains:
  936. * - a Promise, resolve and reject methods.
  937. */
  938. function createPromiseCapability() {
  939. var capability = {};
  940. capability.promise = new Promise(function (resolve, reject) {
  941. capability.resolve = resolve;
  942. capability.reject = reject;
  943. });
  944. return capability;
  945. }
  946. PDFJS.createPromiseCapability = createPromiseCapability;
  947. /**
  948. * Polyfill for Promises:
  949. * The following promise implementation tries to generally implement the
  950. * Promise/A+ spec. Some notable differences from other promise libaries are:
  951. * - There currently isn't a seperate deferred and promise object.
  952. * - Unhandled rejections eventually show an error if they aren't handled.
  953. *
  954. * Based off of the work in:
  955. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  956. */
  957. (function PromiseClosure() {
  958. if (globalScope.Promise) {
  959. // Promises existing in the DOM/Worker, checking presence of all/resolve
  960. if (typeof globalScope.Promise.all !== 'function') {
  961. globalScope.Promise.all = function (iterable) {
  962. var count = 0, results = [], resolve, reject;
  963. var promise = new globalScope.Promise(function (resolve_, reject_) {
  964. resolve = resolve_;
  965. reject = reject_;
  966. });
  967. iterable.forEach(function (p, i) {
  968. count++;
  969. p.then(function (result) {
  970. results[i] = result;
  971. count--;
  972. if (count === 0) {
  973. resolve(results);
  974. }
  975. }, reject);
  976. });
  977. if (count === 0) {
  978. resolve(results);
  979. }
  980. return promise;
  981. };
  982. }
  983. if (typeof globalScope.Promise.resolve !== 'function') {
  984. globalScope.Promise.resolve = function (value) {
  985. return new globalScope.Promise(function (resolve) { resolve(value); });
  986. };
  987. }
  988. if (typeof globalScope.Promise.reject !== 'function') {
  989. globalScope.Promise.reject = function (reason) {
  990. return new globalScope.Promise(function (resolve, reject) {
  991. reject(reason);
  992. });
  993. };
  994. }
  995. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  996. globalScope.Promise.prototype.catch = function (onReject) {
  997. return globalScope.Promise.prototype.then(undefined, onReject);
  998. };
  999. }
  1000. return;
  1001. }
  1002. var STATUS_PENDING = 0;
  1003. var STATUS_RESOLVED = 1;
  1004. var STATUS_REJECTED = 2;
  1005. // In an attempt to avoid silent exceptions, unhandled rejections are
  1006. // tracked and if they aren't handled in a certain amount of time an
  1007. // error is logged.
  1008. var REJECTION_TIMEOUT = 500;
  1009. var HandlerManager = {
  1010. handlers: [],
  1011. running: false,
  1012. unhandledRejections: [],
  1013. pendingRejectionCheck: false,
  1014. scheduleHandlers: function scheduleHandlers(promise) {
  1015. if (promise._status === STATUS_PENDING) {
  1016. return;
  1017. }
  1018. this.handlers = this.handlers.concat(promise._handlers);
  1019. promise._handlers = [];
  1020. if (this.running) {
  1021. return;
  1022. }
  1023. this.running = true;
  1024. setTimeout(this.runHandlers.bind(this), 0);
  1025. },
  1026. runHandlers: function runHandlers() {
  1027. var RUN_TIMEOUT = 1; // ms
  1028. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1029. while (this.handlers.length > 0) {
  1030. var handler = this.handlers.shift();
  1031. var nextStatus = handler.thisPromise._status;
  1032. var nextValue = handler.thisPromise._value;
  1033. try {
  1034. if (nextStatus === STATUS_RESOLVED) {
  1035. if (typeof handler.onResolve === 'function') {
  1036. nextValue = handler.onResolve(nextValue);
  1037. }
  1038. } else if (typeof handler.onReject === 'function') {
  1039. nextValue = handler.onReject(nextValue);
  1040. nextStatus = STATUS_RESOLVED;
  1041. if (handler.thisPromise._unhandledRejection) {
  1042. this.removeUnhandeledRejection(handler.thisPromise);
  1043. }
  1044. }
  1045. } catch (ex) {
  1046. nextStatus = STATUS_REJECTED;
  1047. nextValue = ex;
  1048. }
  1049. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1050. if (Date.now() >= timeoutAt) {
  1051. break;
  1052. }
  1053. }
  1054. if (this.handlers.length > 0) {
  1055. setTimeout(this.runHandlers.bind(this), 0);
  1056. return;
  1057. }
  1058. this.running = false;
  1059. },
  1060. addUnhandledRejection: function addUnhandledRejection(promise) {
  1061. this.unhandledRejections.push({
  1062. promise: promise,
  1063. time: Date.now()
  1064. });
  1065. this.scheduleRejectionCheck();
  1066. },
  1067. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1068. promise._unhandledRejection = false;
  1069. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1070. if (this.unhandledRejections[i].promise === promise) {
  1071. this.unhandledRejections.splice(i);
  1072. i--;
  1073. }
  1074. }
  1075. },
  1076. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1077. if (this.pendingRejectionCheck) {
  1078. return;
  1079. }
  1080. this.pendingRejectionCheck = true;
  1081. setTimeout(function rejectionCheck() {
  1082. this.pendingRejectionCheck = false;
  1083. var now = Date.now();
  1084. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1085. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1086. var unhandled = this.unhandledRejections[i].promise._value;
  1087. var msg = 'Unhandled rejection: ' + unhandled;
  1088. if (unhandled.stack) {
  1089. msg += '\n' + unhandled.stack;
  1090. }
  1091. warn(msg);
  1092. this.unhandledRejections.splice(i);
  1093. i--;
  1094. }
  1095. }
  1096. if (this.unhandledRejections.length) {
  1097. this.scheduleRejectionCheck();
  1098. }
  1099. }.bind(this), REJECTION_TIMEOUT);
  1100. }
  1101. };
  1102. function Promise(resolver) {
  1103. this._status = STATUS_PENDING;
  1104. this._handlers = [];
  1105. try {
  1106. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1107. } catch (e) {
  1108. this._reject(e);
  1109. }
  1110. }
  1111. /**
  1112. * Builds a promise that is resolved when all the passed in promises are
  1113. * resolved.
  1114. * @param {array} array of data and/or promises to wait for.
  1115. * @return {Promise} New dependant promise.
  1116. */
  1117. Promise.all = function Promise_all(promises) {
  1118. var resolveAll, rejectAll;
  1119. var deferred = new Promise(function (resolve, reject) {
  1120. resolveAll = resolve;
  1121. rejectAll = reject;
  1122. });
  1123. var unresolved = promises.length;
  1124. var results = [];
  1125. if (unresolved === 0) {
  1126. resolveAll(results);
  1127. return deferred;
  1128. }
  1129. function reject(reason) {
  1130. if (deferred._status === STATUS_REJECTED) {
  1131. return;
  1132. }
  1133. results = [];
  1134. rejectAll(reason);
  1135. }
  1136. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1137. var promise = promises[i];
  1138. var resolve = (function(i) {
  1139. return function(value) {
  1140. if (deferred._status === STATUS_REJECTED) {
  1141. return;
  1142. }
  1143. results[i] = value;
  1144. unresolved--;
  1145. if (unresolved === 0) {
  1146. resolveAll(results);
  1147. }
  1148. };
  1149. })(i);
  1150. if (Promise.isPromise(promise)) {
  1151. promise.then(resolve, reject);
  1152. } else {
  1153. resolve(promise);
  1154. }
  1155. }
  1156. return deferred;
  1157. };
  1158. /**
  1159. * Checks if the value is likely a promise (has a 'then' function).
  1160. * @return {boolean} true if value is thenable
  1161. */
  1162. Promise.isPromise = function Promise_isPromise(value) {
  1163. return value && typeof value.then === 'function';
  1164. };
  1165. /**
  1166. * Creates resolved promise
  1167. * @param value resolve value
  1168. * @returns {Promise}
  1169. */
  1170. Promise.resolve = function Promise_resolve(value) {
  1171. return new Promise(function (resolve) { resolve(value); });
  1172. };
  1173. /**
  1174. * Creates rejected promise
  1175. * @param reason rejection value
  1176. * @returns {Promise}
  1177. */
  1178. Promise.reject = function Promise_reject(reason) {
  1179. return new Promise(function (resolve, reject) { reject(reason); });
  1180. };
  1181. Promise.prototype = {
  1182. _status: null,
  1183. _value: null,
  1184. _handlers: null,
  1185. _unhandledRejection: null,
  1186. _updateStatus: function Promise__updateStatus(status, value) {
  1187. if (this._status === STATUS_RESOLVED ||
  1188. this._status === STATUS_REJECTED) {
  1189. return;
  1190. }
  1191. if (status === STATUS_RESOLVED &&
  1192. Promise.isPromise(value)) {
  1193. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1194. this._updateStatus.bind(this, STATUS_REJECTED));
  1195. return;
  1196. }
  1197. this._status = status;
  1198. this._value = value;
  1199. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1200. this._unhandledRejection = true;
  1201. HandlerManager.addUnhandledRejection(this);
  1202. }
  1203. HandlerManager.scheduleHandlers(this);
  1204. },
  1205. _resolve: function Promise_resolve(value) {
  1206. this._updateStatus(STATUS_RESOLVED, value);
  1207. },
  1208. _reject: function Promise_reject(reason) {
  1209. this._updateStatus(STATUS_REJECTED, reason);
  1210. },
  1211. then: function Promise_then(onResolve, onReject) {
  1212. var nextPromise = new Promise(function (resolve, reject) {
  1213. this.resolve = resolve;
  1214. this.reject = reject;
  1215. });
  1216. this._handlers.push({
  1217. thisPromise: this,
  1218. onResolve: onResolve,
  1219. onReject: onReject,
  1220. nextPromise: nextPromise
  1221. });
  1222. HandlerManager.scheduleHandlers(this);
  1223. return nextPromise;
  1224. },
  1225. catch: function Promise_catch(onReject) {
  1226. return this.then(undefined, onReject);
  1227. }
  1228. };
  1229. globalScope.Promise = Promise;
  1230. })();
  1231. var StatTimer = (function StatTimerClosure() {
  1232. function rpad(str, pad, length) {
  1233. while (str.length < length) {
  1234. str += pad;
  1235. }
  1236. return str;
  1237. }
  1238. function StatTimer() {
  1239. this.started = {};
  1240. this.times = [];
  1241. this.enabled = true;
  1242. }
  1243. StatTimer.prototype = {
  1244. time: function StatTimer_time(name) {
  1245. if (!this.enabled) {
  1246. return;
  1247. }
  1248. if (name in this.started) {
  1249. warn('Timer is already running for ' + name);
  1250. }
  1251. this.started[name] = Date.now();
  1252. },
  1253. timeEnd: function StatTimer_timeEnd(name) {
  1254. if (!this.enabled) {
  1255. return;
  1256. }
  1257. if (!(name in this.started)) {
  1258. warn('Timer has not been started for ' + name);
  1259. }
  1260. this.times.push({
  1261. 'name': name,
  1262. 'start': this.started[name],
  1263. 'end': Date.now()
  1264. });
  1265. // Remove timer from started so it can be called again.
  1266. delete this.started[name];
  1267. },
  1268. toString: function StatTimer_toString() {
  1269. var i, ii;
  1270. var times = this.times;
  1271. var out = '';
  1272. // Find the longest name for padding purposes.
  1273. var longest = 0;
  1274. for (i = 0, ii = times.length; i < ii; ++i) {
  1275. var name = times[i]['name'];
  1276. if (name.length > longest) {
  1277. longest = name.length;
  1278. }
  1279. }
  1280. for (i = 0, ii = times.length; i < ii; ++i) {
  1281. var span = times[i];
  1282. var duration = span.end - span.start;
  1283. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1284. }
  1285. return out;
  1286. }
  1287. };
  1288. return StatTimer;
  1289. })();
  1290. PDFJS.createBlob = function createBlob(data, contentType) {
  1291. if (typeof Blob !== 'undefined') {
  1292. return new Blob([data], { type: contentType });
  1293. }
  1294. // Blob builder is deprecated in FF14 and removed in FF18.
  1295. var bb = new MozBlobBuilder();
  1296. bb.append(data);
  1297. return bb.getBlob(contentType);
  1298. };
  1299. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1300. // Blob/createObjectURL is not available, falling back to data schema.
  1301. var digits =
  1302. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1303. return function createObjectURL(data, contentType) {
  1304. if (!PDFJS.disableCreateObjectURL &&
  1305. typeof URL !== 'undefined' && URL.createObjectURL) {
  1306. var blob = PDFJS.createBlob(data, contentType);
  1307. return URL.createObjectURL(blob);
  1308. }
  1309. var buffer = 'data:' + contentType + ';base64,';
  1310. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1311. var b1 = data[i] & 0xFF;
  1312. var b2 = data[i + 1] & 0xFF;
  1313. var b3 = data[i + 2] & 0xFF;
  1314. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1315. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1316. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1317. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1318. }
  1319. return buffer;
  1320. };
  1321. })();
  1322. function MessageHandler(name, comObj) {
  1323. this.name = name;
  1324. this.comObj = comObj;
  1325. this.callbackIndex = 1;
  1326. this.postMessageTransfers = true;
  1327. var callbacksCapabilities = this.callbacksCapabilities = {};
  1328. var ah = this.actionHandler = {};
  1329. ah['console_log'] = [function ahConsoleLog(data) {
  1330. console.log.apply(console, data);
  1331. }];
  1332. ah['console_error'] = [function ahConsoleError(data) {
  1333. console.error.apply(console, data);
  1334. }];
  1335. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1336. UnsupportedManager.notify(data);
  1337. }];
  1338. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1339. var data = event.data;
  1340. if (data.isReply) {
  1341. var callbackId = data.callbackId;
  1342. if (data.callbackId in callbacksCapabilities) {
  1343. var callback = callbacksCapabilities[callbackId];
  1344. delete callbacksCapabilities[callbackId];
  1345. if ('error' in data) {
  1346. callback.reject(data.error);
  1347. } else {
  1348. callback.resolve(data.data);
  1349. }
  1350. } else {
  1351. error('Cannot resolve callback ' + callbackId);
  1352. }
  1353. } else if (data.action in ah) {
  1354. var action = ah[data.action];
  1355. if (data.callbackId) {
  1356. Promise.resolve().then(function () {
  1357. return action[0].call(action[1], data.data);
  1358. }).then(function (result) {
  1359. comObj.postMessage({
  1360. isReply: true,
  1361. callbackId: data.callbackId,
  1362. data: result
  1363. });
  1364. }, function (reason) {
  1365. comObj.postMessage({
  1366. isReply: true,
  1367. callbackId: data.callbackId,
  1368. error: reason
  1369. });
  1370. });
  1371. } else {
  1372. action[0].call(action[1], data.data);
  1373. }
  1374. } else {
  1375. error('Unknown action from worker: ' + data.action);
  1376. }
  1377. };
  1378. }
  1379. MessageHandler.prototype = {
  1380. on: function messageHandlerOn(actionName, handler, scope) {
  1381. var ah = this.actionHandler;
  1382. if (ah[actionName]) {
  1383. error('There is already an actionName called "' + actionName + '"');
  1384. }
  1385. ah[actionName] = [handler, scope];
  1386. },
  1387. /**
  1388. * Sends a message to the comObj to invoke the action with the supplied data.
  1389. * @param {String} actionName Action to call.
  1390. * @param {JSON} data JSON data to send.
  1391. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1392. */
  1393. send: function messageHandlerSend(actionName, data, transfers) {
  1394. var message = {
  1395. action: actionName,
  1396. data: data
  1397. };
  1398. this.postMessage(message, transfers);
  1399. },
  1400. /**
  1401. * Sends a message to the comObj to invoke the action with the supplied data.
  1402. * Expects that other side will callback with the response.
  1403. * @param {String} actionName Action to call.
  1404. * @param {JSON} data JSON data to send.
  1405. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1406. * @returns {Promise} Promise to be resolved with response data.
  1407. */
  1408. sendWithPromise:
  1409. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1410. var callbackId = this.callbackIndex++;
  1411. var message = {
  1412. action: actionName,
  1413. data: data,
  1414. callbackId: callbackId
  1415. };
  1416. var capability = createPromiseCapability();
  1417. this.callbacksCapabilities[callbackId] = capability;
  1418. try {
  1419. this.postMessage(message, transfers);
  1420. } catch (e) {
  1421. capability.reject(e);
  1422. }
  1423. return capability.promise;
  1424. },
  1425. /**
  1426. * Sends raw message to the comObj.
  1427. * @private
  1428. * @param message {Object} Raw message.
  1429. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1430. */
  1431. postMessage: function (message, transfers) {
  1432. if (transfers && this.postMessageTransfers) {
  1433. this.comObj.postMessage(message, transfers);
  1434. } else {
  1435. this.comObj.postMessage(message);
  1436. }
  1437. }
  1438. };
  1439. function loadJpegStream(id, imageUrl, objs) {
  1440. var img = new Image();
  1441. img.onload = (function loadJpegStream_onloadClosure() {
  1442. objs.resolve(id, img);
  1443. });
  1444. img.onerror = (function loadJpegStream_onerrorClosure() {
  1445. objs.resolve(id, null);
  1446. warn('Error during JPEG image loading');
  1447. });
  1448. img.src = imageUrl;
  1449. }
  1450. /**
  1451. * The maximum allowed image size in total pixels e.g. width * height. Images
  1452. * above this value will not be drawn. Use -1 for no limit.
  1453. * @var {number}
  1454. */
  1455. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  1456. -1 : PDFJS.maxImageSize);
  1457. /**
  1458. * The url of where the predefined Adobe CMaps are located. Include trailing
  1459. * slash.
  1460. * @var {string}
  1461. */
  1462. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  1463. /**
  1464. * Specifies if CMaps are binary packed.
  1465. * @var {boolean}
  1466. */
  1467. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  1468. /**
  1469. * By default fonts are converted to OpenType fonts and loaded via font face
  1470. * rules. If disabled, the font will be rendered using a built in font renderer
  1471. * that constructs the glyphs with primitive path commands.
  1472. * @var {boolean}
  1473. */
  1474. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  1475. false : PDFJS.disableFontFace);
  1476. /**
  1477. * Path for image resources, mainly for annotation icons. Include trailing
  1478. * slash.
  1479. * @var {string}
  1480. */
  1481. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  1482. '' : PDFJS.imageResourcesPath);
  1483. /**
  1484. * Disable the web worker and run all code on the main thread. This will happen
  1485. * automatically if the browser doesn't support workers or sending typed arrays
  1486. * to workers.
  1487. * @var {boolean}
  1488. */
  1489. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  1490. false : PDFJS.disableWorker);
  1491. /**
  1492. * Path and filename of the worker file. Required when the worker is enabled in
  1493. * development mode. If unspecified in the production build, the worker will be
  1494. * loaded based on the location of the pdf.js file.
  1495. * @var {string}
  1496. */
  1497. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  1498. /**
  1499. * Disable range request loading of PDF files. When enabled and if the server
  1500. * supports partial content requests then the PDF will be fetched in chunks.
  1501. * Enabled (false) by default.
  1502. * @var {boolean}
  1503. */
  1504. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  1505. false : PDFJS.disableRange);
  1506. /**
  1507. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  1508. * in chunks. This default behavior can be disabled.
  1509. * @var {boolean}
  1510. */
  1511. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  1512. false : PDFJS.disableStream);
  1513. /**
  1514. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  1515. * will automatically keep fetching more data even if it isn't needed to display
  1516. * the current page. This default behavior can be disabled.
  1517. *
  1518. * NOTE: It is also necessary to disable streaming, see above,
  1519. * in order for disabling of pre-fetching to work correctly.
  1520. * @var {boolean}
  1521. */
  1522. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  1523. false : PDFJS.disableAutoFetch);
  1524. /**
  1525. * Enables special hooks for debugging PDF.js.
  1526. * @var {boolean}
  1527. */
  1528. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  1529. /**
  1530. * Enables transfer usage in postMessage for ArrayBuffers.
  1531. * @var {boolean}
  1532. */
  1533. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  1534. true : PDFJS.postMessageTransfers);
  1535. /**
  1536. * Disables URL.createObjectURL usage.
  1537. * @var {boolean}
  1538. */
  1539. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  1540. false : PDFJS.disableCreateObjectURL);
  1541. /**
  1542. * Disables WebGL usage.
  1543. * @var {boolean}
  1544. */
  1545. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  1546. true : PDFJS.disableWebGL);
  1547. /**
  1548. * Disables fullscreen support, and by extension Presentation Mode,
  1549. * in browsers which support the fullscreen API.
  1550. * @var {boolean}
  1551. */
  1552. PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?
  1553. false : PDFJS.disableFullscreen);
  1554. /**
  1555. * Enables CSS only zooming.
  1556. * @var {boolean}
  1557. */
  1558. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  1559. false : PDFJS.useOnlyCssZoom);
  1560. /**
  1561. * Controls the logging level.
  1562. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  1563. * - errors
  1564. * - warnings [default]
  1565. * - infos
  1566. * @var {number}
  1567. */
  1568. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  1569. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  1570. /**
  1571. * The maximum supported canvas size in total pixels e.g. width * height.
  1572. * The default value is 4096 * 4096. Use -1 for no limit.
  1573. * @var {number}
  1574. */
  1575. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  1576. 16777216 : PDFJS.maxCanvasPixels);
  1577. /**
  1578. * Opens external links in a new window if enabled. The default behavior opens
  1579. * external links in the PDF.js window.
  1580. * @var {boolean}
  1581. */
  1582. PDFJS.openExternalLinksInNewWindow = (
  1583. PDFJS.openExternalLinksInNewWindow === undefined ?
  1584. false : PDFJS.openExternalLinksInNewWindow);
  1585. /**
  1586. * Document initialization / loading parameters object.
  1587. *
  1588. * @typedef {Object} DocumentInitParameters
  1589. * @property {string} url - The URL of the PDF.
  1590. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  1591. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  1592. * use atob() to convert it to a binary string first.
  1593. * @property {Object} httpHeaders - Basic authentication headers.
  1594. * @property {boolean} withCredentials - Indicates whether or not cross-site
  1595. * Access-Control requests should be made using credentials such as cookies
  1596. * or authorization headers. The default is false.
  1597. * @property {string} password - For decrypting password-protected PDFs.
  1598. * @property {TypedArray} initialData - A typed array with the first portion or
  1599. * all of the pdf data. Used by the extension since some data is already
  1600. * loaded before the switch to range requests.
  1601. * @property {number} length - The PDF file length. It's used for progress
  1602. * reports and range requests operations.
  1603. * @property {PDFDataRangeTransport} range
  1604. */
  1605. /**
  1606. * @typedef {Object} PDFDocumentStats
  1607. * @property {Array} streamTypes - Used stream types in the document (an item
  1608. * is set to true if specific stream ID was used in the document).
  1609. * @property {Array} fontTypes - Used font type in the document (an item is set
  1610. * to true if specific font ID was used in the document).
  1611. */
  1612. /**
  1613. * This is the main entry point for loading a PDF and interacting with it.
  1614. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  1615. * is used, which means it must follow the same origin rules that any XHR does
  1616. * e.g. No cross domain requests without CORS.
  1617. *
  1618. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  1619. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  1620. * already populated with data or parameter object.
  1621. *
  1622. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  1623. * if you want to manually serve range requests for data in the PDF.
  1624. *
  1625. * @param {function} passwordCallback (deprecated) It is used to request a
  1626. * password if wrong or no password was provided. The callback receives two
  1627. * parameters: function that needs to be called with new password and reason
  1628. * (see {PasswordResponses}).
  1629. *
  1630. * @param {function} progressCallback (deprecated) It is used to be able to
  1631. * monitor the loading progress of the PDF file (necessary to implement e.g.
  1632. * a loading bar). The callback receives an {Object} with the properties:
  1633. * {number} loaded and {number} total.
  1634. *
  1635. * @return {PDFDocumentLoadingTask}
  1636. */
  1637. PDFJS.getDocument = function getDocument(src,
  1638. pdfDataRangeTransport,
  1639. passwordCallback,
  1640. progressCallback) {
  1641. var task = new PDFDocumentLoadingTask();
  1642. // Support of the obsolete arguments (for compatibility with API v1.0)
  1643. if (pdfDataRangeTransport) {
  1644. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  1645. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  1646. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  1647. pdfDataRangeTransport.length = src.length;
  1648. pdfDataRangeTransport.initialData = src.initialData;
  1649. }
  1650. src = Object.create(src);
  1651. src.range = pdfDataRangeTransport;
  1652. }
  1653. task.onPassword = passwordCallback || null;
  1654. task.onProgress = progressCallback || null;
  1655. var workerInitializedCapability, transport;
  1656. var source;
  1657. if (typeof src === 'string') {
  1658. source = { url: src };
  1659. } else if (isArrayBuffer(src)) {
  1660. source = { data: src };
  1661. } else if (src instanceof PDFDataRangeTransport) {
  1662. source = { range: src };
  1663. } else {
  1664. if (typeof src !== 'object') {
  1665. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  1666. 'string or a parameter object');
  1667. }
  1668. if (!src.url && !src.data && !src.range) {
  1669. error('Invalid parameter object: need either .data, .range or .url');
  1670. }
  1671. source = src;
  1672. }
  1673. var params = {};
  1674. for (var key in source) {
  1675. if (key === 'url' && typeof window !== 'undefined') {
  1676. // The full path is required in the 'url' field.
  1677. params[key] = combineUrl(window.location.href, source[key]);
  1678. continue;
  1679. } else if (key === 'range') {
  1680. continue;
  1681. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  1682. // Converting string or array-like data to Uint8Array.
  1683. var pdfBytes = source[key];
  1684. if (typeof pdfBytes === 'string') {
  1685. params[key] = stringToBytes(pdfBytes);
  1686. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  1687. !isNaN(pdfBytes.length)) {
  1688. params[key] = new Uint8Array(pdfBytes);
  1689. } else {
  1690. error('Invalid PDF binary data: either typed array, string or ' +
  1691. 'array-like object is expected in the data property.');
  1692. }
  1693. continue;
  1694. }
  1695. params[key] = source[key];
  1696. }
  1697. workerInitializedCapability = createPromiseCapability();
  1698. transport = new WorkerTransport(workerInitializedCapability, source.range);
  1699. workerInitializedCapability.promise.then(function transportInitialized() {
  1700. transport.fetchDocument(task, params);
  1701. });
  1702. return task;
  1703. };
  1704. /**
  1705. * PDF document loading operation.
  1706. * @class
  1707. */
  1708. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  1709. /** @constructs PDFDocumentLoadingTask */
  1710. function PDFDocumentLoadingTask() {
  1711. this._capability = createPromiseCapability();
  1712. /**
  1713. * Callback to request a password if wrong or no password was provided.
  1714. * The callback receives two parameters: function that needs to be called
  1715. * with new password and reason (see {PasswordResponses}).
  1716. */
  1717. this.onPassword = null;
  1718. /**
  1719. * Callback to be able to monitor the loading progress of the PDF file
  1720. * (necessary to implement e.g. a loading bar). The callback receives
  1721. * an {Object} with the properties: {number} loaded and {number} total.
  1722. */
  1723. this.onProgress = null;
  1724. }
  1725. PDFDocumentLoadingTask.prototype =
  1726. /** @lends PDFDocumentLoadingTask.prototype */ {
  1727. /**
  1728. * @return {Promise}
  1729. */
  1730. get promise() {
  1731. return this._capability.promise;
  1732. },
  1733. // TODO add cancel or abort method
  1734. /**
  1735. * Registers callbacks to indicate the document loading completion.
  1736. *
  1737. * @param {function} onFulfilled The callback for the loading completion.
  1738. * @param {function} onRejected The callback for the loading failure.
  1739. * @return {Promise} A promise that is resolved after the onFulfilled or
  1740. * onRejected callback.
  1741. */
  1742. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  1743. return this.promise.then.apply(this.promise, arguments);
  1744. }
  1745. };
  1746. return PDFDocumentLoadingTask;
  1747. })();
  1748. /**
  1749. * Abstract class to support range requests file loading.
  1750. * @class
  1751. */
  1752. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  1753. /**
  1754. * @constructs PDFDataRangeTransport
  1755. * @param {number} length
  1756. * @param {Uint8Array} initialData
  1757. */
  1758. function PDFDataRangeTransport(length, initialData) {
  1759. this.length = length;
  1760. this.initialData = initialData;
  1761. this._rangeListeners = [];
  1762. this._progressListeners = [];
  1763. this._progressiveReadListeners = [];
  1764. this._readyCapability = createPromiseCapability();
  1765. }
  1766. PDFDataRangeTransport.prototype =
  1767. /** @lends PDFDataRangeTransport.prototype */ {
  1768. addRangeListener:
  1769. function PDFDataRangeTransport_addRangeListener(listener) {
  1770. this._rangeListeners.push(listener);
  1771. },
  1772. addProgressListener:
  1773. function PDFDataRangeTransport_addProgressListener(listener) {
  1774. this._progressListeners.push(listener);
  1775. },
  1776. addProgressiveReadListener:
  1777. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  1778. this._progressiveReadListeners.push(listener);
  1779. },
  1780. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  1781. var listeners = this._rangeListeners;
  1782. for (var i = 0, n = listeners.length; i < n; ++i) {
  1783. listeners[i](begin, chunk);
  1784. }
  1785. },
  1786. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  1787. this._readyCapability.promise.then(function () {
  1788. var listeners = this._progressListeners;
  1789. for (var i = 0, n = listeners.length; i < n; ++i) {
  1790. listeners[i](loaded);
  1791. }
  1792. }.bind(this));
  1793. },
  1794. onDataProgressiveRead:
  1795. function PDFDataRangeTransport_onDataProgress(chunk) {
  1796. this._readyCapability.promise.then(function () {
  1797. var listeners = this._progressiveReadListeners;
  1798. for (var i = 0, n = listeners.length; i < n; ++i) {
  1799. listeners[i](chunk);
  1800. }
  1801. }.bind(this));
  1802. },
  1803. transportReady: function PDFDataRangeTransport_transportReady() {
  1804. this._readyCapability.resolve();
  1805. },
  1806. requestDataRange:
  1807. function PDFDataRangeTransport_requestDataRange(begin, end) {
  1808. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  1809. }
  1810. };
  1811. return PDFDataRangeTransport;
  1812. })();
  1813. PDFJS.PDFDataRangeTransport = PDFDataRangeTransport;
  1814. /**
  1815. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  1816. * properties that can be read synchronously.
  1817. * @class
  1818. */
  1819. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  1820. function PDFDocumentProxy(pdfInfo, transport) {
  1821. this.pdfInfo = pdfInfo;
  1822. this.transport = transport;
  1823. }
  1824. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  1825. /**
  1826. * @return {number} Total number of pages the PDF contains.
  1827. */
  1828. get numPages() {
  1829. return this.pdfInfo.numPages;
  1830. },
  1831. /**
  1832. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  1833. * unique.
  1834. */
  1835. get fingerprint() {
  1836. return this.pdfInfo.fingerprint;
  1837. },
  1838. /**
  1839. * @param {number} pageNumber The page number to get. The first page is 1.
  1840. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  1841. * object.
  1842. */
  1843. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  1844. return this.transport.getPage(pageNumber);
  1845. },
  1846. /**
  1847. * @param {{num: number, gen: number}} ref The page reference. Must have
  1848. * the 'num' and 'gen' properties.
  1849. * @return {Promise} A promise that is resolved with the page index that is
  1850. * associated with the reference.
  1851. */
  1852. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  1853. return this.transport.getPageIndex(ref);
  1854. },
  1855. /**
  1856. * @return {Promise} A promise that is resolved with a lookup table for
  1857. * mapping named destinations to reference numbers.
  1858. *
  1859. * This can be slow for large documents: use getDestination instead
  1860. */
  1861. getDestinations: function PDFDocumentProxy_getDestinations() {
  1862. return this.transport.getDestinations();
  1863. },
  1864. /**
  1865. * @param {string} id The named destination to get.
  1866. * @return {Promise} A promise that is resolved with all information
  1867. * of the given named destination.
  1868. */
  1869. getDestination: function PDFDocumentProxy_getDestination(id) {
  1870. return this.transport.getDestination(id);
  1871. },
  1872. /**
  1873. * @return {Promise} A promise that is resolved with a lookup table for
  1874. * mapping named attachments to their content.
  1875. */
  1876. getAttachments: function PDFDocumentProxy_getAttachments() {
  1877. return this.transport.getAttachments();
  1878. },
  1879. /**
  1880. * @return {Promise} A promise that is resolved with an array of all the
  1881. * JavaScript strings in the name tree.
  1882. */
  1883. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  1884. return this.transport.getJavaScript();
  1885. },
  1886. /**
  1887. * @return {Promise} A promise that is resolved with an {Array} that is a
  1888. * tree outline (if it has one) of the PDF. The tree is in the format of:
  1889. * [
  1890. * {
  1891. * title: string,
  1892. * bold: boolean,
  1893. * italic: boolean,
  1894. * color: rgb array,
  1895. * dest: dest obj,
  1896. * items: array of more items like this
  1897. * },
  1898. * ...
  1899. * ].
  1900. */
  1901. getOutline: function PDFDocumentProxy_getOutline() {
  1902. return this.transport.getOutline();
  1903. },
  1904. /**
  1905. * @return {Promise} A promise that is resolved with an {Object} that has
  1906. * info and metadata properties. Info is an {Object} filled with anything
  1907. * available in the information dictionary and similarly metadata is a
  1908. * {Metadata} object with information from the metadata section of the PDF.
  1909. */
  1910. getMetadata: function PDFDocumentProxy_getMetadata() {
  1911. return this.transport.getMetadata();
  1912. },
  1913. /**
  1914. * @return {Promise} A promise that is resolved with a TypedArray that has
  1915. * the raw data from the PDF.
  1916. */
  1917. getData: function PDFDocumentProxy_getData() {
  1918. return this.transport.getData();
  1919. },
  1920. /**
  1921. * @return {Promise} A promise that is resolved when the document's data
  1922. * is loaded. It is resolved with an {Object} that contains the length
  1923. * property that indicates size of the PDF data in bytes.
  1924. */
  1925. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  1926. return this.transport.downloadInfoCapability.promise;
  1927. },
  1928. /**
  1929. * @return {Promise} A promise this is resolved with current stats about
  1930. * document structures (see {@link PDFDocumentStats}).
  1931. */
  1932. getStats: function PDFDocumentProxy_getStats() {
  1933. return this.transport.getStats();
  1934. },
  1935. /**
  1936. * Cleans up resources allocated by the document, e.g. created @font-face.
  1937. */
  1938. cleanup: function PDFDocumentProxy_cleanup() {
  1939. this.transport.startCleanup();
  1940. },
  1941. /**
  1942. * Destroys current document instance and terminates worker.
  1943. */
  1944. destroy: function PDFDocumentProxy_destroy() {
  1945. this.transport.destroy();
  1946. }
  1947. };
  1948. return PDFDocumentProxy;
  1949. })();
  1950. /**
  1951. * Page text content.
  1952. *
  1953. * @typedef {Object} TextContent
  1954. * @property {array} items - array of {@link TextItem}
  1955. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  1956. * name.
  1957. */
  1958. /**
  1959. * Page text content part.
  1960. *
  1961. * @typedef {Object} TextItem
  1962. * @property {string} str - text content.
  1963. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  1964. * @property {array} transform - transformation matrix.
  1965. * @property {number} width - width in device space.
  1966. * @property {number} height - height in device space.
  1967. * @property {string} fontName - font name used by pdf.js for converted font.
  1968. */
  1969. /**
  1970. * Text style.
  1971. *
  1972. * @typedef {Object} TextStyle
  1973. * @property {number} ascent - font ascent.
  1974. * @property {number} descent - font descent.
  1975. * @property {boolean} vertical - text is in vertical mode.
  1976. * @property {string} fontFamily - possible font family
  1977. */
  1978. /**
  1979. * Page render parameters.
  1980. *
  1981. * @typedef {Object} RenderParameters
  1982. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  1983. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  1984. * calling of PDFPage.getViewport method.
  1985. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  1986. * (default value is 'display').
  1987. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  1988. * endLayout and appendImage functions.
  1989. * @property {function} continueCallback - (deprecated) A function that will be
  1990. * called each time the rendering is paused. To continue
  1991. * rendering call the function that is the first argument
  1992. * to the callback.
  1993. */
  1994. /**
  1995. * PDF page operator list.
  1996. *
  1997. * @typedef {Object} PDFOperatorList
  1998. * @property {Array} fnArray - Array containing the operator functions.
  1999. * @property {Array} argsArray - Array containing the arguments of the
  2000. * functions.
  2001. */
  2002. /**
  2003. * Proxy to a PDFPage in the worker thread.
  2004. * @class
  2005. */
  2006. var PDFPageProxy = (function PDFPageProxyClosure() {
  2007. function PDFPageProxy(pageIndex, pageInfo, transport) {
  2008. this.pageIndex = pageIndex;
  2009. this.pageInfo = pageInfo;
  2010. this.transport = transport;
  2011. this.stats = new StatTimer();
  2012. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  2013. this.commonObjs = transport.commonObjs;
  2014. this.objs = new PDFObjects();
  2015. this.cleanupAfterRender = false;
  2016. this.pendingDestroy = false;
  2017. this.intentStates = {};
  2018. }
  2019. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  2020. /**
  2021. * @return {number} Page number of the page. First page is 1.
  2022. */
  2023. get pageNumber() {
  2024. return this.pageIndex + 1;
  2025. },
  2026. /**
  2027. * @return {number} The number of degrees the page is rotated clockwise.
  2028. */
  2029. get rotate() {
  2030. return this.pageInfo.rotate;
  2031. },
  2032. /**
  2033. * @return {Object} The reference that points to this page. It has 'num' and
  2034. * 'gen' properties.
  2035. */
  2036. get ref() {
  2037. return this.pageInfo.ref;
  2038. },
  2039. /**
  2040. * @return {Array} An array of the visible portion of the PDF page in the
  2041. * user space units - [x1, y1, x2, y2].
  2042. */
  2043. get view() {
  2044. return this.pageInfo.view;
  2045. },
  2046. /**
  2047. * @param {number} scale The desired scale of the viewport.
  2048. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  2049. * defaults to the page rotation.
  2050. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  2051. * along with transforms required for rendering.
  2052. */
  2053. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  2054. if (arguments.length < 2) {
  2055. rotate = this.rotate;
  2056. }
  2057. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  2058. },
  2059. /**
  2060. * @return {Promise} A promise that is resolved with an {Array} of the
  2061. * annotation objects.
  2062. */
  2063. getAnnotations: function PDFPageProxy_getAnnotations() {
  2064. if (this.annotationsPromise) {
  2065. return this.annotationsPromise;
  2066. }
  2067. var promise = this.transport.getAnnotations(this.pageIndex);
  2068. this.annotationsPromise = promise;
  2069. return promise;
  2070. },
  2071. /**
  2072. * Begins the process of rendering a page to the desired context.
  2073. * @param {RenderParameters} params Page render parameters.
  2074. * @return {RenderTask} An object that contains the promise, which
  2075. * is resolved when the page finishes rendering.
  2076. */
  2077. render: function PDFPageProxy_render(params) {
  2078. var stats = this.stats;
  2079. stats.time('Overall');
  2080. // If there was a pending destroy cancel it so no cleanup happens during
  2081. // this call to render.
  2082. this.pendingDestroy = false;
  2083. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  2084. if (!this.intentStates[renderingIntent]) {
  2085. this.intentStates[renderingIntent] = {};
  2086. }
  2087. var intentState = this.intentStates[renderingIntent];
  2088. // If there's no displayReadyCapability yet, then the operatorList
  2089. // was never requested before. Make the request and create the promise.
  2090. if (!intentState.displayReadyCapability) {
  2091. intentState.receivingOperatorList = true;
  2092. intentState.displayReadyCapability = createPromiseCapability();
  2093. intentState.operatorList = {
  2094. fnArray: [],
  2095. argsArray: [],
  2096. lastChunk: false
  2097. };
  2098. this.stats.time('Page Request');
  2099. this.transport.messageHandler.send('RenderPageRequest', {
  2100. pageIndex: this.pageNumber - 1,
  2101. intent: renderingIntent
  2102. });
  2103. }
  2104. var internalRenderTask = new InternalRenderTask(complete, params,
  2105. this.objs,
  2106. this.commonObjs,
  2107. intentState.operatorList,
  2108. this.pageNumber);
  2109. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  2110. if (!intentState.renderTasks) {
  2111. intentState.renderTasks = [];
  2112. }
  2113. intentState.renderTasks.push(internalRenderTask);
  2114. var renderTask = internalRenderTask.task;
  2115. // Obsolete parameter support
  2116. if (params.continueCallback) {
  2117. renderTask.onContinue = params.continueCallback;
  2118. }
  2119. var self = this;
  2120. intentState.displayReadyCapability.promise.then(
  2121. function pageDisplayReadyPromise(transparency) {
  2122. if (self.pendingDestroy) {
  2123. complete();
  2124. return;
  2125. }
  2126. stats.time('Rendering');
  2127. internalRenderTask.initalizeGraphics(transparency);
  2128. internalRenderTask.operatorListChanged();
  2129. },
  2130. function pageDisplayReadPromiseError(reason) {
  2131. complete(reason);
  2132. }
  2133. );
  2134. function complete(error) {
  2135. var i = intentState.renderTasks.indexOf(internalRenderTask);
  2136. if (i >= 0) {
  2137. intentState.renderTasks.splice(i, 1);
  2138. }
  2139. if (self.cleanupAfterRender) {
  2140. self.pendingDestroy = true;
  2141. }
  2142. self._tryDestroy();
  2143. if (error) {
  2144. internalRenderTask.capability.reject(error);
  2145. } else {
  2146. internalRenderTask.capability.resolve();
  2147. }
  2148. stats.timeEnd('Rendering');
  2149. stats.timeEnd('Overall');
  2150. }
  2151. return renderTask;
  2152. },
  2153. /**
  2154. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  2155. * object that represents page's operator list.
  2156. */
  2157. getOperatorList: function PDFPageProxy_getOperatorList() {
  2158. function operatorListChanged() {
  2159. if (intentState.operatorList.lastChunk) {
  2160. intentState.opListReadCapability.resolve(intentState.operatorList);
  2161. }
  2162. }
  2163. var renderingIntent = 'oplist';
  2164. if (!this.intentStates[renderingIntent]) {
  2165. this.intentStates[renderingIntent] = {};
  2166. }
  2167. var intentState = this.intentStates[renderingIntent];
  2168. if (!intentState.opListReadCapability) {
  2169. var opListTask = {};
  2170. opListTask.operatorListChanged = operatorListChanged;
  2171. intentState.receivingOperatorList = true;
  2172. intentState.opListReadCapability = createPromiseCapability();
  2173. intentState.renderTasks = [];
  2174. intentState.renderTasks.push(opListTask);
  2175. intentState.operatorList = {
  2176. fnArray: [],
  2177. argsArray: [],
  2178. lastChunk: false
  2179. };
  2180. this.transport.messageHandler.send('RenderPageRequest', {
  2181. pageIndex: this.pageIndex,
  2182. intent: renderingIntent
  2183. });
  2184. }
  2185. return intentState.opListReadCapability.promise;
  2186. },
  2187. /**
  2188. * @return {Promise} That is resolved a {@link TextContent}
  2189. * object that represent the page text content.
  2190. */
  2191. getTextContent: function PDFPageProxy_getTextContent() {
  2192. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  2193. pageIndex: this.pageNumber - 1
  2194. });
  2195. },
  2196. /**
  2197. * Destroys resources allocated by the page.
  2198. */
  2199. destroy: function PDFPageProxy_destroy() {
  2200. this.pendingDestroy = true;
  2201. this._tryDestroy();
  2202. },
  2203. /**
  2204. * For internal use only. Attempts to clean up if rendering is in a state
  2205. * where that's possible.
  2206. * @ignore
  2207. */
  2208. _tryDestroy: function PDFPageProxy__destroy() {
  2209. if (!this.pendingDestroy ||
  2210. Object.keys(this.intentStates).some(function(intent) {
  2211. var intentState = this.intentStates[intent];
  2212. return (intentState.renderTasks.length !== 0 ||
  2213. intentState.receivingOperatorList);
  2214. }, this)) {
  2215. return;
  2216. }
  2217. Object.keys(this.intentStates).forEach(function(intent) {
  2218. delete this.intentStates[intent];
  2219. }, this);
  2220. this.objs.clear();
  2221. this.annotationsPromise = null;
  2222. this.pendingDestroy = false;
  2223. },
  2224. /**
  2225. * For internal use only.
  2226. * @ignore
  2227. */
  2228. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  2229. intent) {
  2230. var intentState = this.intentStates[intent];
  2231. // TODO Refactor RenderPageRequest to separate rendering
  2232. // and operator list logic
  2233. if (intentState.displayReadyCapability) {
  2234. intentState.displayReadyCapability.resolve(transparency);
  2235. }
  2236. },
  2237. /**
  2238. * For internal use only.
  2239. * @ignore
  2240. */
  2241. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  2242. intent) {
  2243. var intentState = this.intentStates[intent];
  2244. var i, ii;
  2245. // Add the new chunk to the current operator list.
  2246. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2247. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2248. intentState.operatorList.argsArray.push(
  2249. operatorListChunk.argsArray[i]);
  2250. }
  2251. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2252. // Notify all the rendering tasks there are more operators to be consumed.
  2253. for (i = 0; i < intentState.renderTasks.length; i++) {
  2254. intentState.renderTasks[i].operatorListChanged();
  2255. }
  2256. if (operatorListChunk.lastChunk) {
  2257. intentState.receivingOperatorList = false;
  2258. this._tryDestroy();
  2259. }
  2260. }
  2261. };
  2262. return PDFPageProxy;
  2263. })();
  2264. /**
  2265. * For internal use only.
  2266. * @ignore
  2267. */
  2268. var WorkerTransport = (function WorkerTransportClosure() {
  2269. function WorkerTransport(workerInitializedCapability, pdfDataRangeTransport) {
  2270. this.pdfDataRangeTransport = pdfDataRangeTransport;
  2271. this.workerInitializedCapability = workerInitializedCapability;
  2272. this.commonObjs = new PDFObjects();
  2273. this.loadingTask = null;
  2274. this.pageCache = [];
  2275. this.pagePromises = [];
  2276. this.downloadInfoCapability = createPromiseCapability();
  2277. // If worker support isn't disabled explicit and the browser has worker
  2278. // support, create a new web worker and test if it/the browser fullfills
  2279. // all requirements to run parts of pdf.js in a web worker.
  2280. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  2281. // as it arrives on the worker. Chrome added this with version 15.
  2282. // Either workers are disabled, not supported or have thrown an exception.
  2283. // Thus, we fallback to a faked worker.
  2284. this.setupFakeWorker();
  2285. }
  2286. WorkerTransport.prototype = {
  2287. destroy: function WorkerTransport_destroy() {
  2288. this.pageCache = [];
  2289. this.pagePromises = [];
  2290. var self = this;
  2291. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  2292. FontLoader.clear();
  2293. if (self.worker) {
  2294. self.worker.terminate();
  2295. }
  2296. });
  2297. },
  2298. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  2299. globalScope.PDFJS.disableWorker = true;
  2300. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  2301. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  2302. // In the developer build load worker_loader which in turn loads all the
  2303. // other files and resolves the promise. In production only the
  2304. // pdf.worker.js file is needed.
  2305. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  2306. }
  2307. PDFJS.fakeWorkerFilesLoadedCapability.promise.then(function () {
  2308. warn('Setting up fake worker.');
  2309. // If we don't use a worker, just post/sendMessage to the main thread.
  2310. var fakeWorker = {
  2311. postMessage: function WorkerTransport_postMessage(obj) {
  2312. fakeWorker.onmessage({data: obj});
  2313. },
  2314. terminate: function WorkerTransport_terminate() {}
  2315. };
  2316. var messageHandler = new MessageHandler('main', fakeWorker);
  2317. this.setupMessageHandler(messageHandler);
  2318. // If the main thread is our worker, setup the handling for the messages
  2319. // the main thread sends to it self.
  2320. PDFJS.WorkerMessageHandler.setup(messageHandler);
  2321. this.workerInitializedCapability.resolve();
  2322. }.bind(this));
  2323. },
  2324. setupMessageHandler:
  2325. function WorkerTransport_setupMessageHandler(messageHandler) {
  2326. this.messageHandler = messageHandler;
  2327. function updatePassword(password) {
  2328. messageHandler.send('UpdatePassword', password);
  2329. }
  2330. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  2331. if (pdfDataRangeTransport) {
  2332. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  2333. messageHandler.send('OnDataRange', {
  2334. begin: begin,
  2335. chunk: chunk
  2336. });
  2337. });
  2338. pdfDataRangeTransport.addProgressListener(function(loaded) {
  2339. messageHandler.send('OnDataProgress', {
  2340. loaded: loaded
  2341. });
  2342. });
  2343. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  2344. messageHandler.send('OnDataRange', {
  2345. chunk: chunk
  2346. });
  2347. });
  2348. messageHandler.on('RequestDataRange',
  2349. function transportDataRange(data) {
  2350. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  2351. }, this);
  2352. }
  2353. messageHandler.on('GetDoc', function transportDoc(data) {
  2354. var pdfInfo = data.pdfInfo;
  2355. this.numPages = data.pdfInfo.numPages;
  2356. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  2357. this.pdfDocument = pdfDocument;
  2358. this.loadingTask._capability.resolve(pdfDocument);
  2359. }, this);
  2360. messageHandler.on('NeedPassword',
  2361. function transportNeedPassword(exception) {
  2362. var loadingTask = this.loadingTask;
  2363. if (loadingTask.onPassword) {
  2364. return loadingTask.onPassword(updatePassword,
  2365. PasswordResponses.NEED_PASSWORD);
  2366. }
  2367. loadingTask._capability.reject(
  2368. new PasswordException(exception.message, exception.code));
  2369. }, this);
  2370. messageHandler.on('IncorrectPassword',
  2371. function transportIncorrectPassword(exception) {
  2372. var loadingTask = this.loadingTask;
  2373. if (loadingTask.onPassword) {
  2374. return loadingTask.onPassword(updatePassword,
  2375. PasswordResponses.INCORRECT_PASSWORD);
  2376. }
  2377. loadingTask._capability.reject(
  2378. new PasswordException(exception.message, exception.code));
  2379. }, this);
  2380. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  2381. this.loadingTask._capability.reject(
  2382. new InvalidPDFException(exception.message));
  2383. }, this);
  2384. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  2385. this.loadingTask._capability.reject(
  2386. new MissingPDFException(exception.message));
  2387. }, this);
  2388. messageHandler.on('UnexpectedResponse',
  2389. function transportUnexpectedResponse(exception) {
  2390. this.loadingTask._capability.reject(
  2391. new UnexpectedResponseException(exception.message, exception.status));
  2392. }, this);
  2393. messageHandler.on('UnknownError',
  2394. function transportUnknownError(exception) {
  2395. this.loadingTask._capability.reject(
  2396. new UnknownErrorException(exception.message, exception.details));
  2397. }, this);
  2398. messageHandler.on('DataLoaded', function transportPage(data) {
  2399. this.downloadInfoCapability.resolve(data);
  2400. }, this);
  2401. messageHandler.on('PDFManagerReady', function transportPage(data) {
  2402. if (this.pdfDataRangeTransport) {
  2403. this.pdfDataRangeTransport.transportReady();
  2404. }
  2405. }, this);
  2406. messageHandler.on('StartRenderPage', function transportRender(data) {
  2407. var page = this.pageCache[data.pageIndex];
  2408. page.stats.timeEnd('Page Request');
  2409. page._startRenderPage(data.transparency, data.intent);
  2410. }, this);
  2411. messageHandler.on('RenderPageChunk', function transportRender(data) {
  2412. var page = this.pageCache[data.pageIndex];
  2413. page._renderPageChunk(data.operatorList, data.intent);
  2414. }, this);
  2415. messageHandler.on('commonobj', function transportObj(data) {
  2416. var id = data[0];
  2417. var type = data[1];
  2418. if (this.commonObjs.hasData(id)) {
  2419. return;
  2420. }
  2421. switch (type) {
  2422. case 'Font':
  2423. var exportedData = data[2];
  2424. var font;
  2425. if ('error' in exportedData) {
  2426. var error = exportedData.error;
  2427. warn('Error during font loading: ' + error);
  2428. this.commonObjs.resolve(id, error);
  2429. break;
  2430. } else {
  2431. font = new FontFaceObject(exportedData);
  2432. }
  2433. FontLoader.bind(
  2434. [font],
  2435. function fontReady(fontObjs) {
  2436. this.commonObjs.resolve(id, font);
  2437. }.bind(this)
  2438. );
  2439. break;
  2440. case 'FontPath':
  2441. this.commonObjs.resolve(id, data[2]);
  2442. break;
  2443. default:
  2444. error('Got unknown common object type ' + type);
  2445. }
  2446. }, this);
  2447. messageHandler.on('obj', function transportObj(data) {
  2448. var id = data[0];
  2449. var pageIndex = data[1];
  2450. var type = data[2];
  2451. var pageProxy = this.pageCache[pageIndex];
  2452. var imageData;
  2453. if (pageProxy.objs.hasData(id)) {
  2454. return;
  2455. }
  2456. switch (type) {
  2457. case 'JpegStream':
  2458. imageData = data[3];
  2459. loadJpegStream(id, imageData, pageProxy.objs);
  2460. break;
  2461. case 'Image':
  2462. imageData = data[3];
  2463. pageProxy.objs.resolve(id, imageData);
  2464. // heuristics that will allow not to store large data
  2465. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2466. if (imageData && 'data' in imageData &&
  2467. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  2468. pageProxy.cleanupAfterRender = true;
  2469. }
  2470. break;
  2471. default:
  2472. error('Got unknown object type ' + type);
  2473. }
  2474. }, this);
  2475. messageHandler.on('DocProgress', function transportDocProgress(data) {
  2476. var loadingTask = this.loadingTask;
  2477. if (loadingTask.onProgress) {
  2478. loadingTask.onProgress({
  2479. loaded: data.loaded,
  2480. total: data.total
  2481. });
  2482. }
  2483. }, this);
  2484. messageHandler.on('PageError', function transportError(data) {
  2485. var page = this.pageCache[data.pageNum - 1];
  2486. var intentState = page.intentStates[data.intent];
  2487. if (intentState.displayReadyCapability) {
  2488. intentState.displayReadyCapability.reject(data.error);
  2489. } else {
  2490. error(data.error);
  2491. }
  2492. }, this);
  2493. messageHandler.on('JpegDecode', function(data) {
  2494. var imageUrl = data[0];
  2495. var components = data[1];
  2496. if (components !== 3 && components !== 1) {
  2497. return Promise.reject(
  2498. new Error('Only 3 components or 1 component can be returned'));
  2499. }
  2500. return new Promise(function (resolve, reject) {
  2501. var img = new Image();
  2502. img.onload = function () {
  2503. var width = img.width;
  2504. var height = img.height;
  2505. var size = width * height;
  2506. var rgbaLength = size * 4;
  2507. var buf = new Uint8Array(size * components);
  2508. var tmpCanvas = createScratchCanvas(width, height);
  2509. var tmpCtx = tmpCanvas.getContext('2d');
  2510. tmpCtx.drawImage(img, 0, 0);
  2511. var data = tmpCtx.getImageData(0, 0, width, height).data;
  2512. var i, j;
  2513. if (components === 3) {
  2514. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  2515. buf[j] = data[i];
  2516. buf[j + 1] = data[i + 1];
  2517. buf[j + 2] = data[i + 2];
  2518. }
  2519. } else if (components === 1) {
  2520. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  2521. buf[j] = data[i];
  2522. }
  2523. }
  2524. resolve({ data: buf, width: width, height: height});
  2525. };
  2526. img.onerror = function () {
  2527. reject(new Error('JpegDecode failed to load image'));
  2528. };
  2529. img.src = imageUrl;
  2530. });
  2531. });
  2532. },
  2533. fetchDocument: function WorkerTransport_fetchDocument(loadingTask, source) {
  2534. this.loadingTask = loadingTask;
  2535. source.disableAutoFetch = PDFJS.disableAutoFetch;
  2536. source.disableStream = PDFJS.disableStream;
  2537. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  2538. if (this.pdfDataRangeTransport) {
  2539. source.length = this.pdfDataRangeTransport.length;
  2540. source.initialData = this.pdfDataRangeTransport.initialData;
  2541. }
  2542. this.messageHandler.send('GetDocRequest', {
  2543. source: source,
  2544. disableRange: PDFJS.disableRange,
  2545. maxImageSize: PDFJS.maxImageSize,
  2546. cMapUrl: PDFJS.cMapUrl,
  2547. cMapPacked: PDFJS.cMapPacked,
  2548. disableFontFace: PDFJS.disableFontFace,
  2549. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  2550. verbosity: PDFJS.verbosity
  2551. });
  2552. },
  2553. getData: function WorkerTransport_getData() {
  2554. return this.messageHandler.sendWithPromise('GetData', null);
  2555. },
  2556. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  2557. if (pageNumber <= 0 || pageNumber > this.numPages ||
  2558. (pageNumber|0) !== pageNumber) {
  2559. return Promise.reject(new Error('Invalid page request'));
  2560. }
  2561. var pageIndex = pageNumber - 1;
  2562. if (pageIndex in this.pagePromises) {
  2563. return this.pagePromises[pageIndex];
  2564. }
  2565. var promise = this.messageHandler.sendWithPromise('GetPage', {
  2566. pageIndex: pageIndex
  2567. }).then(function (pageInfo) {
  2568. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  2569. this.pageCache[pageIndex] = page;
  2570. return page;
  2571. }.bind(this));
  2572. this.pagePromises[pageIndex] = promise;
  2573. return promise;
  2574. },
  2575. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  2576. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  2577. },
  2578. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  2579. return this.messageHandler.sendWithPromise('GetAnnotations',
  2580. { pageIndex: pageIndex });
  2581. },
  2582. getDestinations: function WorkerTransport_getDestinations() {
  2583. return this.messageHandler.sendWithPromise('GetDestinations', null);
  2584. },
  2585. getDestination: function WorkerTransport_getDestination(id) {
  2586. return this.messageHandler.sendWithPromise('GetDestination', { id: id } );
  2587. },
  2588. getAttachments: function WorkerTransport_getAttachments() {
  2589. return this.messageHandler.sendWithPromise('GetAttachments', null);
  2590. },
  2591. getJavaScript: function WorkerTransport_getJavaScript() {
  2592. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  2593. },
  2594. getOutline: function WorkerTransport_getOutline() {
  2595. return this.messageHandler.sendWithPromise('GetOutline', null);
  2596. },
  2597. getMetadata: function WorkerTransport_getMetadata() {
  2598. return this.messageHandler.sendWithPromise('GetMetadata', null).
  2599. then(function transportMetadata(results) {
  2600. return {
  2601. info: results[0],
  2602. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  2603. };
  2604. });
  2605. },
  2606. getStats: function WorkerTransport_getStats() {
  2607. return this.messageHandler.sendWithPromise('GetStats', null);
  2608. },
  2609. startCleanup: function WorkerTransport_startCleanup() {
  2610. this.messageHandler.sendWithPromise('Cleanup', null).
  2611. then(function endCleanup() {
  2612. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  2613. var page = this.pageCache[i];
  2614. if (page) {
  2615. page.destroy();
  2616. }
  2617. }
  2618. this.commonObjs.clear();
  2619. FontLoader.clear();
  2620. }.bind(this));
  2621. }
  2622. };
  2623. return WorkerTransport;
  2624. })();
  2625. /**
  2626. * A PDF document and page is built of many objects. E.g. there are objects
  2627. * for fonts, images, rendering code and such. These objects might get processed
  2628. * inside of a worker. The `PDFObjects` implements some basic functions to
  2629. * manage these objects.
  2630. * @ignore
  2631. */
  2632. var PDFObjects = (function PDFObjectsClosure() {
  2633. function PDFObjects() {
  2634. this.objs = {};
  2635. }
  2636. PDFObjects.prototype = {
  2637. /**
  2638. * Internal function.
  2639. * Ensures there is an object defined for `objId`.
  2640. */
  2641. ensureObj: function PDFObjects_ensureObj(objId) {
  2642. if (this.objs[objId]) {
  2643. return this.objs[objId];
  2644. }
  2645. var obj = {
  2646. capability: createPromiseCapability(),
  2647. data: null,
  2648. resolved: false
  2649. };
  2650. this.objs[objId] = obj;
  2651. return obj;
  2652. },
  2653. /**
  2654. * If called *without* callback, this returns the data of `objId` but the
  2655. * object needs to be resolved. If it isn't, this function throws.
  2656. *
  2657. * If called *with* a callback, the callback is called with the data of the
  2658. * object once the object is resolved. That means, if you call this
  2659. * function and the object is already resolved, the callback gets called
  2660. * right away.
  2661. */
  2662. get: function PDFObjects_get(objId, callback) {
  2663. // If there is a callback, then the get can be async and the object is
  2664. // not required to be resolved right now
  2665. if (callback) {
  2666. this.ensureObj(objId).capability.promise.then(callback);
  2667. return null;
  2668. }
  2669. // If there isn't a callback, the user expects to get the resolved data
  2670. // directly.
  2671. var obj = this.objs[objId];
  2672. // If there isn't an object yet or the object isn't resolved, then the
  2673. // data isn't ready yet!
  2674. if (!obj || !obj.resolved) {
  2675. error('Requesting object that isn\'t resolved yet ' + objId);
  2676. }
  2677. return obj.data;
  2678. },
  2679. /**
  2680. * Resolves the object `objId` with optional `data`.
  2681. */
  2682. resolve: function PDFObjects_resolve(objId, data) {
  2683. var obj = this.ensureObj(objId);
  2684. obj.resolved = true;
  2685. obj.data = data;
  2686. obj.capability.resolve(data);
  2687. },
  2688. isResolved: function PDFObjects_isResolved(objId) {
  2689. var objs = this.objs;
  2690. if (!objs[objId]) {
  2691. return false;
  2692. } else {
  2693. return objs[objId].resolved;
  2694. }
  2695. },
  2696. hasData: function PDFObjects_hasData(objId) {
  2697. return this.isResolved(objId);
  2698. },
  2699. /**
  2700. * Returns the data of `objId` if object exists, null otherwise.
  2701. */
  2702. getData: function PDFObjects_getData(objId) {
  2703. var objs = this.objs;
  2704. if (!objs[objId] || !objs[objId].resolved) {
  2705. return null;
  2706. } else {
  2707. return objs[objId].data;
  2708. }
  2709. },
  2710. clear: function PDFObjects_clear() {
  2711. this.objs = {};
  2712. }
  2713. };
  2714. return PDFObjects;
  2715. })();
  2716. /**
  2717. * Allows controlling of the rendering tasks.
  2718. * @class
  2719. */
  2720. var RenderTask = (function RenderTaskClosure() {
  2721. function RenderTask(internalRenderTask) {
  2722. this._internalRenderTask = internalRenderTask;
  2723. /**
  2724. * Callback for incremental rendering -- a function that will be called
  2725. * each time the rendering is paused. To continue rendering call the
  2726. * function that is the first argument to the callback.
  2727. * @type {function}
  2728. */
  2729. this.onContinue = null;
  2730. }
  2731. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  2732. /**
  2733. * Promise for rendering task completion.
  2734. * @return {Promise}
  2735. */
  2736. get promise() {
  2737. return this._internalRenderTask.capability.promise;
  2738. },
  2739. /**
  2740. * Cancels the rendering task. If the task is currently rendering it will
  2741. * not be cancelled until graphics pauses with a timeout. The promise that
  2742. * this object extends will resolved when cancelled.
  2743. */
  2744. cancel: function RenderTask_cancel() {
  2745. this._internalRenderTask.cancel();
  2746. },
  2747. /**
  2748. * Registers callbacks to indicate the rendering task completion.
  2749. *
  2750. * @param {function} onFulfilled The callback for the rendering completion.
  2751. * @param {function} onRejected The callback for the rendering failure.
  2752. * @return {Promise} A promise that is resolved after the onFulfilled or
  2753. * onRejected callback.
  2754. */
  2755. then: function RenderTask_then(onFulfilled, onRejected) {
  2756. return this.promise.then.apply(this.promise, arguments);
  2757. }
  2758. };
  2759. return RenderTask;
  2760. })();
  2761. /**
  2762. * For internal use only.
  2763. * @ignore
  2764. */
  2765. var InternalRenderTask = (function InternalRenderTaskClosure() {
  2766. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  2767. pageNumber) {
  2768. this.callback = callback;
  2769. this.params = params;
  2770. this.objs = objs;
  2771. this.commonObjs = commonObjs;
  2772. this.operatorListIdx = null;
  2773. this.operatorList = operatorList;
  2774. this.pageNumber = pageNumber;
  2775. this.running = false;
  2776. this.graphicsReadyCallback = null;
  2777. this.graphicsReady = false;
  2778. this.useRequestAnimationFrame = false;
  2779. this.cancelled = false;
  2780. this.capability = createPromiseCapability();
  2781. this.task = new RenderTask(this);
  2782. // caching this-bound methods
  2783. this._continueBound = this._continue.bind(this);
  2784. this._scheduleNextBound = this._scheduleNext.bind(this);
  2785. this._nextBound = this._next.bind(this);
  2786. }
  2787. InternalRenderTask.prototype = {
  2788. initalizeGraphics:
  2789. function InternalRenderTask_initalizeGraphics(transparency) {
  2790. if (this.cancelled) {
  2791. return;
  2792. }
  2793. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  2794. globalScope.StepperManager.enabled) {
  2795. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  2796. this.stepper.init(this.operatorList);
  2797. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2798. }
  2799. var params = this.params;
  2800. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  2801. this.objs, params.imageLayer);
  2802. this.gfx.beginDrawing(params.viewport, transparency);
  2803. this.operatorListIdx = 0;
  2804. this.graphicsReady = true;
  2805. if (this.graphicsReadyCallback) {
  2806. this.graphicsReadyCallback();
  2807. }
  2808. },
  2809. cancel: function InternalRenderTask_cancel() {
  2810. this.running = false;
  2811. this.cancelled = true;
  2812. this.callback('cancelled');
  2813. },
  2814. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  2815. if (!this.graphicsReady) {
  2816. if (!this.graphicsReadyCallback) {
  2817. this.graphicsReadyCallback = this._continueBound;
  2818. }
  2819. return;
  2820. }
  2821. if (this.stepper) {
  2822. this.stepper.updateOperatorList(this.operatorList);
  2823. }
  2824. if (this.running) {
  2825. return;
  2826. }
  2827. this._continue();
  2828. },
  2829. _continue: function InternalRenderTask__continue() {
  2830. this.running = true;
  2831. if (this.cancelled) {
  2832. return;
  2833. }
  2834. if (this.task.onContinue) {
  2835. this.task.onContinue.call(this.task, this._scheduleNextBound);
  2836. } else {
  2837. this._scheduleNext();
  2838. }
  2839. },
  2840. _scheduleNext: function InternalRenderTask__scheduleNext() {
  2841. if (this.useRequestAnimationFrame) {
  2842. window.requestAnimationFrame(this._nextBound);
  2843. } else {
  2844. Promise.resolve(undefined).then(this._nextBound);
  2845. }
  2846. },
  2847. _next: function InternalRenderTask__next() {
  2848. if (this.cancelled) {
  2849. return;
  2850. }
  2851. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  2852. this.operatorListIdx,
  2853. this._continueBound,
  2854. this.stepper);
  2855. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2856. this.running = false;
  2857. if (this.operatorList.lastChunk) {
  2858. this.gfx.endDrawing();
  2859. this.callback();
  2860. }
  2861. }
  2862. }
  2863. };
  2864. return InternalRenderTask;
  2865. })();
  2866. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  2867. function fixMetadata(meta) {
  2868. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2869. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2870. function(code, d1, d2, d3) {
  2871. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2872. });
  2873. var chars = '';
  2874. for (var i = 0; i < bytes.length; i += 2) {
  2875. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2876. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2877. code !== 38 && false ? String.fromCharCode(code) :
  2878. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2879. }
  2880. return '>' + chars;
  2881. });
  2882. }
  2883. function Metadata(meta) {
  2884. if (typeof meta === 'string') {
  2885. // Ghostscript produces invalid metadata
  2886. meta = fixMetadata(meta);
  2887. var parser = new DOMParser();
  2888. meta = parser.parseFromString(meta, 'application/xml');
  2889. } else if (!(meta instanceof Document)) {
  2890. error('Metadata: Invalid metadata object');
  2891. }
  2892. this.metaDocument = meta;
  2893. this.metadata = {};
  2894. this.parse();
  2895. }
  2896. Metadata.prototype = {
  2897. parse: function Metadata_parse() {
  2898. var doc = this.metaDocument;
  2899. var rdf = doc.documentElement;
  2900. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2901. rdf = rdf.firstChild;
  2902. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2903. rdf = rdf.nextSibling;
  2904. }
  2905. }
  2906. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2907. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2908. return;
  2909. }
  2910. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2911. for (i = 0, length = children.length; i < length; i++) {
  2912. desc = children[i];
  2913. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2914. continue;
  2915. }
  2916. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2917. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2918. entry = desc.childNodes[ii];
  2919. name = entry.nodeName.toLowerCase();
  2920. this.metadata[name] = entry.textContent.trim();
  2921. }
  2922. }
  2923. }
  2924. },
  2925. get: function Metadata_get(name) {
  2926. return this.metadata[name] || null;
  2927. },
  2928. has: function Metadata_has(name) {
  2929. return typeof this.metadata[name] !== 'undefined';
  2930. }
  2931. };
  2932. return Metadata;
  2933. })();
  2934. // <canvas> contexts store most of the state we need natively.
  2935. // However, PDF needs a bit more state, which we store here.
  2936. // Minimal font size that would be used during canvas fillText operations.
  2937. var MIN_FONT_SIZE = 16;
  2938. // Maximum font size that would be used during canvas fillText operations.
  2939. var MAX_FONT_SIZE = 100;
  2940. var MAX_GROUP_SIZE = 4096;
  2941. // Heuristic value used when enforcing minimum line widths.
  2942. var MIN_WIDTH_FACTOR = 0.65;
  2943. var COMPILE_TYPE3_GLYPHS = true;
  2944. var MAX_SIZE_TO_COMPILE = 1000;
  2945. var FULL_CHUNK_HEIGHT = 16;
  2946. function createScratchCanvas(width, height) {
  2947. var canvas = document.createElement('canvas');
  2948. canvas.width = width;
  2949. canvas.height = height;
  2950. return canvas;
  2951. }
  2952. function addContextCurrentTransform(ctx) {
  2953. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  2954. if (!ctx.mozCurrentTransform) {
  2955. ctx._originalSave = ctx.save;
  2956. ctx._originalRestore = ctx.restore;
  2957. ctx._originalRotate = ctx.rotate;
  2958. ctx._originalScale = ctx.scale;
  2959. ctx._originalTranslate = ctx.translate;
  2960. ctx._originalTransform = ctx.transform;
  2961. ctx._originalSetTransform = ctx.setTransform;
  2962. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  2963. ctx._transformStack = [];
  2964. Object.defineProperty(ctx, 'mozCurrentTransform', {
  2965. get: function getCurrentTransform() {
  2966. return this._transformMatrix;
  2967. }
  2968. });
  2969. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  2970. get: function getCurrentTransformInverse() {
  2971. // Calculation done using WolframAlpha:
  2972. // http://www.wolframalpha.com/input/?
  2973. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  2974. var m = this._transformMatrix;
  2975. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  2976. var ad_bc = a * d - b * c;
  2977. var bc_ad = b * c - a * d;
  2978. return [
  2979. d / ad_bc,
  2980. b / bc_ad,
  2981. c / bc_ad,
  2982. a / ad_bc,
  2983. (d * e - c * f) / bc_ad,
  2984. (b * e - a * f) / ad_bc
  2985. ];
  2986. }
  2987. });
  2988. ctx.save = function ctxSave() {
  2989. var old = this._transformMatrix;
  2990. this._transformStack.push(old);
  2991. this._transformMatrix = old.slice(0, 6);
  2992. this._originalSave();
  2993. };
  2994. ctx.restore = function ctxRestore() {
  2995. var prev = this._transformStack.pop();
  2996. if (prev) {
  2997. this._transformMatrix = prev;
  2998. this._originalRestore();
  2999. }
  3000. };
  3001. ctx.translate = function ctxTranslate(x, y) {
  3002. var m = this._transformMatrix;
  3003. m[4] = m[0] * x + m[2] * y + m[4];
  3004. m[5] = m[1] * x + m[3] * y + m[5];
  3005. this._originalTranslate(x, y);
  3006. };
  3007. ctx.scale = function ctxScale(x, y) {
  3008. var m = this._transformMatrix;
  3009. m[0] = m[0] * x;
  3010. m[1] = m[1] * x;
  3011. m[2] = m[2] * y;
  3012. m[3] = m[3] * y;
  3013. this._originalScale(x, y);
  3014. };
  3015. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  3016. var m = this._transformMatrix;
  3017. this._transformMatrix = [
  3018. m[0] * a + m[2] * b,
  3019. m[1] * a + m[3] * b,
  3020. m[0] * c + m[2] * d,
  3021. m[1] * c + m[3] * d,
  3022. m[0] * e + m[2] * f + m[4],
  3023. m[1] * e + m[3] * f + m[5]
  3024. ];
  3025. ctx._originalTransform(a, b, c, d, e, f);
  3026. };
  3027. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  3028. this._transformMatrix = [a, b, c, d, e, f];
  3029. ctx._originalSetTransform(a, b, c, d, e, f);
  3030. };
  3031. ctx.rotate = function ctxRotate(angle) {
  3032. var cosValue = Math.cos(angle);
  3033. var sinValue = Math.sin(angle);
  3034. var m = this._transformMatrix;
  3035. this._transformMatrix = [
  3036. m[0] * cosValue + m[2] * sinValue,
  3037. m[1] * cosValue + m[3] * sinValue,
  3038. m[0] * (-sinValue) + m[2] * cosValue,
  3039. m[1] * (-sinValue) + m[3] * cosValue,
  3040. m[4],
  3041. m[5]
  3042. ];
  3043. this._originalRotate(angle);
  3044. };
  3045. }
  3046. }
  3047. var CachedCanvases = (function CachedCanvasesClosure() {
  3048. var cache = {};
  3049. return {
  3050. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  3051. trackTransform) {
  3052. var canvasEntry;
  3053. if (cache[id] !== undefined) {
  3054. canvasEntry = cache[id];
  3055. canvasEntry.canvas.width = width;
  3056. canvasEntry.canvas.height = height;
  3057. // reset canvas transform for emulated mozCurrentTransform, if needed
  3058. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  3059. } else {
  3060. var canvas = createScratchCanvas(width, height);
  3061. var ctx = canvas.getContext('2d');
  3062. if (trackTransform) {
  3063. addContextCurrentTransform(ctx);
  3064. }
  3065. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  3066. }
  3067. return canvasEntry;
  3068. },
  3069. clear: function () {
  3070. for (var id in cache) {
  3071. var canvasEntry = cache[id];
  3072. // Zeroing the width and height causes Firefox to release graphics
  3073. // resources immediately, which can greatly reduce memory consumption.
  3074. canvasEntry.canvas.width = 0;
  3075. canvasEntry.canvas.height = 0;
  3076. delete cache[id];
  3077. }
  3078. }
  3079. };
  3080. })();
  3081. function compileType3Glyph(imgData) {
  3082. var POINT_TO_PROCESS_LIMIT = 1000;
  3083. var width = imgData.width, height = imgData.height;
  3084. var i, j, j0, width1 = width + 1;
  3085. var points = new Uint8Array(width1 * (height + 1));
  3086. var POINT_TYPES =
  3087. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  3088. // decodes bit-packed mask data
  3089. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  3090. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  3091. for (i = 0, ii = data0.length; i < ii; i++) {
  3092. var mask = 128, elem = data0[i];
  3093. while (mask > 0) {
  3094. data[pos++] = (elem & mask) ? 0 : 255;
  3095. mask >>= 1;
  3096. }
  3097. }
  3098. // finding iteresting points: every point is located between mask pixels,
  3099. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  3100. // will have flags assigned based on neighboring mask pixels:
  3101. // 4 | 8
  3102. // --P--
  3103. // 2 | 1
  3104. // We are interested only in points with the flags:
  3105. // - outside corners: 1, 2, 4, 8;
  3106. // - inside corners: 7, 11, 13, 14;
  3107. // - and, intersections: 5, 10.
  3108. var count = 0;
  3109. pos = 0;
  3110. if (data[pos] !== 0) {
  3111. points[0] = 1;
  3112. ++count;
  3113. }
  3114. for (j = 1; j < width; j++) {
  3115. if (data[pos] !== data[pos + 1]) {
  3116. points[j] = data[pos] ? 2 : 1;
  3117. ++count;
  3118. }
  3119. pos++;
  3120. }
  3121. if (data[pos] !== 0) {
  3122. points[j] = 2;
  3123. ++count;
  3124. }
  3125. for (i = 1; i < height; i++) {
  3126. pos = i * lineSize;
  3127. j0 = i * width1;
  3128. if (data[pos - lineSize] !== data[pos]) {
  3129. points[j0] = data[pos] ? 1 : 8;
  3130. ++count;
  3131. }
  3132. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  3133. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  3134. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  3135. for (j = 1; j < width; j++) {
  3136. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  3137. (data[pos - lineSize + 1] ? 8 : 0);
  3138. if (POINT_TYPES[sum]) {
  3139. points[j0 + j] = POINT_TYPES[sum];
  3140. ++count;
  3141. }
  3142. pos++;
  3143. }
  3144. if (data[pos - lineSize] !== data[pos]) {
  3145. points[j0 + j] = data[pos] ? 2 : 4;
  3146. ++count;
  3147. }
  3148. if (count > POINT_TO_PROCESS_LIMIT) {
  3149. return null;
  3150. }
  3151. }
  3152. pos = lineSize * (height - 1);
  3153. j0 = i * width1;
  3154. if (data[pos] !== 0) {
  3155. points[j0] = 8;
  3156. ++count;
  3157. }
  3158. for (j = 1; j < width; j++) {
  3159. if (data[pos] !== data[pos + 1]) {
  3160. points[j0 + j] = data[pos] ? 4 : 8;
  3161. ++count;
  3162. }
  3163. pos++;
  3164. }
  3165. if (data[pos] !== 0) {
  3166. points[j0 + j] = 4;
  3167. ++count;
  3168. }
  3169. if (count > POINT_TO_PROCESS_LIMIT) {
  3170. return null;
  3171. }
  3172. // building outlines
  3173. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  3174. var outlines = [];
  3175. for (i = 0; count && i <= height; i++) {
  3176. var p = i * width1;
  3177. var end = p + width;
  3178. while (p < end && !points[p]) {
  3179. p++;
  3180. }
  3181. if (p === end) {
  3182. continue;
  3183. }
  3184. var coords = [p % width1, i];
  3185. var type = points[p], p0 = p, pp;
  3186. do {
  3187. var step = steps[type];
  3188. do {
  3189. p += step;
  3190. } while (!points[p]);
  3191. pp = points[p];
  3192. if (pp !== 5 && pp !== 10) {
  3193. // set new direction
  3194. type = pp;
  3195. // delete mark
  3196. points[p] = 0;
  3197. } else { // type is 5 or 10, ie, a crossing
  3198. // set new direction
  3199. type = pp & ((0x33 * type) >> 4);
  3200. // set new type for "future hit"
  3201. points[p] &= (type >> 2 | type << 2);
  3202. }
  3203. coords.push(p % width1);
  3204. coords.push((p / width1) | 0);
  3205. --count;
  3206. } while (p0 !== p);
  3207. outlines.push(coords);
  3208. --i;
  3209. }
  3210. var drawOutline = function(c) {
  3211. c.save();
  3212. // the path shall be painted in [0..1]x[0..1] space
  3213. c.scale(1 / width, -1 / height);
  3214. c.translate(0, -height);
  3215. c.beginPath();
  3216. for (var i = 0, ii = outlines.length; i < ii; i++) {
  3217. var o = outlines[i];
  3218. c.moveTo(o[0], o[1]);
  3219. for (var j = 2, jj = o.length; j < jj; j += 2) {
  3220. c.lineTo(o[j], o[j+1]);
  3221. }
  3222. }
  3223. c.fill();
  3224. c.beginPath();
  3225. c.restore();
  3226. };
  3227. return drawOutline;
  3228. }
  3229. var CanvasExtraState = (function CanvasExtraStateClosure() {
  3230. function CanvasExtraState(old) {
  3231. // Are soft masks and alpha values shapes or opacities?
  3232. this.alphaIsShape = false;
  3233. this.fontSize = 0;
  3234. this.fontSizeScale = 1;
  3235. this.textMatrix = IDENTITY_MATRIX;
  3236. this.textMatrixScale = 1;
  3237. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3238. this.leading = 0;
  3239. // Current point (in user coordinates)
  3240. this.x = 0;
  3241. this.y = 0;
  3242. // Start of text line (in text coordinates)
  3243. this.lineX = 0;
  3244. this.lineY = 0;
  3245. // Character and word spacing
  3246. this.charSpacing = 0;
  3247. this.wordSpacing = 0;
  3248. this.textHScale = 1;
  3249. this.textRenderingMode = TextRenderingMode.FILL;
  3250. this.textRise = 0;
  3251. // Default fore and background colors
  3252. this.fillColor = '#000000';
  3253. this.strokeColor = '#000000';
  3254. this.patternFill = false;
  3255. // Note: fill alpha applies to all non-stroking operations
  3256. this.fillAlpha = 1;
  3257. this.strokeAlpha = 1;
  3258. this.lineWidth = 1;
  3259. this.activeSMask = null; // nonclonable field (see the save method below)
  3260. this.old = old;
  3261. }
  3262. CanvasExtraState.prototype = {
  3263. clone: function CanvasExtraState_clone() {
  3264. return Object.create(this);
  3265. },
  3266. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  3267. this.x = x;
  3268. this.y = y;
  3269. }
  3270. };
  3271. return CanvasExtraState;
  3272. })();
  3273. var CanvasGraphics = (function CanvasGraphicsClosure() {
  3274. // Defines the time the executeOperatorList is going to be executing
  3275. // before it stops and shedules a continue of execution.
  3276. var EXECUTION_TIME = 15;
  3277. // Defines the number of steps before checking the execution time
  3278. var EXECUTION_STEPS = 10;
  3279. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  3280. this.ctx = canvasCtx;
  3281. this.current = new CanvasExtraState();
  3282. this.stateStack = [];
  3283. this.pendingClip = null;
  3284. this.pendingEOFill = false;
  3285. this.res = null;
  3286. this.xobjs = null;
  3287. this.commonObjs = commonObjs;
  3288. this.objs = objs;
  3289. this.imageLayer = imageLayer;
  3290. this.groupStack = [];
  3291. this.processingType3 = null;
  3292. // Patterns are painted relative to the initial page/form transform, see pdf
  3293. // spec 8.7.2 NOTE 1.
  3294. this.baseTransform = null;
  3295. this.baseTransformStack = [];
  3296. this.groupLevel = 0;
  3297. this.smaskStack = [];
  3298. this.smaskCounter = 0;
  3299. this.tempSMask = null;
  3300. if (canvasCtx) {
  3301. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  3302. // the transformation must already be set in canvasCtx._transformMatrix.
  3303. addContextCurrentTransform(canvasCtx);
  3304. }
  3305. this.cachedGetSinglePixelWidth = null;
  3306. }
  3307. function putBinaryImageData(ctx, imgData) {
  3308. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  3309. ctx.putImageData(imgData, 0, 0);
  3310. return;
  3311. }
  3312. // Put the image data to the canvas in chunks, rather than putting the
  3313. // whole image at once. This saves JS memory, because the ImageData object
  3314. // is smaller. It also possibly saves C++ memory within the implementation
  3315. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  3316. // the data passed to putImageData()). |n| shouldn't be too small, however,
  3317. // because too many putImageData() calls will slow things down.
  3318. //
  3319. // Note: as written, if the last chunk is partial, the putImageData() call
  3320. // will (conceptually) put pixels past the bounds of the canvas. But
  3321. // that's ok; any such pixels are ignored.
  3322. var height = imgData.height, width = imgData.width;
  3323. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3324. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3325. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3326. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3327. var srcPos = 0, destPos;
  3328. var src = imgData.data;
  3329. var dest = chunkImgData.data;
  3330. var i, j, thisChunkHeight, elemsInThisChunk;
  3331. // There are multiple forms in which the pixel data can be passed, and
  3332. // imgData.kind tells us which one this is.
  3333. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  3334. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  3335. var srcLength = src.byteLength;
  3336. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  3337. new Uint32ArrayView(dest);
  3338. var dest32DataLength = dest32.length;
  3339. var fullSrcDiff = (width + 7) >> 3;
  3340. var white = 0xFFFFFFFF;
  3341. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  3342. 0xFF000000 : 0x000000FF;
  3343. for (i = 0; i < totalChunks; i++) {
  3344. thisChunkHeight =
  3345. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3346. destPos = 0;
  3347. for (j = 0; j < thisChunkHeight; j++) {
  3348. var srcDiff = srcLength - srcPos;
  3349. var k = 0;
  3350. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  3351. var kEndUnrolled = kEnd & ~7;
  3352. var mask = 0;
  3353. var srcByte = 0;
  3354. for (; k < kEndUnrolled; k += 8) {
  3355. srcByte = src[srcPos++];
  3356. dest32[destPos++] = (srcByte & 128) ? white : black;
  3357. dest32[destPos++] = (srcByte & 64) ? white : black;
  3358. dest32[destPos++] = (srcByte & 32) ? white : black;
  3359. dest32[destPos++] = (srcByte & 16) ? white : black;
  3360. dest32[destPos++] = (srcByte & 8) ? white : black;
  3361. dest32[destPos++] = (srcByte & 4) ? white : black;
  3362. dest32[destPos++] = (srcByte & 2) ? white : black;
  3363. dest32[destPos++] = (srcByte & 1) ? white : black;
  3364. }
  3365. for (; k < kEnd; k++) {
  3366. if (mask === 0) {
  3367. srcByte = src[srcPos++];
  3368. mask = 128;
  3369. }
  3370. dest32[destPos++] = (srcByte & mask) ? white : black;
  3371. mask >>= 1;
  3372. }
  3373. }
  3374. // We ran out of input. Make all remaining pixels transparent.
  3375. while (destPos < dest32DataLength) {
  3376. dest32[destPos++] = 0;
  3377. }
  3378. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3379. }
  3380. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  3381. // RGBA, 32-bits per pixel.
  3382. j = 0;
  3383. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  3384. for (i = 0; i < fullChunks; i++) {
  3385. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3386. srcPos += elemsInThisChunk;
  3387. ctx.putImageData(chunkImgData, 0, j);
  3388. j += FULL_CHUNK_HEIGHT;
  3389. }
  3390. if (i < totalChunks) {
  3391. elemsInThisChunk = width * partialChunkHeight * 4;
  3392. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3393. ctx.putImageData(chunkImgData, 0, j);
  3394. }
  3395. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  3396. // RGB, 24-bits per pixel.
  3397. thisChunkHeight = FULL_CHUNK_HEIGHT;
  3398. elemsInThisChunk = width * thisChunkHeight;
  3399. for (i = 0; i < totalChunks; i++) {
  3400. if (i >= fullChunks) {
  3401. thisChunkHeight = partialChunkHeight;
  3402. elemsInThisChunk = width * thisChunkHeight;
  3403. }
  3404. destPos = 0;
  3405. for (j = elemsInThisChunk; j--;) {
  3406. dest[destPos++] = src[srcPos++];
  3407. dest[destPos++] = src[srcPos++];
  3408. dest[destPos++] = src[srcPos++];
  3409. dest[destPos++] = 255;
  3410. }
  3411. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3412. }
  3413. } else {
  3414. error('bad image kind: ' + imgData.kind);
  3415. }
  3416. }
  3417. function putBinaryImageMask(ctx, imgData) {
  3418. var height = imgData.height, width = imgData.width;
  3419. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3420. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3421. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3422. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3423. var srcPos = 0;
  3424. var src = imgData.data;
  3425. var dest = chunkImgData.data;
  3426. for (var i = 0; i < totalChunks; i++) {
  3427. var thisChunkHeight =
  3428. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3429. // Expand the mask so it can be used by the canvas. Any required
  3430. // inversion has already been handled.
  3431. var destPos = 3; // alpha component offset
  3432. for (var j = 0; j < thisChunkHeight; j++) {
  3433. var mask = 0;
  3434. for (var k = 0; k < width; k++) {
  3435. if (!mask) {
  3436. var elem = src[srcPos++];
  3437. mask = 128;
  3438. }
  3439. dest[destPos] = (elem & mask) ? 0 : 255;
  3440. destPos += 4;
  3441. mask >>= 1;
  3442. }
  3443. }
  3444. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3445. }
  3446. }
  3447. function copyCtxState(sourceCtx, destCtx) {
  3448. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  3449. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  3450. 'globalCompositeOperation', 'font'];
  3451. for (var i = 0, ii = properties.length; i < ii; i++) {
  3452. var property = properties[i];
  3453. if (sourceCtx[property] !== undefined) {
  3454. destCtx[property] = sourceCtx[property];
  3455. }
  3456. }
  3457. if (sourceCtx.setLineDash !== undefined) {
  3458. destCtx.setLineDash(sourceCtx.getLineDash());
  3459. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  3460. } else if (sourceCtx.mozDashOffset !== undefined) {
  3461. destCtx.mozDash = sourceCtx.mozDash;
  3462. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  3463. }
  3464. }
  3465. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  3466. var length = bytes.length;
  3467. for (var i = 3; i < length; i += 4) {
  3468. var alpha = bytes[i];
  3469. if (alpha === 0) {
  3470. bytes[i - 3] = r0;
  3471. bytes[i - 2] = g0;
  3472. bytes[i - 1] = b0;
  3473. } else if (alpha < 255) {
  3474. var alpha_ = 255 - alpha;
  3475. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  3476. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  3477. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  3478. }
  3479. }
  3480. }
  3481. function composeSMaskAlpha(maskData, layerData) {
  3482. var length = maskData.length;
  3483. var scale = 1 / 255;
  3484. for (var i = 3; i < length; i += 4) {
  3485. var alpha = maskData[i];
  3486. layerData[i] = (layerData[i] * alpha * scale) | 0;
  3487. }
  3488. }
  3489. function composeSMaskLuminosity(maskData, layerData) {
  3490. var length = maskData.length;
  3491. for (var i = 3; i < length; i += 4) {
  3492. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  3493. (maskData[i - 2] * 152) + // * 0.59 ....
  3494. (maskData[i - 1] * 28); // * 0.11 ....
  3495. layerData[i] = (layerData[i] * y) >> 16;
  3496. }
  3497. }
  3498. function genericComposeSMask(maskCtx, layerCtx, width, height,
  3499. subtype, backdrop) {
  3500. var hasBackdrop = !!backdrop;
  3501. var r0 = hasBackdrop ? backdrop[0] : 0;
  3502. var g0 = hasBackdrop ? backdrop[1] : 0;
  3503. var b0 = hasBackdrop ? backdrop[2] : 0;
  3504. var composeFn;
  3505. if (subtype === 'Luminosity') {
  3506. composeFn = composeSMaskLuminosity;
  3507. } else {
  3508. composeFn = composeSMaskAlpha;
  3509. }
  3510. // processing image in chunks to save memory
  3511. var PIXELS_TO_PROCESS = 1048576;
  3512. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  3513. for (var row = 0; row < height; row += chunkSize) {
  3514. var chunkHeight = Math.min(chunkSize, height - row);
  3515. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  3516. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  3517. if (hasBackdrop) {
  3518. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  3519. }
  3520. composeFn(maskData.data, layerData.data);
  3521. maskCtx.putImageData(layerData, 0, row);
  3522. }
  3523. }
  3524. function composeSMask(ctx, smask, layerCtx) {
  3525. var mask = smask.canvas;
  3526. var maskCtx = smask.context;
  3527. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  3528. smask.offsetX, smask.offsetY);
  3529. var backdrop = smask.backdrop || null;
  3530. if (WebGLUtils.isEnabled) {
  3531. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  3532. {subtype: smask.subtype, backdrop: backdrop});
  3533. ctx.setTransform(1, 0, 0, 1, 0, 0);
  3534. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  3535. return;
  3536. }
  3537. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  3538. smask.subtype, backdrop);
  3539. ctx.drawImage(mask, 0, 0);
  3540. }
  3541. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3542. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3543. var NORMAL_CLIP = {};
  3544. var EO_CLIP = {};
  3545. CanvasGraphics.prototype = {
  3546. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  3547. // For pdfs that use blend modes we have to clear the canvas else certain
  3548. // blend modes can look wrong since we'd be blending with a white
  3549. // backdrop. The problem with a transparent backdrop though is we then
  3550. // don't get sub pixel anti aliasing on text, so we fill with white if
  3551. // we can.
  3552. var width = this.ctx.canvas.width;
  3553. var height = this.ctx.canvas.height;
  3554. if (transparency) {
  3555. this.ctx.clearRect(0, 0, width, height);
  3556. } else {
  3557. this.ctx.mozOpaque = true;
  3558. this.ctx.save();
  3559. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  3560. this.ctx.fillRect(0, 0, width, height);
  3561. this.ctx.restore();
  3562. }
  3563. var transform = viewport.transform;
  3564. this.ctx.save();
  3565. this.ctx.transform.apply(this.ctx, transform);
  3566. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  3567. if (this.imageLayer) {
  3568. this.imageLayer.beginLayout();
  3569. }
  3570. },
  3571. executeOperatorList: function CanvasGraphics_executeOperatorList(
  3572. operatorList,
  3573. executionStartIdx, continueCallback,
  3574. stepper) {
  3575. var argsArray = operatorList.argsArray;
  3576. var fnArray = operatorList.fnArray;
  3577. var i = executionStartIdx || 0;
  3578. var argsArrayLen = argsArray.length;
  3579. // Sometimes the OperatorList to execute is empty.
  3580. if (argsArrayLen === i) {
  3581. return i;
  3582. }
  3583. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  3584. typeof continueCallback === 'function');
  3585. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  3586. var steps = 0;
  3587. var commonObjs = this.commonObjs;
  3588. var objs = this.objs;
  3589. var fnId;
  3590. while (true) {
  3591. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  3592. stepper.breakIt(i, continueCallback);
  3593. return i;
  3594. }
  3595. fnId = fnArray[i];
  3596. if (fnId !== OPS.dependency) {
  3597. this[fnId].apply(this, argsArray[i]);
  3598. } else {
  3599. var deps = argsArray[i];
  3600. for (var n = 0, nn = deps.length; n < nn; n++) {
  3601. var depObjId = deps[n];
  3602. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  3603. var objsPool = common ? commonObjs : objs;
  3604. // If the promise isn't resolved yet, add the continueCallback
  3605. // to the promise and bail out.
  3606. if (!objsPool.isResolved(depObjId)) {
  3607. objsPool.get(depObjId, continueCallback);
  3608. return i;
  3609. }
  3610. }
  3611. }
  3612. i++;
  3613. // If the entire operatorList was executed, stop as were done.
  3614. if (i === argsArrayLen) {
  3615. return i;
  3616. }
  3617. // If the execution took longer then a certain amount of time and
  3618. // `continueCallback` is specified, interrupt the execution.
  3619. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  3620. if (Date.now() > endTime) {
  3621. continueCallback();
  3622. return i;
  3623. }
  3624. steps = 0;
  3625. }
  3626. // If the operatorList isn't executed completely yet OR the execution
  3627. // time was short enough, do another execution round.
  3628. }
  3629. },
  3630. endDrawing: function CanvasGraphics_endDrawing() {
  3631. this.ctx.restore();
  3632. CachedCanvases.clear();
  3633. WebGLUtils.clear();
  3634. if (this.imageLayer) {
  3635. this.imageLayer.endLayout();
  3636. }
  3637. },
  3638. // Graphics state
  3639. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  3640. this.current.lineWidth = width;
  3641. this.ctx.lineWidth = width;
  3642. },
  3643. setLineCap: function CanvasGraphics_setLineCap(style) {
  3644. this.ctx.lineCap = LINE_CAP_STYLES[style];
  3645. },
  3646. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  3647. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  3648. },
  3649. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  3650. this.ctx.miterLimit = limit;
  3651. },
  3652. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  3653. var ctx = this.ctx;
  3654. if (ctx.setLineDash !== undefined) {
  3655. ctx.setLineDash(dashArray);
  3656. ctx.lineDashOffset = dashPhase;
  3657. } else {
  3658. ctx.mozDash = dashArray;
  3659. ctx.mozDashOffset = dashPhase;
  3660. }
  3661. },
  3662. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  3663. // Maybe if we one day fully support color spaces this will be important
  3664. // for now we can ignore.
  3665. // TODO set rendering intent?
  3666. },
  3667. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  3668. // There's no way to control this with canvas, but we can safely ignore.
  3669. // TODO set flatness?
  3670. },
  3671. setGState: function CanvasGraphics_setGState(states) {
  3672. for (var i = 0, ii = states.length; i < ii; i++) {
  3673. var state = states[i];
  3674. var key = state[0];
  3675. var value = state[1];
  3676. switch (key) {
  3677. case 'LW':
  3678. this.setLineWidth(value);
  3679. break;
  3680. case 'LC':
  3681. this.setLineCap(value);
  3682. break;
  3683. case 'LJ':
  3684. this.setLineJoin(value);
  3685. break;
  3686. case 'ML':
  3687. this.setMiterLimit(value);
  3688. break;
  3689. case 'D':
  3690. this.setDash(value[0], value[1]);
  3691. break;
  3692. case 'RI':
  3693. this.setRenderingIntent(value);
  3694. break;
  3695. case 'FL':
  3696. this.setFlatness(value);
  3697. break;
  3698. case 'Font':
  3699. this.setFont(value[0], value[1]);
  3700. break;
  3701. case 'CA':
  3702. this.current.strokeAlpha = state[1];
  3703. break;
  3704. case 'ca':
  3705. this.current.fillAlpha = state[1];
  3706. this.ctx.globalAlpha = state[1];
  3707. break;
  3708. case 'BM':
  3709. if (value && value.name && (value.name !== 'Normal')) {
  3710. var mode = value.name.replace(/([A-Z])/g,
  3711. function(c) {
  3712. return '-' + c.toLowerCase();
  3713. }
  3714. ).substring(1);
  3715. this.ctx.globalCompositeOperation = mode;
  3716. if (this.ctx.globalCompositeOperation !== mode) {
  3717. warn('globalCompositeOperation "' + mode +
  3718. '" is not supported');
  3719. }
  3720. } else {
  3721. this.ctx.globalCompositeOperation = 'source-over';
  3722. }
  3723. break;
  3724. case 'SMask':
  3725. if (this.current.activeSMask) {
  3726. this.endSMaskGroup();
  3727. }
  3728. this.current.activeSMask = value ? this.tempSMask : null;
  3729. if (this.current.activeSMask) {
  3730. this.beginSMaskGroup();
  3731. }
  3732. this.tempSMask = null;
  3733. break;
  3734. }
  3735. }
  3736. },
  3737. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  3738. var activeSMask = this.current.activeSMask;
  3739. var drawnWidth = activeSMask.canvas.width;
  3740. var drawnHeight = activeSMask.canvas.height;
  3741. var cacheId = 'smaskGroupAt' + this.groupLevel;
  3742. var scratchCanvas = CachedCanvases.getCanvas(
  3743. cacheId, drawnWidth, drawnHeight, true);
  3744. var currentCtx = this.ctx;
  3745. var currentTransform = currentCtx.mozCurrentTransform;
  3746. this.ctx.save();
  3747. var groupCtx = scratchCanvas.context;
  3748. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  3749. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  3750. groupCtx.transform.apply(groupCtx, currentTransform);
  3751. copyCtxState(currentCtx, groupCtx);
  3752. this.ctx = groupCtx;
  3753. this.setGState([
  3754. ['BM', 'Normal'],
  3755. ['ca', 1],
  3756. ['CA', 1]
  3757. ]);
  3758. this.groupStack.push(currentCtx);
  3759. this.groupLevel++;
  3760. },
  3761. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  3762. var groupCtx = this.ctx;
  3763. this.groupLevel--;
  3764. this.ctx = this.groupStack.pop();
  3765. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  3766. this.ctx.restore();
  3767. },
  3768. save: function CanvasGraphics_save() {
  3769. this.ctx.save();
  3770. var old = this.current;
  3771. this.stateStack.push(old);
  3772. this.current = old.clone();
  3773. this.current.activeSMask = null;
  3774. },
  3775. restore: function CanvasGraphics_restore() {
  3776. if (this.stateStack.length !== 0) {
  3777. if (this.current.activeSMask !== null) {
  3778. this.endSMaskGroup();
  3779. }
  3780. this.current = this.stateStack.pop();
  3781. this.ctx.restore();
  3782. this.cachedGetSinglePixelWidth = null;
  3783. }
  3784. },
  3785. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  3786. this.ctx.transform(a, b, c, d, e, f);
  3787. this.cachedGetSinglePixelWidth = null;
  3788. },
  3789. // Path
  3790. constructPath: function CanvasGraphics_constructPath(ops, args) {
  3791. var ctx = this.ctx;
  3792. var current = this.current;
  3793. var x = current.x, y = current.y;
  3794. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  3795. switch (ops[i] | 0) {
  3796. case OPS.rectangle:
  3797. x = args[j++];
  3798. y = args[j++];
  3799. var width = args[j++];
  3800. var height = args[j++];
  3801. if (width === 0) {
  3802. width = this.getSinglePixelWidth();
  3803. }
  3804. if (height === 0) {
  3805. height = this.getSinglePixelWidth();
  3806. }
  3807. var xw = x + width;
  3808. var yh = y + height;
  3809. this.ctx.moveTo(x, y);
  3810. this.ctx.lineTo(xw, y);
  3811. this.ctx.lineTo(xw, yh);
  3812. this.ctx.lineTo(x, yh);
  3813. this.ctx.lineTo(x, y);
  3814. this.ctx.closePath();
  3815. break;
  3816. case OPS.moveTo:
  3817. x = args[j++];
  3818. y = args[j++];
  3819. ctx.moveTo(x, y);
  3820. break;
  3821. case OPS.lineTo:
  3822. x = args[j++];
  3823. y = args[j++];
  3824. ctx.lineTo(x, y);
  3825. break;
  3826. case OPS.curveTo:
  3827. x = args[j + 4];
  3828. y = args[j + 5];
  3829. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  3830. x, y);
  3831. j += 6;
  3832. break;
  3833. case OPS.curveTo2:
  3834. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  3835. args[j + 2], args[j + 3]);
  3836. x = args[j + 2];
  3837. y = args[j + 3];
  3838. j += 4;
  3839. break;
  3840. case OPS.curveTo3:
  3841. x = args[j + 2];
  3842. y = args[j + 3];
  3843. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  3844. j += 4;
  3845. break;
  3846. case OPS.closePath:
  3847. ctx.closePath();
  3848. break;
  3849. }
  3850. }
  3851. current.setCurrentPoint(x, y);
  3852. },
  3853. closePath: function CanvasGraphics_closePath() {
  3854. this.ctx.closePath();
  3855. },
  3856. stroke: function CanvasGraphics_stroke(consumePath) {
  3857. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3858. var ctx = this.ctx;
  3859. var strokeColor = this.current.strokeColor;
  3860. // Prevent drawing too thin lines by enforcing a minimum line width.
  3861. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  3862. this.current.lineWidth);
  3863. // For stroke we want to temporarily change the global alpha to the
  3864. // stroking alpha.
  3865. ctx.globalAlpha = this.current.strokeAlpha;
  3866. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  3867. strokeColor.type === 'Pattern') {
  3868. // for patterns, we transform to pattern space, calculate
  3869. // the pattern, call stroke, and restore to user space
  3870. ctx.save();
  3871. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  3872. ctx.stroke();
  3873. ctx.restore();
  3874. } else {
  3875. ctx.stroke();
  3876. }
  3877. if (consumePath) {
  3878. this.consumePath();
  3879. }
  3880. // Restore the global alpha to the fill alpha
  3881. ctx.globalAlpha = this.current.fillAlpha;
  3882. },
  3883. closeStroke: function CanvasGraphics_closeStroke() {
  3884. this.closePath();
  3885. this.stroke();
  3886. },
  3887. fill: function CanvasGraphics_fill(consumePath) {
  3888. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3889. var ctx = this.ctx;
  3890. var fillColor = this.current.fillColor;
  3891. var isPatternFill = this.current.patternFill;
  3892. var needRestore = false;
  3893. if (isPatternFill) {
  3894. ctx.save();
  3895. ctx.fillStyle = fillColor.getPattern(ctx, this);
  3896. needRestore = true;
  3897. }
  3898. if (this.pendingEOFill) {
  3899. if (ctx.mozFillRule !== undefined) {
  3900. ctx.mozFillRule = 'evenodd';
  3901. ctx.fill();
  3902. ctx.mozFillRule = 'nonzero';
  3903. } else {
  3904. try {
  3905. ctx.fill('evenodd');
  3906. } catch (ex) {
  3907. // shouldn't really happen, but browsers might think differently
  3908. ctx.fill();
  3909. }
  3910. }
  3911. this.pendingEOFill = false;
  3912. } else {
  3913. ctx.fill();
  3914. }
  3915. if (needRestore) {
  3916. ctx.restore();
  3917. }
  3918. if (consumePath) {
  3919. this.consumePath();
  3920. }
  3921. },
  3922. eoFill: function CanvasGraphics_eoFill() {
  3923. this.pendingEOFill = true;
  3924. this.fill();
  3925. },
  3926. fillStroke: function CanvasGraphics_fillStroke() {
  3927. this.fill(false);
  3928. this.stroke(false);
  3929. this.consumePath();
  3930. },
  3931. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  3932. this.pendingEOFill = true;
  3933. this.fillStroke();
  3934. },
  3935. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  3936. this.closePath();
  3937. this.fillStroke();
  3938. },
  3939. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  3940. this.pendingEOFill = true;
  3941. this.closePath();
  3942. this.fillStroke();
  3943. },
  3944. endPath: function CanvasGraphics_endPath() {
  3945. this.consumePath();
  3946. },
  3947. // Clipping
  3948. clip: function CanvasGraphics_clip() {
  3949. this.pendingClip = NORMAL_CLIP;
  3950. },
  3951. eoClip: function CanvasGraphics_eoClip() {
  3952. this.pendingClip = EO_CLIP;
  3953. },
  3954. // Text
  3955. beginText: function CanvasGraphics_beginText() {
  3956. this.current.textMatrix = IDENTITY_MATRIX;
  3957. this.current.textMatrixScale = 1;
  3958. this.current.x = this.current.lineX = 0;
  3959. this.current.y = this.current.lineY = 0;
  3960. },
  3961. endText: function CanvasGraphics_endText() {
  3962. var paths = this.pendingTextPaths;
  3963. var ctx = this.ctx;
  3964. if (paths === undefined) {
  3965. ctx.beginPath();
  3966. return;
  3967. }
  3968. ctx.save();
  3969. ctx.beginPath();
  3970. for (var i = 0; i < paths.length; i++) {
  3971. var path = paths[i];
  3972. ctx.setTransform.apply(ctx, path.transform);
  3973. ctx.translate(path.x, path.y);
  3974. path.addToPath(ctx, path.fontSize);
  3975. }
  3976. ctx.restore();
  3977. ctx.clip();
  3978. ctx.beginPath();
  3979. delete this.pendingTextPaths;
  3980. },
  3981. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  3982. this.current.charSpacing = spacing;
  3983. },
  3984. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  3985. this.current.wordSpacing = spacing;
  3986. },
  3987. setHScale: function CanvasGraphics_setHScale(scale) {
  3988. this.current.textHScale = scale / 100;
  3989. },
  3990. setLeading: function CanvasGraphics_setLeading(leading) {
  3991. this.current.leading = -leading;
  3992. },
  3993. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  3994. var fontObj = this.commonObjs.get(fontRefName);
  3995. var current = this.current;
  3996. if (!fontObj) {
  3997. error('Can\'t find font for ' + fontRefName);
  3998. }
  3999. current.fontMatrix = (fontObj.fontMatrix ?
  4000. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  4001. // A valid matrix needs all main diagonal elements to be non-zero
  4002. // This also ensures we bypass FF bugzilla bug #719844.
  4003. if (current.fontMatrix[0] === 0 ||
  4004. current.fontMatrix[3] === 0) {
  4005. warn('Invalid font matrix for font ' + fontRefName);
  4006. }
  4007. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  4008. // and in some docs this can be negative (inverted x-y axes).
  4009. if (size < 0) {
  4010. size = -size;
  4011. current.fontDirection = -1;
  4012. } else {
  4013. current.fontDirection = 1;
  4014. }
  4015. this.current.font = fontObj;
  4016. this.current.fontSize = size;
  4017. if (fontObj.isType3Font) {
  4018. return; // we don't need ctx.font for Type3 fonts
  4019. }
  4020. var name = fontObj.loadedName || 'sans-serif';
  4021. var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
  4022. (fontObj.bold ? 'bold' : 'normal');
  4023. var italic = fontObj.italic ? 'italic' : 'normal';
  4024. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  4025. // Some font backends cannot handle fonts below certain size.
  4026. // Keeping the font at minimal size and using the fontSizeScale to change
  4027. // the current transformation matrix before the fillText/strokeText.
  4028. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  4029. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  4030. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  4031. this.current.fontSizeScale = size / browserFontSize;
  4032. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  4033. this.ctx.font = rule;
  4034. },
  4035. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  4036. this.current.textRenderingMode = mode;
  4037. },
  4038. setTextRise: function CanvasGraphics_setTextRise(rise) {
  4039. this.current.textRise = rise;
  4040. },
  4041. moveText: function CanvasGraphics_moveText(x, y) {
  4042. this.current.x = this.current.lineX += x;
  4043. this.current.y = this.current.lineY += y;
  4044. },
  4045. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  4046. this.setLeading(-y);
  4047. this.moveText(x, y);
  4048. },
  4049. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  4050. this.current.textMatrix = [a, b, c, d, e, f];
  4051. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  4052. this.current.x = this.current.lineX = 0;
  4053. this.current.y = this.current.lineY = 0;
  4054. },
  4055. nextLine: function CanvasGraphics_nextLine() {
  4056. this.moveText(0, this.current.leading);
  4057. },
  4058. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  4059. var ctx = this.ctx;
  4060. var current = this.current;
  4061. var font = current.font;
  4062. var textRenderingMode = current.textRenderingMode;
  4063. var fontSize = current.fontSize / current.fontSizeScale;
  4064. var fillStrokeMode = textRenderingMode &
  4065. TextRenderingMode.FILL_STROKE_MASK;
  4066. var isAddToPathSet = !!(textRenderingMode &
  4067. TextRenderingMode.ADD_TO_PATH_FLAG);
  4068. var addToPath;
  4069. if (font.disableFontFace || isAddToPathSet) {
  4070. addToPath = font.getPathGenerator(this.commonObjs, character);
  4071. }
  4072. if (font.disableFontFace) {
  4073. ctx.save();
  4074. ctx.translate(x, y);
  4075. ctx.beginPath();
  4076. addToPath(ctx, fontSize);
  4077. if (fillStrokeMode === TextRenderingMode.FILL ||
  4078. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4079. ctx.fill();
  4080. }
  4081. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4082. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4083. ctx.stroke();
  4084. }
  4085. ctx.restore();
  4086. } else {
  4087. if (fillStrokeMode === TextRenderingMode.FILL ||
  4088. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4089. ctx.fillText(character, x, y);
  4090. }
  4091. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4092. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4093. ctx.strokeText(character, x, y);
  4094. }
  4095. }
  4096. if (isAddToPathSet) {
  4097. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  4098. paths.push({
  4099. transform: ctx.mozCurrentTransform,
  4100. x: x,
  4101. y: y,
  4102. fontSize: fontSize,
  4103. addToPath: addToPath
  4104. });
  4105. }
  4106. },
  4107. get isFontSubpixelAAEnabled() {
  4108. // Checks if anti-aliasing is enabled when scaled text is painted.
  4109. // On Windows GDI scaled fonts looks bad.
  4110. var ctx = document.createElement('canvas').getContext('2d');
  4111. ctx.scale(1.5, 1);
  4112. ctx.fillText('I', 0, 10);
  4113. var data = ctx.getImageData(0, 0, 10, 10).data;
  4114. var enabled = false;
  4115. for (var i = 3; i < data.length; i += 4) {
  4116. if (data[i] > 0 && data[i] < 255) {
  4117. enabled = true;
  4118. break;
  4119. }
  4120. }
  4121. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  4122. },
  4123. showText: function CanvasGraphics_showText(glyphs) {
  4124. var current = this.current;
  4125. var font = current.font;
  4126. if (font.isType3Font) {
  4127. return this.showType3Text(glyphs);
  4128. }
  4129. var fontSize = current.fontSize;
  4130. if (fontSize === 0) {
  4131. return;
  4132. }
  4133. var ctx = this.ctx;
  4134. var fontSizeScale = current.fontSizeScale;
  4135. var charSpacing = current.charSpacing;
  4136. var wordSpacing = current.wordSpacing;
  4137. var fontDirection = current.fontDirection;
  4138. var textHScale = current.textHScale * fontDirection;
  4139. var glyphsLength = glyphs.length;
  4140. var vertical = font.vertical;
  4141. var defaultVMetrics = font.defaultVMetrics;
  4142. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  4143. var simpleFillText =
  4144. current.textRenderingMode === TextRenderingMode.FILL &&
  4145. !font.disableFontFace;
  4146. ctx.save();
  4147. ctx.transform.apply(ctx, current.textMatrix);
  4148. ctx.translate(current.x, current.y + current.textRise);
  4149. if (fontDirection > 0) {
  4150. ctx.scale(textHScale, -1);
  4151. } else {
  4152. ctx.scale(textHScale, 1);
  4153. }
  4154. var lineWidth = current.lineWidth;
  4155. var scale = current.textMatrixScale;
  4156. if (scale === 0 || lineWidth === 0) {
  4157. var fillStrokeMode = current.textRenderingMode &
  4158. TextRenderingMode.FILL_STROKE_MASK;
  4159. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4160. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4161. this.cachedGetSinglePixelWidth = null;
  4162. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  4163. }
  4164. } else {
  4165. lineWidth /= scale;
  4166. }
  4167. if (fontSizeScale !== 1.0) {
  4168. ctx.scale(fontSizeScale, fontSizeScale);
  4169. lineWidth /= fontSizeScale;
  4170. }
  4171. ctx.lineWidth = lineWidth;
  4172. var x = 0, i;
  4173. for (i = 0; i < glyphsLength; ++i) {
  4174. var glyph = glyphs[i];
  4175. if (glyph === null) {
  4176. // word break
  4177. x += fontDirection * wordSpacing;
  4178. continue;
  4179. } else if (isNum(glyph)) {
  4180. x += -glyph * fontSize * 0.001;
  4181. continue;
  4182. }
  4183. var restoreNeeded = false;
  4184. var character = glyph.fontChar;
  4185. var accent = glyph.accent;
  4186. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  4187. var width = glyph.width;
  4188. if (vertical) {
  4189. var vmetric, vx, vy;
  4190. vmetric = glyph.vmetric || defaultVMetrics;
  4191. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  4192. vx = -vx * widthAdvanceScale;
  4193. vy = vmetric[2] * widthAdvanceScale;
  4194. width = vmetric ? -vmetric[0] : width;
  4195. scaledX = vx / fontSizeScale;
  4196. scaledY = (x + vy) / fontSizeScale;
  4197. } else {
  4198. scaledX = x / fontSizeScale;
  4199. scaledY = 0;
  4200. }
  4201. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  4202. // some standard fonts may not have the exact width, trying to
  4203. // rescale per character
  4204. var measuredWidth = ctx.measureText(character).width * 1000 /
  4205. fontSize * fontSizeScale;
  4206. var characterScaleX = width / measuredWidth;
  4207. restoreNeeded = true;
  4208. ctx.save();
  4209. ctx.scale(characterScaleX, 1);
  4210. scaledX /= characterScaleX;
  4211. }
  4212. if (simpleFillText && !accent) {
  4213. // common case
  4214. ctx.fillText(character, scaledX, scaledY);
  4215. } else {
  4216. this.paintChar(character, scaledX, scaledY);
  4217. if (accent) {
  4218. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  4219. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  4220. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  4221. }
  4222. }
  4223. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  4224. x += charWidth;
  4225. if (restoreNeeded) {
  4226. ctx.restore();
  4227. }
  4228. }
  4229. if (vertical) {
  4230. current.y -= x * textHScale;
  4231. } else {
  4232. current.x += x * textHScale;
  4233. }
  4234. ctx.restore();
  4235. },
  4236. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  4237. // Type3 fonts - each glyph is a "mini-PDF"
  4238. var ctx = this.ctx;
  4239. var current = this.current;
  4240. var font = current.font;
  4241. var fontSize = current.fontSize;
  4242. var fontDirection = current.fontDirection;
  4243. var charSpacing = current.charSpacing;
  4244. var wordSpacing = current.wordSpacing;
  4245. var textHScale = current.textHScale * fontDirection;
  4246. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  4247. var glyphsLength = glyphs.length;
  4248. var isTextInvisible =
  4249. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  4250. var i, glyph, width;
  4251. if (isTextInvisible || fontSize === 0) {
  4252. return;
  4253. }
  4254. this.cachedGetSinglePixelWidth = null;
  4255. ctx.save();
  4256. ctx.transform.apply(ctx, current.textMatrix);
  4257. ctx.translate(current.x, current.y);
  4258. ctx.scale(textHScale, fontDirection);
  4259. for (i = 0; i < glyphsLength; ++i) {
  4260. glyph = glyphs[i];
  4261. if (glyph === null) {
  4262. // word break
  4263. this.ctx.translate(wordSpacing, 0);
  4264. current.x += wordSpacing * textHScale;
  4265. continue;
  4266. } else if (isNum(glyph)) {
  4267. var spacingLength = -glyph * 0.001 * fontSize;
  4268. this.ctx.translate(spacingLength, 0);
  4269. current.x += spacingLength * textHScale;
  4270. continue;
  4271. }
  4272. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4273. if (!operatorList) {
  4274. warn('Type3 character \"' + glyph.operatorListId +
  4275. '\" is not available');
  4276. continue;
  4277. }
  4278. this.processingType3 = glyph;
  4279. this.save();
  4280. ctx.scale(fontSize, fontSize);
  4281. ctx.transform.apply(ctx, fontMatrix);
  4282. this.executeOperatorList(operatorList);
  4283. this.restore();
  4284. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4285. width = transformed[0] * fontSize + charSpacing;
  4286. ctx.translate(width, 0);
  4287. current.x += width * textHScale;
  4288. }
  4289. ctx.restore();
  4290. this.processingType3 = null;
  4291. },
  4292. // Type3 fonts
  4293. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4294. // We can safely ignore this since the width should be the same
  4295. // as the width in the Widths array.
  4296. },
  4297. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4298. yWidth,
  4299. llx,
  4300. lly,
  4301. urx,
  4302. ury) {
  4303. // TODO According to the spec we're also suppose to ignore any operators
  4304. // that set color or include images while processing this type3 font.
  4305. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  4306. this.clip();
  4307. this.endPath();
  4308. },
  4309. // Color
  4310. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4311. var pattern;
  4312. if (IR[0] === 'TilingPattern') {
  4313. var color = IR[1];
  4314. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4315. this.commonObjs, this.baseTransform);
  4316. } else {
  4317. pattern = getShadingPatternFromIR(IR);
  4318. }
  4319. return pattern;
  4320. },
  4321. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4322. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4323. },
  4324. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4325. this.current.fillColor = this.getColorN_Pattern(arguments);
  4326. this.current.patternFill = true;
  4327. },
  4328. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4329. var color = Util.makeCssRgb(r, g, b);
  4330. this.ctx.strokeStyle = color;
  4331. this.current.strokeColor = color;
  4332. },
  4333. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4334. var color = Util.makeCssRgb(r, g, b);
  4335. this.ctx.fillStyle = color;
  4336. this.current.fillColor = color;
  4337. this.current.patternFill = false;
  4338. },
  4339. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4340. var ctx = this.ctx;
  4341. this.save();
  4342. var pattern = getShadingPatternFromIR(patternIR);
  4343. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4344. var inv = ctx.mozCurrentTransformInverse;
  4345. if (inv) {
  4346. var canvas = ctx.canvas;
  4347. var width = canvas.width;
  4348. var height = canvas.height;
  4349. var bl = Util.applyTransform([0, 0], inv);
  4350. var br = Util.applyTransform([0, height], inv);
  4351. var ul = Util.applyTransform([width, 0], inv);
  4352. var ur = Util.applyTransform([width, height], inv);
  4353. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4354. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4355. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4356. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4357. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4358. } else {
  4359. // HACK to draw the gradient onto an infinite rectangle.
  4360. // PDF gradients are drawn across the entire image while
  4361. // Canvas only allows gradients to be drawn in a rectangle
  4362. // The following bug should allow us to remove this.
  4363. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4364. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4365. }
  4366. this.restore();
  4367. },
  4368. // Images
  4369. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4370. error('Should not call beginInlineImage');
  4371. },
  4372. beginImageData: function CanvasGraphics_beginImageData() {
  4373. error('Should not call beginImageData');
  4374. },
  4375. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4376. bbox) {
  4377. this.save();
  4378. this.baseTransformStack.push(this.baseTransform);
  4379. if (isArray(matrix) && 6 === matrix.length) {
  4380. this.transform.apply(this, matrix);
  4381. }
  4382. this.baseTransform = this.ctx.mozCurrentTransform;
  4383. if (isArray(bbox) && 4 === bbox.length) {
  4384. var width = bbox[2] - bbox[0];
  4385. var height = bbox[3] - bbox[1];
  4386. this.ctx.rect(bbox[0], bbox[1], width, height);
  4387. this.clip();
  4388. this.endPath();
  4389. }
  4390. },
  4391. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4392. this.restore();
  4393. this.baseTransform = this.baseTransformStack.pop();
  4394. },
  4395. beginGroup: function CanvasGraphics_beginGroup(group) {
  4396. this.save();
  4397. var currentCtx = this.ctx;
  4398. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4399. // group results aren't usually that different and they even have tools
  4400. // that ignore this setting. Notes from Rik on implmenting:
  4401. // - When you encounter an transparency group, create a new canvas with
  4402. // the dimensions of the bbox
  4403. // - copy the content from the previous canvas to the new canvas
  4404. // - draw as usual
  4405. // - remove the backdrop alpha:
  4406. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4407. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4408. // backdrop
  4409. // - remove background color:
  4410. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4411. if (!group.isolated) {
  4412. info('TODO: Support non-isolated groups.');
  4413. }
  4414. // TODO knockout - supposedly possible with the clever use of compositing
  4415. // modes.
  4416. if (group.knockout) {
  4417. warn('Knockout groups not supported.');
  4418. }
  4419. var currentTransform = currentCtx.mozCurrentTransform;
  4420. if (group.matrix) {
  4421. currentCtx.transform.apply(currentCtx, group.matrix);
  4422. }
  4423. assert(group.bbox, 'Bounding box is required.');
  4424. // Based on the current transform figure out how big the bounding box
  4425. // will actually be.
  4426. var bounds = Util.getAxialAlignedBoundingBox(
  4427. group.bbox,
  4428. currentCtx.mozCurrentTransform);
  4429. // Clip the bounding box to the current canvas.
  4430. var canvasBounds = [0,
  4431. 0,
  4432. currentCtx.canvas.width,
  4433. currentCtx.canvas.height];
  4434. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4435. // Use ceil in case we're between sizes so we don't create canvas that is
  4436. // too small and make the canvas at least 1x1 pixels.
  4437. var offsetX = Math.floor(bounds[0]);
  4438. var offsetY = Math.floor(bounds[1]);
  4439. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4440. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4441. var scaleX = 1, scaleY = 1;
  4442. if (drawnWidth > MAX_GROUP_SIZE) {
  4443. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4444. drawnWidth = MAX_GROUP_SIZE;
  4445. }
  4446. if (drawnHeight > MAX_GROUP_SIZE) {
  4447. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4448. drawnHeight = MAX_GROUP_SIZE;
  4449. }
  4450. var cacheId = 'groupAt' + this.groupLevel;
  4451. if (group.smask) {
  4452. // Using two cache entries is case if masks are used one after another.
  4453. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4454. }
  4455. var scratchCanvas = CachedCanvases.getCanvas(
  4456. cacheId, drawnWidth, drawnHeight, true);
  4457. var groupCtx = scratchCanvas.context;
  4458. // Since we created a new canvas that is just the size of the bounding box
  4459. // we have to translate the group ctx.
  4460. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4461. groupCtx.translate(-offsetX, -offsetY);
  4462. groupCtx.transform.apply(groupCtx, currentTransform);
  4463. if (group.smask) {
  4464. // Saving state and cached mask to be used in setGState.
  4465. this.smaskStack.push({
  4466. canvas: scratchCanvas.canvas,
  4467. context: groupCtx,
  4468. offsetX: offsetX,
  4469. offsetY: offsetY,
  4470. scaleX: scaleX,
  4471. scaleY: scaleY,
  4472. subtype: group.smask.subtype,
  4473. backdrop: group.smask.backdrop
  4474. });
  4475. } else {
  4476. // Setup the current ctx so when the group is popped we draw it at the
  4477. // right location.
  4478. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4479. currentCtx.translate(offsetX, offsetY);
  4480. currentCtx.scale(scaleX, scaleY);
  4481. }
  4482. // The transparency group inherits all off the current graphics state
  4483. // except the blend mode, soft mask, and alpha constants.
  4484. copyCtxState(currentCtx, groupCtx);
  4485. this.ctx = groupCtx;
  4486. this.setGState([
  4487. ['BM', 'Normal'],
  4488. ['ca', 1],
  4489. ['CA', 1]
  4490. ]);
  4491. this.groupStack.push(currentCtx);
  4492. this.groupLevel++;
  4493. },
  4494. endGroup: function CanvasGraphics_endGroup(group) {
  4495. this.groupLevel--;
  4496. var groupCtx = this.ctx;
  4497. this.ctx = this.groupStack.pop();
  4498. // Turn off image smoothing to avoid sub pixel interpolation which can
  4499. // look kind of blurry for some pdfs.
  4500. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4501. this.ctx.imageSmoothingEnabled = false;
  4502. } else {
  4503. this.ctx.mozImageSmoothingEnabled = false;
  4504. }
  4505. if (group.smask) {
  4506. this.tempSMask = this.smaskStack.pop();
  4507. } else {
  4508. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4509. }
  4510. this.restore();
  4511. },
  4512. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4513. this.save();
  4514. this.current = new CanvasExtraState();
  4515. },
  4516. endAnnotations: function CanvasGraphics_endAnnotations() {
  4517. this.restore();
  4518. },
  4519. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4520. matrix) {
  4521. this.save();
  4522. if (isArray(rect) && 4 === rect.length) {
  4523. var width = rect[2] - rect[0];
  4524. var height = rect[3] - rect[1];
  4525. this.ctx.rect(rect[0], rect[1], width, height);
  4526. this.clip();
  4527. this.endPath();
  4528. }
  4529. this.transform.apply(this, transform);
  4530. this.transform.apply(this, matrix);
  4531. },
  4532. endAnnotation: function CanvasGraphics_endAnnotation() {
  4533. this.restore();
  4534. },
  4535. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4536. var domImage = this.objs.get(objId);
  4537. if (!domImage) {
  4538. warn('Dependent image isn\'t ready yet');
  4539. return;
  4540. }
  4541. this.save();
  4542. var ctx = this.ctx;
  4543. // scale the image to the unit square
  4544. ctx.scale(1 / w, -1 / h);
  4545. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4546. 0, -h, w, h);
  4547. if (this.imageLayer) {
  4548. var currentTransform = ctx.mozCurrentTransformInverse;
  4549. var position = this.getCanvasPosition(0, 0);
  4550. this.imageLayer.appendImage({
  4551. objId: objId,
  4552. left: position[0],
  4553. top: position[1],
  4554. width: w / currentTransform[0],
  4555. height: h / currentTransform[3]
  4556. });
  4557. }
  4558. this.restore();
  4559. },
  4560. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  4561. var ctx = this.ctx;
  4562. var width = img.width, height = img.height;
  4563. var fillColor = this.current.fillColor;
  4564. var isPatternFill = this.current.patternFill;
  4565. var glyph = this.processingType3;
  4566. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  4567. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  4568. glyph.compiled =
  4569. compileType3Glyph({data: img.data, width: width, height: height});
  4570. } else {
  4571. glyph.compiled = null;
  4572. }
  4573. }
  4574. if (glyph && glyph.compiled) {
  4575. glyph.compiled(ctx);
  4576. return;
  4577. }
  4578. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4579. var maskCtx = maskCanvas.context;
  4580. maskCtx.save();
  4581. putBinaryImageMask(maskCtx, img);
  4582. maskCtx.globalCompositeOperation = 'source-in';
  4583. maskCtx.fillStyle = isPatternFill ?
  4584. fillColor.getPattern(maskCtx, this) : fillColor;
  4585. maskCtx.fillRect(0, 0, width, height);
  4586. maskCtx.restore();
  4587. this.paintInlineImageXObject(maskCanvas.canvas);
  4588. },
  4589. paintImageMaskXObjectRepeat:
  4590. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  4591. scaleY, positions) {
  4592. var width = imgData.width;
  4593. var height = imgData.height;
  4594. var fillColor = this.current.fillColor;
  4595. var isPatternFill = this.current.patternFill;
  4596. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4597. var maskCtx = maskCanvas.context;
  4598. maskCtx.save();
  4599. putBinaryImageMask(maskCtx, imgData);
  4600. maskCtx.globalCompositeOperation = 'source-in';
  4601. maskCtx.fillStyle = isPatternFill ?
  4602. fillColor.getPattern(maskCtx, this) : fillColor;
  4603. maskCtx.fillRect(0, 0, width, height);
  4604. maskCtx.restore();
  4605. var ctx = this.ctx;
  4606. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4607. ctx.save();
  4608. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  4609. ctx.scale(1, -1);
  4610. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4611. 0, -1, 1, 1);
  4612. ctx.restore();
  4613. }
  4614. },
  4615. paintImageMaskXObjectGroup:
  4616. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  4617. var ctx = this.ctx;
  4618. var fillColor = this.current.fillColor;
  4619. var isPatternFill = this.current.patternFill;
  4620. for (var i = 0, ii = images.length; i < ii; i++) {
  4621. var image = images[i];
  4622. var width = image.width, height = image.height;
  4623. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4624. var maskCtx = maskCanvas.context;
  4625. maskCtx.save();
  4626. putBinaryImageMask(maskCtx, image);
  4627. maskCtx.globalCompositeOperation = 'source-in';
  4628. maskCtx.fillStyle = isPatternFill ?
  4629. fillColor.getPattern(maskCtx, this) : fillColor;
  4630. maskCtx.fillRect(0, 0, width, height);
  4631. maskCtx.restore();
  4632. ctx.save();
  4633. ctx.transform.apply(ctx, image.transform);
  4634. ctx.scale(1, -1);
  4635. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4636. 0, -1, 1, 1);
  4637. ctx.restore();
  4638. }
  4639. },
  4640. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  4641. var imgData = this.objs.get(objId);
  4642. if (!imgData) {
  4643. warn('Dependent image isn\'t ready yet');
  4644. return;
  4645. }
  4646. this.paintInlineImageXObject(imgData);
  4647. },
  4648. paintImageXObjectRepeat:
  4649. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  4650. positions) {
  4651. var imgData = this.objs.get(objId);
  4652. if (!imgData) {
  4653. warn('Dependent image isn\'t ready yet');
  4654. return;
  4655. }
  4656. var width = imgData.width;
  4657. var height = imgData.height;
  4658. var map = [];
  4659. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4660. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  4661. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  4662. }
  4663. this.paintInlineImageXObjectGroup(imgData, map);
  4664. },
  4665. paintInlineImageXObject:
  4666. function CanvasGraphics_paintInlineImageXObject(imgData) {
  4667. var width = imgData.width;
  4668. var height = imgData.height;
  4669. var ctx = this.ctx;
  4670. this.save();
  4671. // scale the image to the unit square
  4672. ctx.scale(1 / width, -1 / height);
  4673. var currentTransform = ctx.mozCurrentTransformInverse;
  4674. var a = currentTransform[0], b = currentTransform[1];
  4675. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  4676. var c = currentTransform[2], d = currentTransform[3];
  4677. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  4678. var imgToPaint, tmpCanvas;
  4679. // instanceof HTMLElement does not work in jsdom node.js module
  4680. if (imgData instanceof HTMLElement || !imgData.data) {
  4681. imgToPaint = imgData;
  4682. } else {
  4683. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  4684. var tmpCtx = tmpCanvas.context;
  4685. putBinaryImageData(tmpCtx, imgData);
  4686. imgToPaint = tmpCanvas.canvas;
  4687. }
  4688. var paintWidth = width, paintHeight = height;
  4689. var tmpCanvasId = 'prescale1';
  4690. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  4691. // pixels during drawImage operation, painting on the temporary canvas(es)
  4692. // that are twice smaller in size
  4693. while ((widthScale > 2 && paintWidth > 1) ||
  4694. (heightScale > 2 && paintHeight > 1)) {
  4695. var newWidth = paintWidth, newHeight = paintHeight;
  4696. if (widthScale > 2 && paintWidth > 1) {
  4697. newWidth = Math.ceil(paintWidth / 2);
  4698. widthScale /= paintWidth / newWidth;
  4699. }
  4700. if (heightScale > 2 && paintHeight > 1) {
  4701. newHeight = Math.ceil(paintHeight / 2);
  4702. heightScale /= paintHeight / newHeight;
  4703. }
  4704. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  4705. tmpCtx = tmpCanvas.context;
  4706. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  4707. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4708. 0, 0, newWidth, newHeight);
  4709. imgToPaint = tmpCanvas.canvas;
  4710. paintWidth = newWidth;
  4711. paintHeight = newHeight;
  4712. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  4713. }
  4714. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4715. 0, -height, width, height);
  4716. if (this.imageLayer) {
  4717. var position = this.getCanvasPosition(0, -height);
  4718. this.imageLayer.appendImage({
  4719. imgData: imgData,
  4720. left: position[0],
  4721. top: position[1],
  4722. width: width / currentTransform[0],
  4723. height: height / currentTransform[3]
  4724. });
  4725. }
  4726. this.restore();
  4727. },
  4728. paintInlineImageXObjectGroup:
  4729. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  4730. var ctx = this.ctx;
  4731. var w = imgData.width;
  4732. var h = imgData.height;
  4733. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  4734. var tmpCtx = tmpCanvas.context;
  4735. putBinaryImageData(tmpCtx, imgData);
  4736. for (var i = 0, ii = map.length; i < ii; i++) {
  4737. var entry = map[i];
  4738. ctx.save();
  4739. ctx.transform.apply(ctx, entry.transform);
  4740. ctx.scale(1, -1);
  4741. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  4742. 0, -1, 1, 1);
  4743. if (this.imageLayer) {
  4744. var position = this.getCanvasPosition(entry.x, entry.y);
  4745. this.imageLayer.appendImage({
  4746. imgData: imgData,
  4747. left: position[0],
  4748. top: position[1],
  4749. width: w,
  4750. height: h
  4751. });
  4752. }
  4753. ctx.restore();
  4754. }
  4755. },
  4756. paintSolidColorImageMask:
  4757. function CanvasGraphics_paintSolidColorImageMask() {
  4758. this.ctx.fillRect(0, 0, 1, 1);
  4759. },
  4760. // Marked content
  4761. markPoint: function CanvasGraphics_markPoint(tag) {
  4762. // TODO Marked content.
  4763. },
  4764. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  4765. // TODO Marked content.
  4766. },
  4767. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  4768. // TODO Marked content.
  4769. },
  4770. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  4771. tag, properties) {
  4772. // TODO Marked content.
  4773. },
  4774. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  4775. // TODO Marked content.
  4776. },
  4777. // Compatibility
  4778. beginCompat: function CanvasGraphics_beginCompat() {
  4779. // TODO ignore undefined operators (should we do that anyway?)
  4780. },
  4781. endCompat: function CanvasGraphics_endCompat() {
  4782. // TODO stop ignoring undefined operators
  4783. },
  4784. // Helper functions
  4785. consumePath: function CanvasGraphics_consumePath() {
  4786. var ctx = this.ctx;
  4787. if (this.pendingClip) {
  4788. if (this.pendingClip === EO_CLIP) {
  4789. if (ctx.mozFillRule !== undefined) {
  4790. ctx.mozFillRule = 'evenodd';
  4791. ctx.clip();
  4792. ctx.mozFillRule = 'nonzero';
  4793. } else {
  4794. try {
  4795. ctx.clip('evenodd');
  4796. } catch (ex) {
  4797. // shouldn't really happen, but browsers might think differently
  4798. ctx.clip();
  4799. }
  4800. }
  4801. } else {
  4802. ctx.clip();
  4803. }
  4804. this.pendingClip = null;
  4805. }
  4806. ctx.beginPath();
  4807. },
  4808. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  4809. if (this.cachedGetSinglePixelWidth === null) {
  4810. var inverse = this.ctx.mozCurrentTransformInverse;
  4811. // max of the current horizontal and vertical scale
  4812. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  4813. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  4814. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  4815. }
  4816. return this.cachedGetSinglePixelWidth;
  4817. },
  4818. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  4819. var transform = this.ctx.mozCurrentTransform;
  4820. return [
  4821. transform[0] * x + transform[2] * y + transform[4],
  4822. transform[1] * x + transform[3] * y + transform[5]
  4823. ];
  4824. }
  4825. };
  4826. for (var op in OPS) {
  4827. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  4828. }
  4829. return CanvasGraphics;
  4830. })();
  4831. var WebGLUtils = (function WebGLUtilsClosure() {
  4832. function loadShader(gl, code, shaderType) {
  4833. var shader = gl.createShader(shaderType);
  4834. gl.shaderSource(shader, code);
  4835. gl.compileShader(shader);
  4836. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4837. if (!compiled) {
  4838. var errorMsg = gl.getShaderInfoLog(shader);
  4839. throw new Error('Error during shader compilation: ' + errorMsg);
  4840. }
  4841. return shader;
  4842. }
  4843. function createVertexShader(gl, code) {
  4844. return loadShader(gl, code, gl.VERTEX_SHADER);
  4845. }
  4846. function createFragmentShader(gl, code) {
  4847. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4848. }
  4849. function createProgram(gl, shaders) {
  4850. var program = gl.createProgram();
  4851. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4852. gl.attachShader(program, shaders[i]);
  4853. }
  4854. gl.linkProgram(program);
  4855. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4856. if (!linked) {
  4857. var errorMsg = gl.getProgramInfoLog(program);
  4858. throw new Error('Error during program linking: ' + errorMsg);
  4859. }
  4860. return program;
  4861. }
  4862. function createTexture(gl, image, textureId) {
  4863. gl.activeTexture(textureId);
  4864. var texture = gl.createTexture();
  4865. gl.bindTexture(gl.TEXTURE_2D, texture);
  4866. // Set the parameters so we can render any size image.
  4867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4871. // Upload the image into the texture.
  4872. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4873. return texture;
  4874. }
  4875. var currentGL, currentCanvas;
  4876. function generateGL() {
  4877. if (currentGL) {
  4878. return;
  4879. }
  4880. currentCanvas = document.createElement('canvas');
  4881. currentGL = currentCanvas.getContext('webgl',
  4882. { premultipliedalpha: false });
  4883. }
  4884. var smaskVertexShaderCode = '\
  4885. attribute vec2 a_position; \
  4886. attribute vec2 a_texCoord; \
  4887. \
  4888. uniform vec2 u_resolution; \
  4889. \
  4890. varying vec2 v_texCoord; \
  4891. \
  4892. void main() { \
  4893. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4894. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4895. \
  4896. v_texCoord = a_texCoord; \
  4897. } ';
  4898. var smaskFragmentShaderCode = '\
  4899. precision mediump float; \
  4900. \
  4901. uniform vec4 u_backdrop; \
  4902. uniform int u_subtype; \
  4903. uniform sampler2D u_image; \
  4904. uniform sampler2D u_mask; \
  4905. \
  4906. varying vec2 v_texCoord; \
  4907. \
  4908. void main() { \
  4909. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4910. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4911. if (u_backdrop.a > 0.0) { \
  4912. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4913. u_backdrop.rgb * (1.0 - maskColor.a); \
  4914. } \
  4915. float lum; \
  4916. if (u_subtype == 0) { \
  4917. lum = maskColor.a; \
  4918. } else { \
  4919. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4920. maskColor.b * 0.11; \
  4921. } \
  4922. imageColor.a *= lum; \
  4923. imageColor.rgb *= imageColor.a; \
  4924. gl_FragColor = imageColor; \
  4925. } ';
  4926. var smaskCache = null;
  4927. function initSmaskGL() {
  4928. var canvas, gl;
  4929. generateGL();
  4930. canvas = currentCanvas;
  4931. currentCanvas = null;
  4932. gl = currentGL;
  4933. currentGL = null;
  4934. // setup a GLSL program
  4935. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  4936. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  4937. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4938. gl.useProgram(program);
  4939. var cache = {};
  4940. cache.gl = gl;
  4941. cache.canvas = canvas;
  4942. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4943. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4944. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  4945. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  4946. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  4947. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  4948. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  4949. // provide texture coordinates for the rectangle.
  4950. var texCoordBuffer = gl.createBuffer();
  4951. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  4952. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4953. 0.0, 0.0,
  4954. 1.0, 0.0,
  4955. 0.0, 1.0,
  4956. 0.0, 1.0,
  4957. 1.0, 0.0,
  4958. 1.0, 1.0]), gl.STATIC_DRAW);
  4959. gl.enableVertexAttribArray(texCoordLocation);
  4960. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  4961. gl.uniform1i(texLayerLocation, 0);
  4962. gl.uniform1i(texMaskLocation, 1);
  4963. smaskCache = cache;
  4964. }
  4965. function composeSMask(layer, mask, properties) {
  4966. var width = layer.width, height = layer.height;
  4967. if (!smaskCache) {
  4968. initSmaskGL();
  4969. }
  4970. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  4971. canvas.width = width;
  4972. canvas.height = height;
  4973. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4974. gl.uniform2f(cache.resolutionLocation, width, height);
  4975. if (properties.backdrop) {
  4976. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  4977. properties.backdrop[1], properties.backdrop[2], 1);
  4978. } else {
  4979. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  4980. }
  4981. gl.uniform1i(cache.subtypeLocation,
  4982. properties.subtype === 'Luminosity' ? 1 : 0);
  4983. // Create a textures
  4984. var texture = createTexture(gl, layer, gl.TEXTURE0);
  4985. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  4986. // Create a buffer and put a single clipspace rectangle in
  4987. // it (2 triangles)
  4988. var buffer = gl.createBuffer();
  4989. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  4990. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4991. 0, 0,
  4992. width, 0,
  4993. 0, height,
  4994. 0, height,
  4995. width, 0,
  4996. width, height]), gl.STATIC_DRAW);
  4997. gl.enableVertexAttribArray(cache.positionLocation);
  4998. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4999. // draw
  5000. gl.clearColor(0, 0, 0, 0);
  5001. gl.enable(gl.BLEND);
  5002. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5003. gl.clear(gl.COLOR_BUFFER_BIT);
  5004. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5005. gl.flush();
  5006. gl.deleteTexture(texture);
  5007. gl.deleteTexture(maskTexture);
  5008. gl.deleteBuffer(buffer);
  5009. return canvas;
  5010. }
  5011. var figuresVertexShaderCode = '\
  5012. attribute vec2 a_position; \
  5013. attribute vec3 a_color; \
  5014. \
  5015. uniform vec2 u_resolution; \
  5016. uniform vec2 u_scale; \
  5017. uniform vec2 u_offset; \
  5018. \
  5019. varying vec4 v_color; \
  5020. \
  5021. void main() { \
  5022. vec2 position = (a_position + u_offset) * u_scale; \
  5023. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5024. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5025. \
  5026. v_color = vec4(a_color / 255.0, 1.0); \
  5027. } ';
  5028. var figuresFragmentShaderCode = '\
  5029. precision mediump float; \
  5030. \
  5031. varying vec4 v_color; \
  5032. \
  5033. void main() { \
  5034. gl_FragColor = v_color; \
  5035. } ';
  5036. var figuresCache = null;
  5037. function initFiguresGL() {
  5038. var canvas, gl;
  5039. generateGL();
  5040. canvas = currentCanvas;
  5041. currentCanvas = null;
  5042. gl = currentGL;
  5043. currentGL = null;
  5044. // setup a GLSL program
  5045. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5046. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5047. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5048. gl.useProgram(program);
  5049. var cache = {};
  5050. cache.gl = gl;
  5051. cache.canvas = canvas;
  5052. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5053. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5054. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5055. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5056. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5057. figuresCache = cache;
  5058. }
  5059. function drawFigures(width, height, backgroundColor, figures, context) {
  5060. if (!figuresCache) {
  5061. initFiguresGL();
  5062. }
  5063. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5064. canvas.width = width;
  5065. canvas.height = height;
  5066. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5067. gl.uniform2f(cache.resolutionLocation, width, height);
  5068. // count triangle points
  5069. var count = 0;
  5070. var i, ii, rows;
  5071. for (i = 0, ii = figures.length; i < ii; i++) {
  5072. switch (figures[i].type) {
  5073. case 'lattice':
  5074. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5075. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5076. break;
  5077. case 'triangles':
  5078. count += figures[i].coords.length;
  5079. break;
  5080. }
  5081. }
  5082. // transfer data
  5083. var coords = new Float32Array(count * 2);
  5084. var colors = new Uint8Array(count * 3);
  5085. var coordsMap = context.coords, colorsMap = context.colors;
  5086. var pIndex = 0, cIndex = 0;
  5087. for (i = 0, ii = figures.length; i < ii; i++) {
  5088. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5089. switch (figure.type) {
  5090. case 'lattice':
  5091. var cols = figure.verticesPerRow;
  5092. rows = (ps.length / cols) | 0;
  5093. for (var row = 1; row < rows; row++) {
  5094. var offset = row * cols + 1;
  5095. for (var col = 1; col < cols; col++, offset++) {
  5096. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5097. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5098. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5099. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5100. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5101. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5102. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5103. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5104. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5105. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5106. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5107. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5108. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5109. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5110. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5111. coords[pIndex + 6] = coords[pIndex + 2];
  5112. coords[pIndex + 7] = coords[pIndex + 3];
  5113. coords[pIndex + 8] = coords[pIndex + 4];
  5114. coords[pIndex + 9] = coords[pIndex + 5];
  5115. coords[pIndex + 10] = coordsMap[ps[offset]];
  5116. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5117. colors[cIndex + 9] = colors[cIndex + 3];
  5118. colors[cIndex + 10] = colors[cIndex + 4];
  5119. colors[cIndex + 11] = colors[cIndex + 5];
  5120. colors[cIndex + 12] = colors[cIndex + 6];
  5121. colors[cIndex + 13] = colors[cIndex + 7];
  5122. colors[cIndex + 14] = colors[cIndex + 8];
  5123. colors[cIndex + 15] = colorsMap[cs[offset]];
  5124. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5125. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5126. pIndex += 12;
  5127. cIndex += 18;
  5128. }
  5129. }
  5130. break;
  5131. case 'triangles':
  5132. for (var j = 0, jj = ps.length; j < jj; j++) {
  5133. coords[pIndex] = coordsMap[ps[j]];
  5134. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5135. colors[cIndex] = colorsMap[cs[i]];
  5136. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5137. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5138. pIndex += 2;
  5139. cIndex += 3;
  5140. }
  5141. break;
  5142. }
  5143. }
  5144. // draw
  5145. if (backgroundColor) {
  5146. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5147. backgroundColor[2] / 255, 1.0);
  5148. } else {
  5149. gl.clearColor(0, 0, 0, 0);
  5150. }
  5151. gl.clear(gl.COLOR_BUFFER_BIT);
  5152. var coordsBuffer = gl.createBuffer();
  5153. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5154. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5155. gl.enableVertexAttribArray(cache.positionLocation);
  5156. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5157. var colorsBuffer = gl.createBuffer();
  5158. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5159. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5160. gl.enableVertexAttribArray(cache.colorLocation);
  5161. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5162. 0, 0);
  5163. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5164. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5165. gl.drawArrays(gl.TRIANGLES, 0, count);
  5166. gl.flush();
  5167. gl.deleteBuffer(coordsBuffer);
  5168. gl.deleteBuffer(colorsBuffer);
  5169. return canvas;
  5170. }
  5171. function cleanup() {
  5172. if (smaskCache && smaskCache.canvas) {
  5173. smaskCache.canvas.width = 0;
  5174. smaskCache.canvas.height = 0;
  5175. }
  5176. if (figuresCache && figuresCache.canvas) {
  5177. figuresCache.canvas.width = 0;
  5178. figuresCache.canvas.height = 0;
  5179. }
  5180. smaskCache = null;
  5181. figuresCache = null;
  5182. }
  5183. return {
  5184. get isEnabled() {
  5185. if (PDFJS.disableWebGL) {
  5186. return false;
  5187. }
  5188. var enabled = false;
  5189. try {
  5190. generateGL();
  5191. enabled = !!currentGL;
  5192. } catch (e) { }
  5193. return shadow(this, 'isEnabled', enabled);
  5194. },
  5195. composeSMask: composeSMask,
  5196. drawFigures: drawFigures,
  5197. clear: cleanup
  5198. };
  5199. })();
  5200. var ShadingIRs = {};
  5201. ShadingIRs.RadialAxial = {
  5202. fromIR: function RadialAxial_fromIR(raw) {
  5203. var type = raw[1];
  5204. var colorStops = raw[2];
  5205. var p0 = raw[3];
  5206. var p1 = raw[4];
  5207. var r0 = raw[5];
  5208. var r1 = raw[6];
  5209. return {
  5210. type: 'Pattern',
  5211. getPattern: function RadialAxial_getPattern(ctx) {
  5212. var grad;
  5213. if (type === 'axial') {
  5214. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5215. } else if (type === 'radial') {
  5216. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5217. }
  5218. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5219. var c = colorStops[i];
  5220. grad.addColorStop(c[0], c[1]);
  5221. }
  5222. return grad;
  5223. }
  5224. };
  5225. }
  5226. };
  5227. var createMeshCanvas = (function createMeshCanvasClosure() {
  5228. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5229. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5230. var coords = context.coords, colors = context.colors;
  5231. var bytes = data.data, rowSize = data.width * 4;
  5232. var tmp;
  5233. if (coords[p1 + 1] > coords[p2 + 1]) {
  5234. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5235. }
  5236. if (coords[p2 + 1] > coords[p3 + 1]) {
  5237. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5238. }
  5239. if (coords[p1 + 1] > coords[p2 + 1]) {
  5240. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5241. }
  5242. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5243. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5244. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5245. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5246. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5247. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5248. if (y1 >= y3) {
  5249. return;
  5250. }
  5251. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5252. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5253. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5254. var minY = Math.round(y1), maxY = Math.round(y3);
  5255. var xa, car, cag, cab;
  5256. var xb, cbr, cbg, cbb;
  5257. var k;
  5258. for (var y = minY; y <= maxY; y++) {
  5259. if (y < y2) {
  5260. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5261. xa = x1 - (x1 - x2) * k;
  5262. car = c1r - (c1r - c2r) * k;
  5263. cag = c1g - (c1g - c2g) * k;
  5264. cab = c1b - (c1b - c2b) * k;
  5265. } else {
  5266. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5267. xa = x2 - (x2 - x3) * k;
  5268. car = c2r - (c2r - c3r) * k;
  5269. cag = c2g - (c2g - c3g) * k;
  5270. cab = c2b - (c2b - c3b) * k;
  5271. }
  5272. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5273. xb = x1 - (x1 - x3) * k;
  5274. cbr = c1r - (c1r - c3r) * k;
  5275. cbg = c1g - (c1g - c3g) * k;
  5276. cbb = c1b - (c1b - c3b) * k;
  5277. var x1_ = Math.round(Math.min(xa, xb));
  5278. var x2_ = Math.round(Math.max(xa, xb));
  5279. var j = rowSize * y + x1_ * 4;
  5280. for (var x = x1_; x <= x2_; x++) {
  5281. k = (xa - x) / (xa - xb);
  5282. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5283. bytes[j++] = (car - (car - cbr) * k) | 0;
  5284. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5285. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5286. bytes[j++] = 255;
  5287. }
  5288. }
  5289. }
  5290. function drawFigure(data, figure, context) {
  5291. var ps = figure.coords;
  5292. var cs = figure.colors;
  5293. var i, ii;
  5294. switch (figure.type) {
  5295. case 'lattice':
  5296. var verticesPerRow = figure.verticesPerRow;
  5297. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5298. var cols = verticesPerRow - 1;
  5299. for (i = 0; i < rows; i++) {
  5300. var q = i * verticesPerRow;
  5301. for (var j = 0; j < cols; j++, q++) {
  5302. drawTriangle(data, context,
  5303. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5304. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5305. drawTriangle(data, context,
  5306. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5307. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5308. }
  5309. }
  5310. break;
  5311. case 'triangles':
  5312. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5313. drawTriangle(data, context,
  5314. ps[i], ps[i + 1], ps[i + 2],
  5315. cs[i], cs[i + 1], cs[i + 2]);
  5316. }
  5317. break;
  5318. default:
  5319. error('illigal figure');
  5320. break;
  5321. }
  5322. }
  5323. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5324. backgroundColor) {
  5325. // we will increase scale on some weird factor to let antialiasing take
  5326. // care of "rough" edges
  5327. var EXPECTED_SCALE = 1.1;
  5328. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5329. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5330. var offsetX = Math.floor(bounds[0]);
  5331. var offsetY = Math.floor(bounds[1]);
  5332. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5333. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5334. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5335. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5336. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5337. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5338. var scaleX = boundsWidth / width;
  5339. var scaleY = boundsHeight / height;
  5340. var context = {
  5341. coords: coords,
  5342. colors: colors,
  5343. offsetX: -offsetX,
  5344. offsetY: -offsetY,
  5345. scaleX: 1 / scaleX,
  5346. scaleY: 1 / scaleY
  5347. };
  5348. var canvas, tmpCanvas, i, ii;
  5349. if (WebGLUtils.isEnabled) {
  5350. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5351. figures, context);
  5352. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5353. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5354. tmpCanvas.context.drawImage(canvas, 0, 0);
  5355. canvas = tmpCanvas.canvas;
  5356. } else {
  5357. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5358. var tmpCtx = tmpCanvas.context;
  5359. var data = tmpCtx.createImageData(width, height);
  5360. if (backgroundColor) {
  5361. var bytes = data.data;
  5362. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5363. bytes[i] = backgroundColor[0];
  5364. bytes[i + 1] = backgroundColor[1];
  5365. bytes[i + 2] = backgroundColor[2];
  5366. bytes[i + 3] = 255;
  5367. }
  5368. }
  5369. for (i = 0; i < figures.length; i++) {
  5370. drawFigure(data, figures[i], context);
  5371. }
  5372. tmpCtx.putImageData(data, 0, 0);
  5373. canvas = tmpCanvas.canvas;
  5374. }
  5375. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5376. scaleX: scaleX, scaleY: scaleY};
  5377. }
  5378. return createMeshCanvas;
  5379. })();
  5380. ShadingIRs.Mesh = {
  5381. fromIR: function Mesh_fromIR(raw) {
  5382. //var type = raw[1];
  5383. var coords = raw[2];
  5384. var colors = raw[3];
  5385. var figures = raw[4];
  5386. var bounds = raw[5];
  5387. var matrix = raw[6];
  5388. //var bbox = raw[7];
  5389. var background = raw[8];
  5390. return {
  5391. type: 'Pattern',
  5392. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5393. var scale;
  5394. if (shadingFill) {
  5395. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5396. } else {
  5397. // Obtain scale from matrix and current transformation matrix.
  5398. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5399. if (matrix) {
  5400. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5401. scale = [scale[0] * matrixScale[0],
  5402. scale[1] * matrixScale[1]];
  5403. }
  5404. }
  5405. // Rasterizing on the main thread since sending/queue large canvases
  5406. // might cause OOM.
  5407. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5408. colors, figures, shadingFill ? null : background);
  5409. if (!shadingFill) {
  5410. ctx.setTransform.apply(ctx, owner.baseTransform);
  5411. if (matrix) {
  5412. ctx.transform.apply(ctx, matrix);
  5413. }
  5414. }
  5415. ctx.translate(temporaryPatternCanvas.offsetX,
  5416. temporaryPatternCanvas.offsetY);
  5417. ctx.scale(temporaryPatternCanvas.scaleX,
  5418. temporaryPatternCanvas.scaleY);
  5419. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5420. }
  5421. };
  5422. }
  5423. };
  5424. ShadingIRs.Dummy = {
  5425. fromIR: function Dummy_fromIR() {
  5426. return {
  5427. type: 'Pattern',
  5428. getPattern: function Dummy_fromIR_getPattern() {
  5429. return 'hotpink';
  5430. }
  5431. };
  5432. }
  5433. };
  5434. function getShadingPatternFromIR(raw) {
  5435. var shadingIR = ShadingIRs[raw[0]];
  5436. if (!shadingIR) {
  5437. error('Unknown IR type: ' + raw[0]);
  5438. }
  5439. return shadingIR.fromIR(raw);
  5440. }
  5441. var TilingPattern = (function TilingPatternClosure() {
  5442. var PaintType = {
  5443. COLORED: 1,
  5444. UNCOLORED: 2
  5445. };
  5446. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5447. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5448. this.operatorList = IR[2];
  5449. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5450. this.bbox = IR[4];
  5451. this.xstep = IR[5];
  5452. this.ystep = IR[6];
  5453. this.paintType = IR[7];
  5454. this.tilingType = IR[8];
  5455. this.color = color;
  5456. this.objs = objs;
  5457. this.commonObjs = commonObjs;
  5458. this.baseTransform = baseTransform;
  5459. this.type = 'Pattern';
  5460. this.ctx = ctx;
  5461. }
  5462. TilingPattern.prototype = {
  5463. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5464. var operatorList = this.operatorList;
  5465. var bbox = this.bbox;
  5466. var xstep = this.xstep;
  5467. var ystep = this.ystep;
  5468. var paintType = this.paintType;
  5469. var tilingType = this.tilingType;
  5470. var color = this.color;
  5471. var objs = this.objs;
  5472. var commonObjs = this.commonObjs;
  5473. info('TilingType: ' + tilingType);
  5474. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5475. var topLeft = [x0, y0];
  5476. // we want the canvas to be as large as the step size
  5477. var botRight = [x0 + xstep, y0 + ystep];
  5478. var width = botRight[0] - topLeft[0];
  5479. var height = botRight[1] - topLeft[1];
  5480. // Obtain scale from matrix and current transformation matrix.
  5481. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5482. var curMatrixScale = Util.singularValueDecompose2dScale(
  5483. this.baseTransform);
  5484. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5485. matrixScale[1] * curMatrixScale[1]];
  5486. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5487. // Use width and height values that are as close as possible to the end
  5488. // result when the pattern is used. Too low value makes the pattern look
  5489. // blurry. Too large value makes it look too crispy.
  5490. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5491. MAX_PATTERN_SIZE);
  5492. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5493. MAX_PATTERN_SIZE);
  5494. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  5495. var tmpCtx = tmpCanvas.context;
  5496. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5497. graphics.groupLevel = owner.groupLevel;
  5498. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5499. this.setScale(width, height, xstep, ystep);
  5500. this.transformToScale(graphics);
  5501. // transform coordinates to pattern space
  5502. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5503. graphics.transform.apply(graphics, tmpTranslate);
  5504. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5505. graphics.executeOperatorList(operatorList);
  5506. return tmpCanvas.canvas;
  5507. },
  5508. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5509. this.scale = [width / xstep, height / ystep];
  5510. },
  5511. transformToScale: function TilingPattern_transformToScale(graphics) {
  5512. var scale = this.scale;
  5513. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5514. graphics.transform.apply(graphics, tmpScale);
  5515. },
  5516. scaleToContext: function TilingPattern_scaleToContext() {
  5517. var scale = this.scale;
  5518. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5519. },
  5520. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5521. if (bbox && isArray(bbox) && bbox.length === 4) {
  5522. var bboxWidth = x1 - x0;
  5523. var bboxHeight = y1 - y0;
  5524. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5525. graphics.clip();
  5526. graphics.endPath();
  5527. }
  5528. },
  5529. setFillAndStrokeStyleToContext:
  5530. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5531. switch (paintType) {
  5532. case PaintType.COLORED:
  5533. var ctx = this.ctx;
  5534. context.fillStyle = ctx.fillStyle;
  5535. context.strokeStyle = ctx.strokeStyle;
  5536. break;
  5537. case PaintType.UNCOLORED:
  5538. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5539. context.fillStyle = cssColor;
  5540. context.strokeStyle = cssColor;
  5541. break;
  5542. default:
  5543. error('Unsupported paint type: ' + paintType);
  5544. }
  5545. },
  5546. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5547. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5548. ctx = this.ctx;
  5549. ctx.setTransform.apply(ctx, this.baseTransform);
  5550. ctx.transform.apply(ctx, this.matrix);
  5551. this.scaleToContext();
  5552. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5553. }
  5554. };
  5555. return TilingPattern;
  5556. })();
  5557. PDFJS.disableFontFace = false;
  5558. var FontLoader = {
  5559. insertRule: function fontLoaderInsertRule(rule) {
  5560. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5561. if (!styleElement) {
  5562. styleElement = document.createElement('style');
  5563. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  5564. document.documentElement.getElementsByTagName('head')[0].appendChild(
  5565. styleElement);
  5566. }
  5567. var styleSheet = styleElement.sheet;
  5568. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5569. },
  5570. clear: function fontLoaderClear() {
  5571. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5572. if (styleElement) {
  5573. styleElement.parentNode.removeChild(styleElement);
  5574. }
  5575. this.nativeFontFaces.forEach(function(nativeFontFace) {
  5576. document.fonts.delete(nativeFontFace);
  5577. });
  5578. this.nativeFontFaces.length = 0;
  5579. },
  5580. get loadTestFont() {
  5581. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  5582. // height.
  5583. return shadow(this, 'loadTestFont', atob(
  5584. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  5585. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  5586. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  5587. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  5588. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  5589. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  5590. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  5591. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  5592. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  5593. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  5594. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  5595. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  5596. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  5597. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5598. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5599. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5600. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  5601. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  5602. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  5603. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  5604. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  5605. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  5606. ));
  5607. },
  5608. loadTestFontId: 0,
  5609. loadingContext: {
  5610. requests: [],
  5611. nextRequestId: 0
  5612. },
  5613. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  5614. if (isWorker) {
  5615. return false;
  5616. }
  5617. // User agent string sniffing is bad, but there is no reliable way to tell
  5618. // if font is fully loaded and ready to be used with canvas.
  5619. var userAgent = window.navigator.userAgent;
  5620. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  5621. if (m && m[1] >= 14) {
  5622. return true;
  5623. }
  5624. // TODO other browsers
  5625. if (userAgent === 'node') {
  5626. return true;
  5627. }
  5628. return false;
  5629. })(),
  5630. nativeFontFaces: [],
  5631. isFontLoadingAPISupported: (!isWorker && typeof document !== 'undefined' &&
  5632. !!document.fonts),
  5633. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  5634. this.nativeFontFaces.push(nativeFontFace);
  5635. document.fonts.add(nativeFontFace);
  5636. },
  5637. bind: function fontLoaderBind(fonts, callback) {
  5638. assert(!isWorker, 'bind() shall be called from main thread');
  5639. var rules = [];
  5640. var fontsToLoad = [];
  5641. var fontLoadPromises = [];
  5642. var getNativeFontPromise = function(nativeFontFace) {
  5643. // Return a promise that is always fulfilled, even when the font fails to
  5644. // load.
  5645. return nativeFontFace.loaded.catch(function(e) {
  5646. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  5647. });
  5648. };
  5649. for (var i = 0, ii = fonts.length; i < ii; i++) {
  5650. var font = fonts[i];
  5651. // Add the font to the DOM only once or skip if the font
  5652. // is already loaded.
  5653. if (font.attached || font.loading === false) {
  5654. continue;
  5655. }
  5656. font.attached = true;
  5657. if (this.isFontLoadingAPISupported) {
  5658. var nativeFontFace = font.createNativeFontFace();
  5659. if (nativeFontFace) {
  5660. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  5661. }
  5662. } else {
  5663. var rule = font.bindDOM();
  5664. if (rule) {
  5665. rules.push(rule);
  5666. fontsToLoad.push(font);
  5667. }
  5668. }
  5669. }
  5670. var request = FontLoader.queueLoadingCallback(callback);
  5671. if (this.isFontLoadingAPISupported) {
  5672. Promise.all(fontLoadPromises).then(function() {
  5673. request.complete();
  5674. });
  5675. } else if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  5676. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  5677. } else {
  5678. request.complete();
  5679. }
  5680. },
  5681. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  5682. function LoadLoader_completeRequest() {
  5683. assert(!request.end, 'completeRequest() cannot be called twice');
  5684. request.end = Date.now();
  5685. // sending all completed requests in order how they were queued
  5686. while (context.requests.length > 0 && context.requests[0].end) {
  5687. var otherRequest = context.requests.shift();
  5688. setTimeout(otherRequest.callback, 0);
  5689. }
  5690. }
  5691. var context = FontLoader.loadingContext;
  5692. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  5693. var request = {
  5694. id: requestId,
  5695. complete: LoadLoader_completeRequest,
  5696. callback: callback,
  5697. started: Date.now()
  5698. };
  5699. context.requests.push(request);
  5700. return request;
  5701. },
  5702. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  5703. fonts,
  5704. request) {
  5705. /** Hack begin */
  5706. // There's currently no event when a font has finished downloading so the
  5707. // following code is a dirty hack to 'guess' when a font is
  5708. // ready. It's assumed fonts are loaded in order, so add a known test
  5709. // font after the desired fonts and then test for the loading of that
  5710. // test font.
  5711. function int32(data, offset) {
  5712. return (data.charCodeAt(offset) << 24) |
  5713. (data.charCodeAt(offset + 1) << 16) |
  5714. (data.charCodeAt(offset + 2) << 8) |
  5715. (data.charCodeAt(offset + 3) & 0xff);
  5716. }
  5717. function spliceString(s, offset, remove, insert) {
  5718. var chunk1 = s.substr(0, offset);
  5719. var chunk2 = s.substr(offset + remove);
  5720. return chunk1 + insert + chunk2;
  5721. }
  5722. var i, ii;
  5723. var canvas = document.createElement('canvas');
  5724. canvas.width = 1;
  5725. canvas.height = 1;
  5726. var ctx = canvas.getContext('2d');
  5727. var called = 0;
  5728. function isFontReady(name, callback) {
  5729. called++;
  5730. // With setTimeout clamping this gives the font ~100ms to load.
  5731. if(called > 30) {
  5732. warn('Load test font never loaded.');
  5733. callback();
  5734. return;
  5735. }
  5736. ctx.font = '30px ' + name;
  5737. ctx.fillText('.', 0, 20);
  5738. var imageData = ctx.getImageData(0, 0, 1, 1);
  5739. if (imageData.data[3] > 0) {
  5740. callback();
  5741. return;
  5742. }
  5743. setTimeout(isFontReady.bind(null, name, callback));
  5744. }
  5745. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  5746. // Chromium seems to cache fonts based on a hash of the actual font data,
  5747. // so the font must be modified for each load test else it will appear to
  5748. // be loaded already.
  5749. // TODO: This could maybe be made faster by avoiding the btoa of the full
  5750. // font by splitting it in chunks before hand and padding the font id.
  5751. var data = this.loadTestFont;
  5752. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  5753. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  5754. loadTestFontId);
  5755. // CFF checksum is important for IE, adjusting it
  5756. var CFF_CHECKSUM_OFFSET = 16;
  5757. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  5758. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5759. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5760. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  5761. }
  5762. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  5763. checksum = (checksum - XXXX_VALUE +
  5764. int32(loadTestFontId + 'XXX', i)) | 0;
  5765. }
  5766. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  5767. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  5768. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  5769. url + '}';
  5770. FontLoader.insertRule(rule);
  5771. var names = [];
  5772. for (i = 0, ii = fonts.length; i < ii; i++) {
  5773. names.push(fonts[i].loadedName);
  5774. }
  5775. names.push(loadTestFontId);
  5776. var div = document.createElement('div');
  5777. div.setAttribute('style',
  5778. 'visibility: hidden;' +
  5779. 'width: 10px; height: 10px;' +
  5780. 'position: absolute; top: 0px; left: 0px;');
  5781. for (i = 0, ii = names.length; i < ii; ++i) {
  5782. var span = document.createElement('span');
  5783. span.textContent = 'Hi';
  5784. span.style.fontFamily = names[i];
  5785. div.appendChild(span);
  5786. }
  5787. document.body.appendChild(div);
  5788. isFontReady(loadTestFontId, function() {
  5789. document.body.removeChild(div);
  5790. request.complete();
  5791. });
  5792. /** Hack end */
  5793. }
  5794. };
  5795. var FontFaceObject = (function FontFaceObjectClosure() {
  5796. function FontFaceObject(name, file, properties) {
  5797. this.compiledGlyphs = {};
  5798. if (arguments.length === 1) {
  5799. // importing translated data
  5800. var data = arguments[0];
  5801. for (var i in data) {
  5802. this[i] = data[i];
  5803. }
  5804. return;
  5805. }
  5806. }
  5807. FontFaceObject.prototype = {
  5808. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  5809. if (!this.data) {
  5810. return null;
  5811. }
  5812. if (PDFJS.disableFontFace) {
  5813. this.disableFontFace = true;
  5814. return null;
  5815. }
  5816. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  5817. FontLoader.addNativeFontFace(nativeFontFace);
  5818. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5819. globalScope['FontInspector'].enabled) {
  5820. globalScope['FontInspector'].fontAdded(this);
  5821. }
  5822. return nativeFontFace;
  5823. },
  5824. bindDOM: function FontFaceObject_bindDOM() {
  5825. if (!this.data) {
  5826. return null;
  5827. }
  5828. if (PDFJS.disableFontFace) {
  5829. this.disableFontFace = true;
  5830. return null;
  5831. }
  5832. var data = bytesToString(new Uint8Array(this.data));
  5833. var fontName = this.loadedName;
  5834. // Add the font-face rule to the document
  5835. var url = ('url(data:' + this.mimetype + ';base64,' +
  5836. window.btoa(data) + ');');
  5837. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  5838. FontLoader.insertRule(rule);
  5839. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5840. globalScope['FontInspector'].enabled) {
  5841. globalScope['FontInspector'].fontAdded(this, url);
  5842. }
  5843. return rule;
  5844. },
  5845. getPathGenerator: function FontLoader_getPathGenerator(objs, character) {
  5846. if (!(character in this.compiledGlyphs)) {
  5847. var js = objs.get(this.loadedName + '_path_' + character);
  5848. /*jshint -W054 */
  5849. this.compiledGlyphs[character] = new Function('c', 'size', js);
  5850. }
  5851. return this.compiledGlyphs[character];
  5852. }
  5853. };
  5854. return FontFaceObject;
  5855. })();
  5856. var ANNOT_MIN_SIZE = 10; // px
  5857. var AnnotationUtils = (function AnnotationUtilsClosure() {
  5858. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  5859. function setTextStyles(element, item, fontObj) {
  5860. var style = element.style;
  5861. style.fontSize = item.fontSize + 'px';
  5862. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  5863. if (!fontObj) {
  5864. return;
  5865. }
  5866. style.fontWeight = fontObj.black ?
  5867. (fontObj.bold ? 'bolder' : 'bold') :
  5868. (fontObj.bold ? 'bold' : 'normal');
  5869. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  5870. var fontName = fontObj.loadedName;
  5871. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  5872. // Use a reasonable default font if the font doesn't specify a fallback
  5873. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  5874. style.fontFamily = fontFamily + fallbackName;
  5875. }
  5876. function initContainer(item, drawBorder) {
  5877. var container = document.createElement('section');
  5878. var cstyle = container.style;
  5879. var width = item.rect[2] - item.rect[0];
  5880. var height = item.rect[3] - item.rect[1];
  5881. // Border
  5882. if (item.borderStyle.width > 0) {
  5883. // Border width
  5884. container.style.borderWidth = item.borderStyle.width + 'px';
  5885. if (item.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  5886. // Underline styles only have a bottom border, so we do not need
  5887. // to adjust for all borders. This yields a similar result as
  5888. // Adobe Acrobat/Reader.
  5889. width = width - 2 * item.borderStyle.width;
  5890. height = height - 2 * item.borderStyle.width;
  5891. }
  5892. // Horizontal and vertical border radius
  5893. var horizontalRadius = item.borderStyle.horizontalCornerRadius;
  5894. var verticalRadius = item.borderStyle.verticalCornerRadius;
  5895. if (horizontalRadius > 0 || verticalRadius > 0) {
  5896. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  5897. CustomStyle.setProp('borderRadius', container, radius);
  5898. }
  5899. // Border style
  5900. switch (item.borderStyle.style) {
  5901. case AnnotationBorderStyleType.SOLID:
  5902. container.style.borderStyle = 'solid';
  5903. break;
  5904. case AnnotationBorderStyleType.DASHED:
  5905. container.style.borderStyle = 'dashed';
  5906. break;
  5907. case AnnotationBorderStyleType.BEVELED:
  5908. warn('Unimplemented border style: beveled');
  5909. break;
  5910. case AnnotationBorderStyleType.INSET:
  5911. warn('Unimplemented border style: inset');
  5912. break;
  5913. case AnnotationBorderStyleType.UNDERLINE:
  5914. container.style.borderBottomStyle = 'solid';
  5915. break;
  5916. default:
  5917. break;
  5918. }
  5919. // Border color
  5920. if (item.color) {
  5921. container.style.borderColor =
  5922. Util.makeCssRgb(Math.round(item.color[0] * 255),
  5923. Math.round(item.color[1] * 255),
  5924. Math.round(item.color[2] * 255));
  5925. } else {
  5926. // Default color is black, but that's not obvious from the spec.
  5927. container.style.borderColor = 'rgb(0,0,0)';
  5928. }
  5929. }
  5930. cstyle.width = width + 'px';
  5931. cstyle.height = height + 'px';
  5932. return container;
  5933. }
  5934. function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
  5935. var element = document.createElement('div');
  5936. var width = item.rect[2] - item.rect[0];
  5937. var height = item.rect[3] - item.rect[1];
  5938. element.style.width = width + 'px';
  5939. element.style.height = height + 'px';
  5940. element.style.display = 'table';
  5941. var content = document.createElement('div');
  5942. content.textContent = item.fieldValue;
  5943. var textAlignment = item.textAlignment;
  5944. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  5945. content.style.verticalAlign = 'middle';
  5946. content.style.display = 'table-cell';
  5947. var fontObj = item.fontRefName ?
  5948. commonObjs.getData(item.fontRefName) : null;
  5949. setTextStyles(content, item, fontObj);
  5950. element.appendChild(content);
  5951. return element;
  5952. }
  5953. function getHtmlElementForTextAnnotation(item) {
  5954. var rect = item.rect;
  5955. // sanity check because of OOo-generated PDFs
  5956. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  5957. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  5958. }
  5959. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  5960. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  5961. }
  5962. var container = initContainer(item, false);
  5963. container.className = 'annotText';
  5964. var image = document.createElement('img');
  5965. image.style.height = container.style.height;
  5966. image.style.width = container.style.width;
  5967. var iconName = item.name;
  5968. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  5969. iconName.toLowerCase() + '.svg';
  5970. image.alt = '[{{type}} Annotation]';
  5971. image.dataset.l10nId = 'text_annotation_type';
  5972. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  5973. var contentWrapper = document.createElement('div');
  5974. contentWrapper.className = 'annotTextContentWrapper';
  5975. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  5976. contentWrapper.style.top = '-10px';
  5977. var content = document.createElement('div');
  5978. content.className = 'annotTextContent';
  5979. content.setAttribute('hidden', true);
  5980. var i, ii;
  5981. if (item.hasBgColor) {
  5982. var color = item.color;
  5983. // Enlighten the color (70%)
  5984. var BACKGROUND_ENLIGHT = 0.7;
  5985. var r = BACKGROUND_ENLIGHT * (1.0 - color[0]) + color[0];
  5986. var g = BACKGROUND_ENLIGHT * (1.0 - color[1]) + color[1];
  5987. var b = BACKGROUND_ENLIGHT * (1.0 - color[2]) + color[2];
  5988. content.style.backgroundColor = Util.makeCssRgb((r * 255) | 0,
  5989. (g * 255) | 0,
  5990. (b * 255) | 0);
  5991. }
  5992. var title = document.createElement('h1');
  5993. var text = document.createElement('p');
  5994. title.textContent = item.title;
  5995. if (!item.content && !item.title) {
  5996. content.setAttribute('hidden', true);
  5997. } else {
  5998. var e = document.createElement('span');
  5999. var lines = item.content.split(/(?:\r\n?|\n)/);
  6000. for (i = 0, ii = lines.length; i < ii; ++i) {
  6001. var line = lines[i];
  6002. e.appendChild(document.createTextNode(line));
  6003. if (i < (ii - 1)) {
  6004. e.appendChild(document.createElement('br'));
  6005. }
  6006. }
  6007. text.appendChild(e);
  6008. var pinned = false;
  6009. var showAnnotation = function showAnnotation(pin) {
  6010. if (pin) {
  6011. pinned = true;
  6012. }
  6013. if (content.hasAttribute('hidden')) {
  6014. container.style.zIndex += 1;
  6015. content.removeAttribute('hidden');
  6016. }
  6017. };
  6018. var hideAnnotation = function hideAnnotation(unpin) {
  6019. if (unpin) {
  6020. pinned = false;
  6021. }
  6022. if (!content.hasAttribute('hidden') && !pinned) {
  6023. container.style.zIndex -= 1;
  6024. content.setAttribute('hidden', true);
  6025. }
  6026. };
  6027. var toggleAnnotation = function toggleAnnotation() {
  6028. if (pinned) {
  6029. hideAnnotation(true);
  6030. } else {
  6031. showAnnotation(true);
  6032. }
  6033. };
  6034. image.addEventListener('click', function image_clickHandler() {
  6035. toggleAnnotation();
  6036. }, false);
  6037. image.addEventListener('mouseover', function image_mouseOverHandler() {
  6038. showAnnotation();
  6039. }, false);
  6040. image.addEventListener('mouseout', function image_mouseOutHandler() {
  6041. hideAnnotation();
  6042. }, false);
  6043. content.addEventListener('click', function content_clickHandler() {
  6044. hideAnnotation(true);
  6045. }, false);
  6046. }
  6047. content.appendChild(title);
  6048. content.appendChild(text);
  6049. contentWrapper.appendChild(content);
  6050. container.appendChild(image);
  6051. container.appendChild(contentWrapper);
  6052. return container;
  6053. }
  6054. function getHtmlElementForLinkAnnotation(item) {
  6055. var container = initContainer(item, true);
  6056. container.className = 'annotLink';
  6057. var link = document.createElement('a');
  6058. link.href = link.title = item.url || '';
  6059. if (item.url && PDFJS.openExternalLinksInNewWindow) {
  6060. link.target = '_blank';
  6061. }
  6062. container.appendChild(link);
  6063. return container;
  6064. }
  6065. function getHtmlElement(data, objs) {
  6066. switch (data.annotationType) {
  6067. case AnnotationType.WIDGET:
  6068. return getHtmlElementForTextWidgetAnnotation(data, objs);
  6069. case AnnotationType.TEXT:
  6070. return getHtmlElementForTextAnnotation(data);
  6071. case AnnotationType.LINK:
  6072. return getHtmlElementForLinkAnnotation(data);
  6073. default:
  6074. throw new Error('Unsupported annotationType: ' + data.annotationType);
  6075. }
  6076. }
  6077. return {
  6078. getHtmlElement: getHtmlElement
  6079. };
  6080. })();
  6081. PDFJS.AnnotationUtils = AnnotationUtils;
  6082. var SVG_DEFAULTS = {
  6083. fontStyle: 'normal',
  6084. fontWeight: 'normal',
  6085. fillColor: '#000000'
  6086. };
  6087. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  6088. var PNG_HEADER =
  6089. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  6090. var CHUNK_WRAPPER_SIZE = 12;
  6091. var crcTable = new Int32Array(256);
  6092. for (var i = 0; i < 256; i++) {
  6093. var c = i;
  6094. for (var h = 0; h < 8; h++) {
  6095. if (c & 1) {
  6096. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  6097. } else {
  6098. c = (c >> 1) & 0x7fffffff;
  6099. }
  6100. }
  6101. crcTable[i] = c;
  6102. }
  6103. function crc32(data, start, end) {
  6104. var crc = -1;
  6105. for (var i = start; i < end; i++) {
  6106. var a = (crc ^ data[i]) & 0xff;
  6107. var b = crcTable[a];
  6108. crc = (crc >>> 8) ^ b;
  6109. }
  6110. return crc ^ -1;
  6111. }
  6112. function writePngChunk(type, body, data, offset) {
  6113. var p = offset;
  6114. var len = body.length;
  6115. data[p] = len >> 24 & 0xff;
  6116. data[p + 1] = len >> 16 & 0xff;
  6117. data[p + 2] = len >> 8 & 0xff;
  6118. data[p + 3] = len & 0xff;
  6119. p += 4;
  6120. data[p] = type.charCodeAt(0) & 0xff;
  6121. data[p + 1] = type.charCodeAt(1) & 0xff;
  6122. data[p + 2] = type.charCodeAt(2) & 0xff;
  6123. data[p + 3] = type.charCodeAt(3) & 0xff;
  6124. p += 4;
  6125. data.set(body, p);
  6126. p += body.length;
  6127. var crc = crc32(data, offset + 4, p);
  6128. data[p] = crc >> 24 & 0xff;
  6129. data[p + 1] = crc >> 16 & 0xff;
  6130. data[p + 2] = crc >> 8 & 0xff;
  6131. data[p + 3] = crc & 0xff;
  6132. }
  6133. function adler32(data, start, end) {
  6134. var a = 1;
  6135. var b = 0;
  6136. for (var i = start; i < end; ++i) {
  6137. a = (a + (data[i] & 0xff)) % 65521;
  6138. b = (b + a) % 65521;
  6139. }
  6140. return (b << 16) | a;
  6141. }
  6142. function encode(imgData, kind) {
  6143. var width = imgData.width;
  6144. var height = imgData.height;
  6145. var bitDepth, colorType, lineSize;
  6146. var bytes = imgData.data;
  6147. switch (kind) {
  6148. case ImageKind.GRAYSCALE_1BPP:
  6149. colorType = 0;
  6150. bitDepth = 1;
  6151. lineSize = (width + 7) >> 3;
  6152. break;
  6153. case ImageKind.RGB_24BPP:
  6154. colorType = 2;
  6155. bitDepth = 8;
  6156. lineSize = width * 3;
  6157. break;
  6158. case ImageKind.RGBA_32BPP:
  6159. colorType = 6;
  6160. bitDepth = 8;
  6161. lineSize = width * 4;
  6162. break;
  6163. default:
  6164. throw new Error('invalid format');
  6165. }
  6166. // prefix every row with predictor 0
  6167. var literals = new Uint8Array((1 + lineSize) * height);
  6168. var offsetLiterals = 0, offsetBytes = 0;
  6169. var y, i;
  6170. for (y = 0; y < height; ++y) {
  6171. literals[offsetLiterals++] = 0; // no prediction
  6172. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  6173. offsetLiterals);
  6174. offsetBytes += lineSize;
  6175. offsetLiterals += lineSize;
  6176. }
  6177. if (kind === ImageKind.GRAYSCALE_1BPP) {
  6178. // inverting for B/W
  6179. offsetLiterals = 0;
  6180. for (y = 0; y < height; y++) {
  6181. offsetLiterals++; // skipping predictor
  6182. for (i = 0; i < lineSize; i++) {
  6183. literals[offsetLiterals++] ^= 0xFF;
  6184. }
  6185. }
  6186. }
  6187. var ihdr = new Uint8Array([
  6188. width >> 24 & 0xff,
  6189. width >> 16 & 0xff,
  6190. width >> 8 & 0xff,
  6191. width & 0xff,
  6192. height >> 24 & 0xff,
  6193. height >> 16 & 0xff,
  6194. height >> 8 & 0xff,
  6195. height & 0xff,
  6196. bitDepth, // bit depth
  6197. colorType, // color type
  6198. 0x00, // compression method
  6199. 0x00, // filter method
  6200. 0x00 // interlace method
  6201. ]);
  6202. var len = literals.length;
  6203. var maxBlockLength = 0xFFFF;
  6204. var deflateBlocks = Math.ceil(len / maxBlockLength);
  6205. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  6206. var pi = 0;
  6207. idat[pi++] = 0x78; // compression method and flags
  6208. idat[pi++] = 0x9c; // flags
  6209. var pos = 0;
  6210. while (len > maxBlockLength) {
  6211. // writing non-final DEFLATE blocks type 0 and length of 65535
  6212. idat[pi++] = 0x00;
  6213. idat[pi++] = 0xff;
  6214. idat[pi++] = 0xff;
  6215. idat[pi++] = 0x00;
  6216. idat[pi++] = 0x00;
  6217. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  6218. pi += maxBlockLength;
  6219. pos += maxBlockLength;
  6220. len -= maxBlockLength;
  6221. }
  6222. // writing non-final DEFLATE blocks type 0
  6223. idat[pi++] = 0x01;
  6224. idat[pi++] = len & 0xff;
  6225. idat[pi++] = len >> 8 & 0xff;
  6226. idat[pi++] = (~len & 0xffff) & 0xff;
  6227. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  6228. idat.set(literals.subarray(pos), pi);
  6229. pi += literals.length - pos;
  6230. var adler = adler32(literals, 0, literals.length); // checksum
  6231. idat[pi++] = adler >> 24 & 0xff;
  6232. idat[pi++] = adler >> 16 & 0xff;
  6233. idat[pi++] = adler >> 8 & 0xff;
  6234. idat[pi++] = adler & 0xff;
  6235. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  6236. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  6237. ihdr.length + idat.length;
  6238. var data = new Uint8Array(pngLength);
  6239. var offset = 0;
  6240. data.set(PNG_HEADER, offset);
  6241. offset += PNG_HEADER.length;
  6242. writePngChunk('IHDR', ihdr, data, offset);
  6243. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  6244. writePngChunk('IDATA', idat, data, offset);
  6245. offset += CHUNK_WRAPPER_SIZE + idat.length;
  6246. writePngChunk('IEND', new Uint8Array(0), data, offset);
  6247. return PDFJS.createObjectURL(data, 'image/png');
  6248. }
  6249. return function convertImgDataToPng(imgData) {
  6250. var kind = (imgData.kind === undefined ?
  6251. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  6252. return encode(imgData, kind);
  6253. };
  6254. })();
  6255. var SVGExtraState = (function SVGExtraStateClosure() {
  6256. function SVGExtraState() {
  6257. this.fontSizeScale = 1;
  6258. this.fontWeight = SVG_DEFAULTS.fontWeight;
  6259. this.fontSize = 0;
  6260. this.textMatrix = IDENTITY_MATRIX;
  6261. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6262. this.leading = 0;
  6263. // Current point (in user coordinates)
  6264. this.x = 0;
  6265. this.y = 0;
  6266. // Start of text line (in text coordinates)
  6267. this.lineX = 0;
  6268. this.lineY = 0;
  6269. // Character and word spacing
  6270. this.charSpacing = 0;
  6271. this.wordSpacing = 0;
  6272. this.textHScale = 1;
  6273. this.textRise = 0;
  6274. // Default foreground and background colors
  6275. this.fillColor = SVG_DEFAULTS.fillColor;
  6276. this.strokeColor = '#000000';
  6277. this.fillAlpha = 1;
  6278. this.strokeAlpha = 1;
  6279. this.lineWidth = 1;
  6280. this.lineJoin = '';
  6281. this.lineCap = '';
  6282. this.miterLimit = 0;
  6283. this.dashArray = [];
  6284. this.dashPhase = 0;
  6285. this.dependencies = [];
  6286. // Clipping
  6287. this.clipId = '';
  6288. this.pendingClip = false;
  6289. this.maskId = '';
  6290. }
  6291. SVGExtraState.prototype = {
  6292. clone: function SVGExtraState_clone() {
  6293. return Object.create(this);
  6294. },
  6295. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  6296. this.x = x;
  6297. this.y = y;
  6298. }
  6299. };
  6300. return SVGExtraState;
  6301. })();
  6302. var SVGGraphics = (function SVGGraphicsClosure() {
  6303. function createScratchSVG(width, height) {
  6304. var NS = 'http://www.w3.org/2000/svg';
  6305. var svg = document.createElementNS(NS, 'svg:svg');
  6306. svg.setAttributeNS(null, 'version', '1.1');
  6307. svg.setAttributeNS(null, 'width', width + 'px');
  6308. svg.setAttributeNS(null, 'height', height + 'px');
  6309. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  6310. return svg;
  6311. }
  6312. function opListToTree(opList) {
  6313. var opTree = [];
  6314. var tmp = [];
  6315. var opListLen = opList.length;
  6316. for (var x = 0; x < opListLen; x++) {
  6317. if (opList[x].fn === 'save') {
  6318. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  6319. tmp.push(opTree);
  6320. opTree = opTree[opTree.length - 1].items;
  6321. continue;
  6322. }
  6323. if(opList[x].fn === 'restore') {
  6324. opTree = tmp.pop();
  6325. } else {
  6326. opTree.push(opList[x]);
  6327. }
  6328. }
  6329. return opTree;
  6330. }
  6331. /**
  6332. * Formats float number.
  6333. * @param value {number} number to format.
  6334. * @returns {string}
  6335. */
  6336. function pf(value) {
  6337. if (value === (value | 0)) { // integer number
  6338. return value.toString();
  6339. }
  6340. var s = value.toFixed(10);
  6341. var i = s.length - 1;
  6342. if (s[i] !== '0') {
  6343. return s;
  6344. }
  6345. // removing trailing zeros
  6346. do {
  6347. i--;
  6348. } while (s[i] === '0');
  6349. return s.substr(0, s[i] === '.' ? i : i + 1);
  6350. }
  6351. /**
  6352. * Formats transform matrix. The standard rotation, scale and translate
  6353. * matrices are replaced by their shorter forms, and for identity matrix
  6354. * returns empty string to save the memory.
  6355. * @param m {Array} matrix to format.
  6356. * @returns {string}
  6357. */
  6358. function pm(m) {
  6359. if (m[4] === 0 && m[5] === 0) {
  6360. if (m[1] === 0 && m[2] === 0) {
  6361. if (m[0] === 1 && m[3] === 1) {
  6362. return '';
  6363. }
  6364. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  6365. }
  6366. if (m[0] === m[3] && m[1] === -m[2]) {
  6367. var a = Math.acos(m[0]) * 180 / Math.PI;
  6368. return 'rotate(' + pf(a) + ')';
  6369. }
  6370. } else {
  6371. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  6372. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  6373. }
  6374. }
  6375. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  6376. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  6377. }
  6378. function SVGGraphics(commonObjs, objs) {
  6379. this.current = new SVGExtraState();
  6380. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  6381. this.transformStack = [];
  6382. this.extraStack = [];
  6383. this.commonObjs = commonObjs;
  6384. this.objs = objs;
  6385. this.pendingEOFill = false;
  6386. this.embedFonts = false;
  6387. this.embeddedFonts = {};
  6388. this.cssStyle = null;
  6389. }
  6390. var NS = 'http://www.w3.org/2000/svg';
  6391. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  6392. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  6393. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6394. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6395. var clipCount = 0;
  6396. var maskCount = 0;
  6397. SVGGraphics.prototype = {
  6398. save: function SVGGraphics_save() {
  6399. this.transformStack.push(this.transformMatrix);
  6400. var old = this.current;
  6401. this.extraStack.push(old);
  6402. this.current = old.clone();
  6403. },
  6404. restore: function SVGGraphics_restore() {
  6405. this.transformMatrix = this.transformStack.pop();
  6406. this.current = this.extraStack.pop();
  6407. this.tgrp = document.createElementNS(NS, 'svg:g');
  6408. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6409. this.pgrp.appendChild(this.tgrp);
  6410. },
  6411. group: function SVGGraphics_group(items) {
  6412. this.save();
  6413. this.executeOpTree(items);
  6414. this.restore();
  6415. },
  6416. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  6417. var fnArray = operatorList.fnArray;
  6418. var fnArrayLen = fnArray.length;
  6419. var argsArray = operatorList.argsArray;
  6420. var self = this;
  6421. for (var i = 0; i < fnArrayLen; i++) {
  6422. if (OPS.dependency === fnArray[i]) {
  6423. var deps = argsArray[i];
  6424. for (var n = 0, nn = deps.length; n < nn; n++) {
  6425. var obj = deps[n];
  6426. var common = obj.substring(0, 2) === 'g_';
  6427. var promise;
  6428. if (common) {
  6429. promise = new Promise(function(resolve) {
  6430. self.commonObjs.get(obj, resolve);
  6431. });
  6432. } else {
  6433. promise = new Promise(function(resolve) {
  6434. self.objs.get(obj, resolve);
  6435. });
  6436. }
  6437. this.current.dependencies.push(promise);
  6438. }
  6439. }
  6440. }
  6441. return Promise.all(this.current.dependencies);
  6442. },
  6443. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  6444. var transformMatrix = [a, b, c, d, e, f];
  6445. this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,
  6446. transformMatrix);
  6447. this.tgrp = document.createElementNS(NS, 'svg:g');
  6448. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6449. },
  6450. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  6451. this.svg = createScratchSVG(viewport.width, viewport.height);
  6452. this.viewport = viewport;
  6453. return this.loadDependencies(operatorList).then(function () {
  6454. this.transformMatrix = IDENTITY_MATRIX;
  6455. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  6456. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  6457. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  6458. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6459. this.defs = document.createElementNS(NS, 'svg:defs');
  6460. this.pgrp.appendChild(this.defs);
  6461. this.pgrp.appendChild(this.tgrp);
  6462. this.svg.appendChild(this.pgrp);
  6463. var opTree = this.convertOpList(operatorList);
  6464. this.executeOpTree(opTree);
  6465. return this.svg;
  6466. }.bind(this));
  6467. },
  6468. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  6469. var argsArray = operatorList.argsArray;
  6470. var fnArray = operatorList.fnArray;
  6471. var fnArrayLen = fnArray.length;
  6472. var REVOPS = [];
  6473. var opList = [];
  6474. for (var op in OPS) {
  6475. REVOPS[OPS[op]] = op;
  6476. }
  6477. for (var x = 0; x < fnArrayLen; x++) {
  6478. var fnId = fnArray[x];
  6479. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  6480. }
  6481. return opListToTree(opList);
  6482. },
  6483. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  6484. var opTreeLen = opTree.length;
  6485. for(var x = 0; x < opTreeLen; x++) {
  6486. var fn = opTree[x].fn;
  6487. var fnId = opTree[x].fnId;
  6488. var args = opTree[x].args;
  6489. switch (fnId | 0) {
  6490. case OPS.beginText:
  6491. this.beginText();
  6492. break;
  6493. case OPS.setLeading:
  6494. this.setLeading(args);
  6495. break;
  6496. case OPS.setLeadingMoveText:
  6497. this.setLeadingMoveText(args[0], args[1]);
  6498. break;
  6499. case OPS.setFont:
  6500. this.setFont(args);
  6501. break;
  6502. case OPS.showText:
  6503. this.showText(args[0]);
  6504. break;
  6505. case OPS.showSpacedText:
  6506. this.showText(args[0]);
  6507. break;
  6508. case OPS.endText:
  6509. this.endText();
  6510. break;
  6511. case OPS.moveText:
  6512. this.moveText(args[0], args[1]);
  6513. break;
  6514. case OPS.setCharSpacing:
  6515. this.setCharSpacing(args[0]);
  6516. break;
  6517. case OPS.setWordSpacing:
  6518. this.setWordSpacing(args[0]);
  6519. break;
  6520. case OPS.setHScale:
  6521. this.setHScale(args[0]);
  6522. break;
  6523. case OPS.setTextMatrix:
  6524. this.setTextMatrix(args[0], args[1], args[2],
  6525. args[3], args[4], args[5]);
  6526. break;
  6527. case OPS.setLineWidth:
  6528. this.setLineWidth(args[0]);
  6529. break;
  6530. case OPS.setLineJoin:
  6531. this.setLineJoin(args[0]);
  6532. break;
  6533. case OPS.setLineCap:
  6534. this.setLineCap(args[0]);
  6535. break;
  6536. case OPS.setMiterLimit:
  6537. this.setMiterLimit(args[0]);
  6538. break;
  6539. case OPS.setFillRGBColor:
  6540. this.setFillRGBColor(args[0], args[1], args[2]);
  6541. break;
  6542. case OPS.setStrokeRGBColor:
  6543. this.setStrokeRGBColor(args[0], args[1], args[2]);
  6544. break;
  6545. case OPS.setDash:
  6546. this.setDash(args[0], args[1]);
  6547. break;
  6548. case OPS.setGState:
  6549. this.setGState(args[0]);
  6550. break;
  6551. case OPS.fill:
  6552. this.fill();
  6553. break;
  6554. case OPS.eoFill:
  6555. this.eoFill();
  6556. break;
  6557. case OPS.stroke:
  6558. this.stroke();
  6559. break;
  6560. case OPS.fillStroke:
  6561. this.fillStroke();
  6562. break;
  6563. case OPS.eoFillStroke:
  6564. this.eoFillStroke();
  6565. break;
  6566. case OPS.clip:
  6567. this.clip('nonzero');
  6568. break;
  6569. case OPS.eoClip:
  6570. this.clip('evenodd');
  6571. break;
  6572. case OPS.paintSolidColorImageMask:
  6573. this.paintSolidColorImageMask();
  6574. break;
  6575. case OPS.paintJpegXObject:
  6576. this.paintJpegXObject(args[0], args[1], args[2]);
  6577. break;
  6578. case OPS.paintImageXObject:
  6579. this.paintImageXObject(args[0]);
  6580. break;
  6581. case OPS.paintInlineImageXObject:
  6582. this.paintInlineImageXObject(args[0]);
  6583. break;
  6584. case OPS.paintImageMaskXObject:
  6585. this.paintImageMaskXObject(args[0]);
  6586. break;
  6587. case OPS.paintFormXObjectBegin:
  6588. this.paintFormXObjectBegin(args[0], args[1]);
  6589. break;
  6590. case OPS.paintFormXObjectEnd:
  6591. this.paintFormXObjectEnd();
  6592. break;
  6593. case OPS.closePath:
  6594. this.closePath();
  6595. break;
  6596. case OPS.closeStroke:
  6597. this.closeStroke();
  6598. break;
  6599. case OPS.closeFillStroke:
  6600. this.closeFillStroke();
  6601. break;
  6602. case OPS.nextLine:
  6603. this.nextLine();
  6604. break;
  6605. case OPS.transform:
  6606. this.transform(args[0], args[1], args[2], args[3],
  6607. args[4], args[5]);
  6608. break;
  6609. case OPS.constructPath:
  6610. this.constructPath(args[0], args[1]);
  6611. break;
  6612. case OPS.endPath:
  6613. this.endPath();
  6614. break;
  6615. case 92:
  6616. this.group(opTree[x].items);
  6617. break;
  6618. default:
  6619. warn('Unimplemented method '+ fn);
  6620. break;
  6621. }
  6622. }
  6623. },
  6624. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  6625. this.current.wordSpacing = wordSpacing;
  6626. },
  6627. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  6628. this.current.charSpacing = charSpacing;
  6629. },
  6630. nextLine: function SVGGraphics_nextLine() {
  6631. this.moveText(0, this.current.leading);
  6632. },
  6633. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  6634. var current = this.current;
  6635. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  6636. this.current.x = this.current.lineX = 0;
  6637. this.current.y = this.current.lineY = 0;
  6638. current.xcoords = [];
  6639. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6640. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6641. current.tspan.setAttributeNS(null, 'font-size',
  6642. pf(current.fontSize) + 'px');
  6643. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6644. current.txtElement = document.createElementNS(NS, 'svg:text');
  6645. current.txtElement.appendChild(current.tspan);
  6646. },
  6647. beginText: function SVGGraphics_beginText() {
  6648. this.current.x = this.current.lineX = 0;
  6649. this.current.y = this.current.lineY = 0;
  6650. this.current.textMatrix = IDENTITY_MATRIX;
  6651. this.current.lineMatrix = IDENTITY_MATRIX;
  6652. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  6653. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  6654. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  6655. this.current.xcoords = [];
  6656. },
  6657. moveText: function SVGGraphics_moveText(x, y) {
  6658. var current = this.current;
  6659. this.current.x = this.current.lineX += x;
  6660. this.current.y = this.current.lineY += y;
  6661. current.xcoords = [];
  6662. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6663. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6664. current.tspan.setAttributeNS(null, 'font-size',
  6665. pf(current.fontSize) + 'px');
  6666. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6667. },
  6668. showText: function SVGGraphics_showText(glyphs) {
  6669. var current = this.current;
  6670. var font = current.font;
  6671. var fontSize = current.fontSize;
  6672. if (fontSize === 0) {
  6673. return;
  6674. }
  6675. var charSpacing = current.charSpacing;
  6676. var wordSpacing = current.wordSpacing;
  6677. var fontDirection = current.fontDirection;
  6678. var textHScale = current.textHScale * fontDirection;
  6679. var glyphsLength = glyphs.length;
  6680. var vertical = font.vertical;
  6681. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  6682. var x = 0, i;
  6683. for (i = 0; i < glyphsLength; ++i) {
  6684. var glyph = glyphs[i];
  6685. if (glyph === null) {
  6686. // word break
  6687. x += fontDirection * wordSpacing;
  6688. continue;
  6689. } else if (isNum(glyph)) {
  6690. x += -glyph * fontSize * 0.001;
  6691. continue;
  6692. }
  6693. current.xcoords.push(current.x + x * textHScale);
  6694. var width = glyph.width;
  6695. var character = glyph.fontChar;
  6696. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  6697. x += charWidth;
  6698. current.tspan.textContent += character;
  6699. }
  6700. if (vertical) {
  6701. current.y -= x * textHScale;
  6702. } else {
  6703. current.x += x * textHScale;
  6704. }
  6705. current.tspan.setAttributeNS(null, 'x',
  6706. current.xcoords.map(pf).join(' '));
  6707. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6708. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6709. current.tspan.setAttributeNS(null, 'font-size',
  6710. pf(current.fontSize) + 'px');
  6711. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  6712. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  6713. }
  6714. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  6715. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  6716. }
  6717. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  6718. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  6719. }
  6720. current.txtElement.setAttributeNS(null, 'transform',
  6721. pm(current.textMatrix) +
  6722. ' scale(1, -1)' );
  6723. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  6724. current.txtElement.appendChild(current.tspan);
  6725. current.txtgrp.appendChild(current.txtElement);
  6726. this.tgrp.appendChild(current.txtElement);
  6727. },
  6728. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  6729. this.setLeading(-y);
  6730. this.moveText(x, y);
  6731. },
  6732. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  6733. if (!this.cssStyle) {
  6734. this.cssStyle = document.createElementNS(NS, 'svg:style');
  6735. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  6736. this.defs.appendChild(this.cssStyle);
  6737. }
  6738. var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);
  6739. this.cssStyle.textContent +=
  6740. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  6741. ' src: url(' + url + '); }\n';
  6742. },
  6743. setFont: function SVGGraphics_setFont(details) {
  6744. var current = this.current;
  6745. var fontObj = this.commonObjs.get(details[0]);
  6746. var size = details[1];
  6747. this.current.font = fontObj;
  6748. if (this.embedFonts && fontObj.data &&
  6749. !this.embeddedFonts[fontObj.loadedName]) {
  6750. this.addFontStyle(fontObj);
  6751. this.embeddedFonts[fontObj.loadedName] = fontObj;
  6752. }
  6753. current.fontMatrix = (fontObj.fontMatrix ?
  6754. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  6755. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  6756. (fontObj.bold ? 'bold' : 'normal');
  6757. var italic = fontObj.italic ? 'italic' : 'normal';
  6758. if (size < 0) {
  6759. size = -size;
  6760. current.fontDirection = -1;
  6761. } else {
  6762. current.fontDirection = 1;
  6763. }
  6764. current.fontSize = size;
  6765. current.fontFamily = fontObj.loadedName;
  6766. current.fontWeight = bold;
  6767. current.fontStyle = italic;
  6768. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6769. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6770. current.xcoords = [];
  6771. },
  6772. endText: function SVGGraphics_endText() {
  6773. if (this.current.pendingClip) {
  6774. this.cgrp.appendChild(this.tgrp);
  6775. this.pgrp.appendChild(this.cgrp);
  6776. } else {
  6777. this.pgrp.appendChild(this.tgrp);
  6778. }
  6779. this.tgrp = document.createElementNS(NS, 'svg:g');
  6780. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6781. },
  6782. // Path properties
  6783. setLineWidth: function SVGGraphics_setLineWidth(width) {
  6784. this.current.lineWidth = width;
  6785. },
  6786. setLineCap: function SVGGraphics_setLineCap(style) {
  6787. this.current.lineCap = LINE_CAP_STYLES[style];
  6788. },
  6789. setLineJoin: function SVGGraphics_setLineJoin(style) {
  6790. this.current.lineJoin = LINE_JOIN_STYLES[style];
  6791. },
  6792. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  6793. this.current.miterLimit = limit;
  6794. },
  6795. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  6796. var color = Util.makeCssRgb(r, g, b);
  6797. this.current.strokeColor = color;
  6798. },
  6799. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  6800. var color = Util.makeCssRgb(r, g, b);
  6801. this.current.fillColor = color;
  6802. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  6803. this.current.xcoords = [];
  6804. },
  6805. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  6806. this.current.dashArray = dashArray;
  6807. this.current.dashPhase = dashPhase;
  6808. },
  6809. constructPath: function SVGGraphics_constructPath(ops, args) {
  6810. var current = this.current;
  6811. var x = current.x, y = current.y;
  6812. current.path = document.createElementNS(NS, 'svg:path');
  6813. var d = [];
  6814. var opLength = ops.length;
  6815. for (var i = 0, j = 0; i < opLength; i++) {
  6816. switch (ops[i] | 0) {
  6817. case OPS.rectangle:
  6818. x = args[j++];
  6819. y = args[j++];
  6820. var width = args[j++];
  6821. var height = args[j++];
  6822. var xw = x + width;
  6823. var yh = y + height;
  6824. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  6825. 'L', pf(x), pf(yh), 'Z');
  6826. break;
  6827. case OPS.moveTo:
  6828. x = args[j++];
  6829. y = args[j++];
  6830. d.push('M', pf(x), pf(y));
  6831. break;
  6832. case OPS.lineTo:
  6833. x = args[j++];
  6834. y = args[j++];
  6835. d.push('L', pf(x) , pf(y));
  6836. break;
  6837. case OPS.curveTo:
  6838. x = args[j + 4];
  6839. y = args[j + 5];
  6840. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  6841. pf(args[j + 3]), pf(x), pf(y));
  6842. j += 6;
  6843. break;
  6844. case OPS.curveTo2:
  6845. x = args[j + 2];
  6846. y = args[j + 3];
  6847. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  6848. pf(args[j + 2]), pf(args[j + 3]));
  6849. j += 4;
  6850. break;
  6851. case OPS.curveTo3:
  6852. x = args[j + 2];
  6853. y = args[j + 3];
  6854. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  6855. pf(x), pf(y));
  6856. j += 4;
  6857. break;
  6858. case OPS.closePath:
  6859. d.push('Z');
  6860. break;
  6861. }
  6862. }
  6863. current.path.setAttributeNS(null, 'd', d.join(' '));
  6864. current.path.setAttributeNS(null, 'stroke-miterlimit',
  6865. pf(current.miterLimit));
  6866. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  6867. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  6868. current.path.setAttributeNS(null, 'stroke-width',
  6869. pf(current.lineWidth) + 'px');
  6870. current.path.setAttributeNS(null, 'stroke-dasharray',
  6871. current.dashArray.map(pf).join(' '));
  6872. current.path.setAttributeNS(null, 'stroke-dashoffset',
  6873. pf(current.dashPhase) + 'px');
  6874. current.path.setAttributeNS(null, 'fill', 'none');
  6875. this.tgrp.appendChild(current.path);
  6876. if (current.pendingClip) {
  6877. this.cgrp.appendChild(this.tgrp);
  6878. this.pgrp.appendChild(this.cgrp);
  6879. } else {
  6880. this.pgrp.appendChild(this.tgrp);
  6881. }
  6882. // Saving a reference in current.element so that it can be addressed
  6883. // in 'fill' and 'stroke'
  6884. current.element = current.path;
  6885. current.setCurrentPoint(x, y);
  6886. },
  6887. endPath: function SVGGraphics_endPath() {
  6888. var current = this.current;
  6889. if (current.pendingClip) {
  6890. this.cgrp.appendChild(this.tgrp);
  6891. this.pgrp.appendChild(this.cgrp);
  6892. } else {
  6893. this.pgrp.appendChild(this.tgrp);
  6894. }
  6895. this.tgrp = document.createElementNS(NS, 'svg:g');
  6896. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6897. },
  6898. clip: function SVGGraphics_clip(type) {
  6899. var current = this.current;
  6900. // Add current path to clipping path
  6901. current.clipId = 'clippath' + clipCount;
  6902. clipCount++;
  6903. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  6904. this.clippath.setAttributeNS(null, 'id', current.clipId);
  6905. var clipElement = current.element.cloneNode();
  6906. if (type === 'evenodd') {
  6907. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  6908. } else {
  6909. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  6910. }
  6911. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6912. this.clippath.appendChild(clipElement);
  6913. this.defs.appendChild(this.clippath);
  6914. // Create a new group with that attribute
  6915. current.pendingClip = true;
  6916. this.cgrp = document.createElementNS(NS, 'svg:g');
  6917. this.cgrp.setAttributeNS(null, 'clip-path',
  6918. 'url(#' + current.clipId + ')');
  6919. this.pgrp.appendChild(this.cgrp);
  6920. },
  6921. closePath: function SVGGraphics_closePath() {
  6922. var current = this.current;
  6923. var d = current.path.getAttributeNS(null, 'd');
  6924. d += 'Z';
  6925. current.path.setAttributeNS(null, 'd', d);
  6926. },
  6927. setLeading: function SVGGraphics_setLeading(leading) {
  6928. this.current.leading = -leading;
  6929. },
  6930. setTextRise: function SVGGraphics_setTextRise(textRise) {
  6931. this.current.textRise = textRise;
  6932. },
  6933. setHScale: function SVGGraphics_setHScale(scale) {
  6934. this.current.textHScale = scale / 100;
  6935. },
  6936. setGState: function SVGGraphics_setGState(states) {
  6937. for (var i = 0, ii = states.length; i < ii; i++) {
  6938. var state = states[i];
  6939. var key = state[0];
  6940. var value = state[1];
  6941. switch (key) {
  6942. case 'LW':
  6943. this.setLineWidth(value);
  6944. break;
  6945. case 'LC':
  6946. this.setLineCap(value);
  6947. break;
  6948. case 'LJ':
  6949. this.setLineJoin(value);
  6950. break;
  6951. case 'ML':
  6952. this.setMiterLimit(value);
  6953. break;
  6954. case 'D':
  6955. this.setDash(value[0], value[1]);
  6956. break;
  6957. case 'RI':
  6958. break;
  6959. case 'FL':
  6960. break;
  6961. case 'Font':
  6962. this.setFont(value);
  6963. break;
  6964. case 'CA':
  6965. break;
  6966. case 'ca':
  6967. break;
  6968. case 'BM':
  6969. break;
  6970. case 'SMask':
  6971. break;
  6972. }
  6973. }
  6974. },
  6975. fill: function SVGGraphics_fill() {
  6976. var current = this.current;
  6977. current.element.setAttributeNS(null, 'fill', current.fillColor);
  6978. },
  6979. stroke: function SVGGraphics_stroke() {
  6980. var current = this.current;
  6981. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  6982. current.element.setAttributeNS(null, 'fill', 'none');
  6983. },
  6984. eoFill: function SVGGraphics_eoFill() {
  6985. var current = this.current;
  6986. current.element.setAttributeNS(null, 'fill', current.fillColor);
  6987. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  6988. },
  6989. fillStroke: function SVGGraphics_fillStroke() {
  6990. // Order is important since stroke wants fill to be none.
  6991. // First stroke, then if fill needed, it will be overwritten.
  6992. this.stroke();
  6993. this.fill();
  6994. },
  6995. eoFillStroke: function SVGGraphics_eoFillStroke() {
  6996. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  6997. this.fillStroke();
  6998. },
  6999. closeStroke: function SVGGraphics_closeStroke() {
  7000. this.closePath();
  7001. this.stroke();
  7002. },
  7003. closeFillStroke: function SVGGraphics_closeFillStroke() {
  7004. this.closePath();
  7005. this.fillStroke();
  7006. },
  7007. paintSolidColorImageMask:
  7008. function SVGGraphics_paintSolidColorImageMask() {
  7009. var current = this.current;
  7010. var rect = document.createElementNS(NS, 'svg:rect');
  7011. rect.setAttributeNS(null, 'x', '0');
  7012. rect.setAttributeNS(null, 'y', '0');
  7013. rect.setAttributeNS(null, 'width', '1px');
  7014. rect.setAttributeNS(null, 'height', '1px');
  7015. rect.setAttributeNS(null, 'fill', current.fillColor);
  7016. this.tgrp.appendChild(rect);
  7017. },
  7018. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  7019. var current = this.current;
  7020. var imgObj = this.objs.get(objId);
  7021. var imgEl = document.createElementNS(NS, 'svg:image');
  7022. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  7023. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  7024. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  7025. imgEl.setAttributeNS(null, 'x', '0');
  7026. imgEl.setAttributeNS(null, 'y', pf(-h));
  7027. imgEl.setAttributeNS(null, 'transform',
  7028. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  7029. this.tgrp.appendChild(imgEl);
  7030. if (current.pendingClip) {
  7031. this.cgrp.appendChild(this.tgrp);
  7032. this.pgrp.appendChild(this.cgrp);
  7033. } else {
  7034. this.pgrp.appendChild(this.tgrp);
  7035. }
  7036. },
  7037. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  7038. var imgData = this.objs.get(objId);
  7039. if (!imgData) {
  7040. warn('Dependent image isn\'t ready yet');
  7041. return;
  7042. }
  7043. this.paintInlineImageXObject(imgData);
  7044. },
  7045. paintInlineImageXObject:
  7046. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  7047. var current = this.current;
  7048. var width = imgData.width;
  7049. var height = imgData.height;
  7050. var imgSrc = convertImgDataToPng(imgData);
  7051. var cliprect = document.createElementNS(NS, 'svg:rect');
  7052. cliprect.setAttributeNS(null, 'x', '0');
  7053. cliprect.setAttributeNS(null, 'y', '0');
  7054. cliprect.setAttributeNS(null, 'width', pf(width));
  7055. cliprect.setAttributeNS(null, 'height', pf(height));
  7056. current.element = cliprect;
  7057. this.clip('nonzero');
  7058. var imgEl = document.createElementNS(NS, 'svg:image');
  7059. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  7060. imgEl.setAttributeNS(null, 'x', '0');
  7061. imgEl.setAttributeNS(null, 'y', pf(-height));
  7062. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  7063. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  7064. imgEl.setAttributeNS(null, 'transform',
  7065. 'scale(' + pf(1 / width) + ' ' +
  7066. pf(-1 / height) + ')');
  7067. if (mask) {
  7068. mask.appendChild(imgEl);
  7069. } else {
  7070. this.tgrp.appendChild(imgEl);
  7071. }
  7072. if (current.pendingClip) {
  7073. this.cgrp.appendChild(this.tgrp);
  7074. this.pgrp.appendChild(this.cgrp);
  7075. } else {
  7076. this.pgrp.appendChild(this.tgrp);
  7077. }
  7078. },
  7079. paintImageMaskXObject:
  7080. function SVGGraphics_paintImageMaskXObject(imgData) {
  7081. var current = this.current;
  7082. var width = imgData.width;
  7083. var height = imgData.height;
  7084. var fillColor = current.fillColor;
  7085. current.maskId = 'mask' + maskCount++;
  7086. var mask = document.createElementNS(NS, 'svg:mask');
  7087. mask.setAttributeNS(null, 'id', current.maskId);
  7088. var rect = document.createElementNS(NS, 'svg:rect');
  7089. rect.setAttributeNS(null, 'x', '0');
  7090. rect.setAttributeNS(null, 'y', '0');
  7091. rect.setAttributeNS(null, 'width', pf(width));
  7092. rect.setAttributeNS(null, 'height', pf(height));
  7093. rect.setAttributeNS(null, 'fill', fillColor);
  7094. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  7095. this.defs.appendChild(mask);
  7096. this.tgrp.appendChild(rect);
  7097. this.paintInlineImageXObject(imgData, mask);
  7098. },
  7099. paintFormXObjectBegin:
  7100. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  7101. this.save();
  7102. if (isArray(matrix) && matrix.length === 6) {
  7103. this.transform(matrix[0], matrix[1], matrix[2],
  7104. matrix[3], matrix[4], matrix[5]);
  7105. }
  7106. if (isArray(bbox) && bbox.length === 4) {
  7107. var width = bbox[2] - bbox[0];
  7108. var height = bbox[3] - bbox[1];
  7109. var cliprect = document.createElementNS(NS, 'svg:rect');
  7110. cliprect.setAttributeNS(null, 'x', bbox[0]);
  7111. cliprect.setAttributeNS(null, 'y', bbox[1]);
  7112. cliprect.setAttributeNS(null, 'width', pf(width));
  7113. cliprect.setAttributeNS(null, 'height', pf(height));
  7114. this.current.element = cliprect;
  7115. this.clip('nonzero');
  7116. this.endPath();
  7117. }
  7118. },
  7119. paintFormXObjectEnd:
  7120. function SVGGraphics_paintFormXObjectEnd() {
  7121. this.restore();
  7122. }
  7123. };
  7124. return SVGGraphics;
  7125. })();
  7126. PDFJS.SVGGraphics = SVGGraphics;
  7127. var NetworkManager = (function NetworkManagerClosure() {
  7128. var OK_RESPONSE = 200;
  7129. var PARTIAL_CONTENT_RESPONSE = 206;
  7130. function NetworkManager(url, args) {
  7131. this.url = url;
  7132. args = args || {};
  7133. this.isHttp = /^https?:/i.test(url);
  7134. this.httpHeaders = (this.isHttp && args.httpHeaders) || {};
  7135. this.withCredentials = args.withCredentials || false;
  7136. this.getXhr = args.getXhr ||
  7137. function NetworkManager_getXhr() {
  7138. return new XMLHttpRequest();
  7139. };
  7140. this.currXhrId = 0;
  7141. this.pendingRequests = {};
  7142. this.loadedRequests = {};
  7143. }
  7144. function getArrayBuffer(xhr) {
  7145. var data = xhr.response;
  7146. if (typeof data !== 'string') {
  7147. return data;
  7148. }
  7149. var length = data.length;
  7150. var array = new Uint8Array(length);
  7151. for (var i = 0; i < length; i++) {
  7152. array[i] = data.charCodeAt(i) & 0xFF;
  7153. }
  7154. return array.buffer;
  7155. }
  7156. var supportsMozChunked = (function supportsMozChunkedClosure() {
  7157. var x = new XMLHttpRequest();
  7158. try {
  7159. // Firefox 37- required .open() to be called before setting responseType.
  7160. // https://bugzilla.mozilla.org/show_bug.cgi?id=707484
  7161. x.open('GET', 'https://example.com');
  7162. } catch (e) {
  7163. // Even though the URL is not visited, .open() could fail if the URL is
  7164. // blocked, e.g. via the connect-src CSP directive or the NoScript addon.
  7165. // When this error occurs, this feature detection method will mistakenly
  7166. // report that moz-chunked-arraybuffer is not supported in Firefox 37-.
  7167. }
  7168. try {
  7169. x.responseType = 'moz-chunked-arraybuffer';
  7170. return x.responseType === 'moz-chunked-arraybuffer';
  7171. } catch (e) {
  7172. return false;
  7173. }
  7174. })();
  7175. NetworkManager.prototype = {
  7176. requestRange: function NetworkManager_requestRange(begin, end, listeners) {
  7177. var args = {
  7178. begin: begin,
  7179. end: end
  7180. };
  7181. for (var prop in listeners) {
  7182. args[prop] = listeners[prop];
  7183. }
  7184. return this.request(args);
  7185. },
  7186. requestFull: function NetworkManager_requestFull(listeners) {
  7187. return this.request(listeners);
  7188. },
  7189. request: function NetworkManager_request(args) {
  7190. var xhr = this.getXhr();
  7191. var xhrId = this.currXhrId++;
  7192. var pendingRequest = this.pendingRequests[xhrId] = {
  7193. xhr: xhr
  7194. };
  7195. xhr.open('GET', this.url);
  7196. xhr.withCredentials = this.withCredentials;
  7197. for (var property in this.httpHeaders) {
  7198. var value = this.httpHeaders[property];
  7199. if (typeof value === 'undefined') {
  7200. continue;
  7201. }
  7202. xhr.setRequestHeader(property, value);
  7203. }
  7204. if (this.isHttp && 'begin' in args && 'end' in args) {
  7205. var rangeStr = args.begin + '-' + (args.end - 1);
  7206. xhr.setRequestHeader('Range', 'bytes=' + rangeStr);
  7207. pendingRequest.expectedStatus = 206;
  7208. } else {
  7209. pendingRequest.expectedStatus = 200;
  7210. }
  7211. var useMozChunkedLoading = supportsMozChunked && !!args.onProgressiveData;
  7212. if (useMozChunkedLoading) {
  7213. xhr.responseType = 'moz-chunked-arraybuffer';
  7214. pendingRequest.onProgressiveData = args.onProgressiveData;
  7215. pendingRequest.mozChunked = true;
  7216. } else {
  7217. xhr.responseType = 'arraybuffer';
  7218. }
  7219. if (args.onError) {
  7220. xhr.onerror = function(evt) {
  7221. args.onError(xhr.status);
  7222. };
  7223. }
  7224. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  7225. xhr.onprogress = this.onProgress.bind(this, xhrId);
  7226. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  7227. pendingRequest.onDone = args.onDone;
  7228. pendingRequest.onError = args.onError;
  7229. pendingRequest.onProgress = args.onProgress;
  7230. xhr.send(null);
  7231. return xhrId;
  7232. },
  7233. onProgress: function NetworkManager_onProgress(xhrId, evt) {
  7234. var pendingRequest = this.pendingRequests[xhrId];
  7235. if (!pendingRequest) {
  7236. // Maybe abortRequest was called...
  7237. return;
  7238. }
  7239. if (pendingRequest.mozChunked) {
  7240. var chunk = getArrayBuffer(pendingRequest.xhr);
  7241. pendingRequest.onProgressiveData(chunk);
  7242. }
  7243. var onProgress = pendingRequest.onProgress;
  7244. if (onProgress) {
  7245. onProgress(evt);
  7246. }
  7247. },
  7248. onStateChange: function NetworkManager_onStateChange(xhrId, evt) {
  7249. var pendingRequest = this.pendingRequests[xhrId];
  7250. if (!pendingRequest) {
  7251. // Maybe abortRequest was called...
  7252. return;
  7253. }
  7254. var xhr = pendingRequest.xhr;
  7255. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  7256. pendingRequest.onHeadersReceived();
  7257. delete pendingRequest.onHeadersReceived;
  7258. }
  7259. if (xhr.readyState !== 4) {
  7260. return;
  7261. }
  7262. if (!(xhrId in this.pendingRequests)) {
  7263. // The XHR request might have been aborted in onHeadersReceived()
  7264. // callback, in which case we should abort request
  7265. return;
  7266. }
  7267. delete this.pendingRequests[xhrId];
  7268. // success status == 0 can be on ftp, file and other protocols
  7269. if (xhr.status === 0 && this.isHttp) {
  7270. if (pendingRequest.onError) {
  7271. pendingRequest.onError(xhr.status);
  7272. }
  7273. return;
  7274. }
  7275. var xhrStatus = xhr.status || OK_RESPONSE;
  7276. // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2:
  7277. // "A server MAY ignore the Range header". This means it's possible to
  7278. // get a 200 rather than a 206 response from a range request.
  7279. var ok_response_on_range_request =
  7280. xhrStatus === OK_RESPONSE &&
  7281. pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  7282. if (!ok_response_on_range_request &&
  7283. xhrStatus !== pendingRequest.expectedStatus) {
  7284. if (pendingRequest.onError) {
  7285. pendingRequest.onError(xhr.status);
  7286. }
  7287. return;
  7288. }
  7289. this.loadedRequests[xhrId] = true;
  7290. var chunk = getArrayBuffer(xhr);
  7291. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  7292. var rangeHeader = xhr.getResponseHeader('Content-Range');
  7293. var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  7294. var begin = parseInt(matches[1], 10);
  7295. pendingRequest.onDone({
  7296. begin: begin,
  7297. chunk: chunk
  7298. });
  7299. } else if (pendingRequest.onProgressiveData) {
  7300. pendingRequest.onDone(null);
  7301. } else {
  7302. pendingRequest.onDone({
  7303. begin: 0,
  7304. chunk: chunk
  7305. });
  7306. }
  7307. },
  7308. hasPendingRequests: function NetworkManager_hasPendingRequests() {
  7309. for (var xhrId in this.pendingRequests) {
  7310. return true;
  7311. }
  7312. return false;
  7313. },
  7314. getRequestXhr: function NetworkManager_getXhr(xhrId) {
  7315. return this.pendingRequests[xhrId].xhr;
  7316. },
  7317. isStreamingRequest: function NetworkManager_isStreamingRequest(xhrId) {
  7318. return !!(this.pendingRequests[xhrId].onProgressiveData);
  7319. },
  7320. isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {
  7321. return xhrId in this.pendingRequests;
  7322. },
  7323. isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {
  7324. return xhrId in this.loadedRequests;
  7325. },
  7326. abortAllRequests: function NetworkManager_abortAllRequests() {
  7327. for (var xhrId in this.pendingRequests) {
  7328. this.abortRequest(xhrId | 0);
  7329. }
  7330. },
  7331. abortRequest: function NetworkManager_abortRequest(xhrId) {
  7332. var xhr = this.pendingRequests[xhrId].xhr;
  7333. delete this.pendingRequests[xhrId];
  7334. xhr.abort();
  7335. }
  7336. };
  7337. return NetworkManager;
  7338. })();
  7339. var ChunkedStream = (function ChunkedStreamClosure() {
  7340. function ChunkedStream(length, chunkSize, manager) {
  7341. this.bytes = new Uint8Array(length);
  7342. this.start = 0;
  7343. this.pos = 0;
  7344. this.end = length;
  7345. this.chunkSize = chunkSize;
  7346. this.loadedChunks = [];
  7347. this.numChunksLoaded = 0;
  7348. this.numChunks = Math.ceil(length / chunkSize);
  7349. this.manager = manager;
  7350. this.progressiveDataLength = 0;
  7351. this.lastSuccessfulEnsureByteChunk = -1; // a single-entry cache
  7352. }
  7353. // required methods for a stream. if a particular stream does not
  7354. // implement these, an error should be thrown
  7355. ChunkedStream.prototype = {
  7356. getMissingChunks: function ChunkedStream_getMissingChunks() {
  7357. var chunks = [];
  7358. for (var chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
  7359. if (!this.loadedChunks[chunk]) {
  7360. chunks.push(chunk);
  7361. }
  7362. }
  7363. return chunks;
  7364. },
  7365. getBaseStreams: function ChunkedStream_getBaseStreams() {
  7366. return [this];
  7367. },
  7368. allChunksLoaded: function ChunkedStream_allChunksLoaded() {
  7369. return this.numChunksLoaded === this.numChunks;
  7370. },
  7371. onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) {
  7372. var end = begin + chunk.byteLength;
  7373. assert(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin);
  7374. // Using this.length is inaccurate here since this.start can be moved
  7375. // See ChunkedStream.moveStart()
  7376. var length = this.bytes.length;
  7377. assert(end % this.chunkSize === 0 || end === length,
  7378. 'Bad end offset: ' + end);
  7379. this.bytes.set(new Uint8Array(chunk), begin);
  7380. var chunkSize = this.chunkSize;
  7381. var beginChunk = Math.floor(begin / chunkSize);
  7382. var endChunk = Math.floor((end - 1) / chunkSize) + 1;
  7383. var curChunk;
  7384. for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  7385. if (!this.loadedChunks[curChunk]) {
  7386. this.loadedChunks[curChunk] = true;
  7387. ++this.numChunksLoaded;
  7388. }
  7389. }
  7390. },
  7391. onReceiveProgressiveData:
  7392. function ChunkedStream_onReceiveProgressiveData(data) {
  7393. var position = this.progressiveDataLength;
  7394. var beginChunk = Math.floor(position / this.chunkSize);
  7395. this.bytes.set(new Uint8Array(data), position);
  7396. position += data.byteLength;
  7397. this.progressiveDataLength = position;
  7398. var endChunk = position >= this.end ? this.numChunks :
  7399. Math.floor(position / this.chunkSize);
  7400. var curChunk;
  7401. for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  7402. if (!this.loadedChunks[curChunk]) {
  7403. this.loadedChunks[curChunk] = true;
  7404. ++this.numChunksLoaded;
  7405. }
  7406. }
  7407. },
  7408. ensureByte: function ChunkedStream_ensureByte(pos) {
  7409. var chunk = Math.floor(pos / this.chunkSize);
  7410. if (chunk === this.lastSuccessfulEnsureByteChunk) {
  7411. return;
  7412. }
  7413. if (!this.loadedChunks[chunk]) {
  7414. throw new MissingDataException(pos, pos + 1);
  7415. }
  7416. this.lastSuccessfulEnsureByteChunk = chunk;
  7417. },
  7418. ensureRange: function ChunkedStream_ensureRange(begin, end) {
  7419. if (begin >= end) {
  7420. return;
  7421. }
  7422. if (end <= this.progressiveDataLength) {
  7423. return;
  7424. }
  7425. var chunkSize = this.chunkSize;
  7426. var beginChunk = Math.floor(begin / chunkSize);
  7427. var endChunk = Math.floor((end - 1) / chunkSize) + 1;
  7428. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7429. if (!this.loadedChunks[chunk]) {
  7430. throw new MissingDataException(begin, end);
  7431. }
  7432. }
  7433. },
  7434. nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) {
  7435. var chunk, n;
  7436. for (chunk = beginChunk, n = this.numChunks; chunk < n; ++chunk) {
  7437. if (!this.loadedChunks[chunk]) {
  7438. return chunk;
  7439. }
  7440. }
  7441. // Wrap around to beginning
  7442. for (chunk = 0; chunk < beginChunk; ++chunk) {
  7443. if (!this.loadedChunks[chunk]) {
  7444. return chunk;
  7445. }
  7446. }
  7447. return null;
  7448. },
  7449. hasChunk: function ChunkedStream_hasChunk(chunk) {
  7450. return !!this.loadedChunks[chunk];
  7451. },
  7452. get length() {
  7453. return this.end - this.start;
  7454. },
  7455. get isEmpty() {
  7456. return this.length === 0;
  7457. },
  7458. getByte: function ChunkedStream_getByte() {
  7459. var pos = this.pos;
  7460. if (pos >= this.end) {
  7461. return -1;
  7462. }
  7463. this.ensureByte(pos);
  7464. return this.bytes[this.pos++];
  7465. },
  7466. getUint16: function ChunkedStream_getUint16() {
  7467. var b0 = this.getByte();
  7468. var b1 = this.getByte();
  7469. if (b0 === -1 || b1 === -1) {
  7470. return -1;
  7471. }
  7472. return (b0 << 8) + b1;
  7473. },
  7474. getInt32: function ChunkedStream_getInt32() {
  7475. var b0 = this.getByte();
  7476. var b1 = this.getByte();
  7477. var b2 = this.getByte();
  7478. var b3 = this.getByte();
  7479. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  7480. },
  7481. // returns subarray of original buffer
  7482. // should only be read
  7483. getBytes: function ChunkedStream_getBytes(length) {
  7484. var bytes = this.bytes;
  7485. var pos = this.pos;
  7486. var strEnd = this.end;
  7487. if (!length) {
  7488. this.ensureRange(pos, strEnd);
  7489. return bytes.subarray(pos, strEnd);
  7490. }
  7491. var end = pos + length;
  7492. if (end > strEnd) {
  7493. end = strEnd;
  7494. }
  7495. this.ensureRange(pos, end);
  7496. this.pos = end;
  7497. return bytes.subarray(pos, end);
  7498. },
  7499. peekByte: function ChunkedStream_peekByte() {
  7500. var peekedByte = this.getByte();
  7501. this.pos--;
  7502. return peekedByte;
  7503. },
  7504. peekBytes: function ChunkedStream_peekBytes(length) {
  7505. var bytes = this.getBytes(length);
  7506. this.pos -= bytes.length;
  7507. return bytes;
  7508. },
  7509. getByteRange: function ChunkedStream_getBytes(begin, end) {
  7510. this.ensureRange(begin, end);
  7511. return this.bytes.subarray(begin, end);
  7512. },
  7513. skip: function ChunkedStream_skip(n) {
  7514. if (!n) {
  7515. n = 1;
  7516. }
  7517. this.pos += n;
  7518. },
  7519. reset: function ChunkedStream_reset() {
  7520. this.pos = this.start;
  7521. },
  7522. moveStart: function ChunkedStream_moveStart() {
  7523. this.start = this.pos;
  7524. },
  7525. makeSubStream: function ChunkedStream_makeSubStream(start, length, dict) {
  7526. this.ensureRange(start, start + length);
  7527. function ChunkedStreamSubstream() {}
  7528. ChunkedStreamSubstream.prototype = Object.create(this);
  7529. ChunkedStreamSubstream.prototype.getMissingChunks = function() {
  7530. var chunkSize = this.chunkSize;
  7531. var beginChunk = Math.floor(this.start / chunkSize);
  7532. var endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
  7533. var missingChunks = [];
  7534. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7535. if (!this.loadedChunks[chunk]) {
  7536. missingChunks.push(chunk);
  7537. }
  7538. }
  7539. return missingChunks;
  7540. };
  7541. var subStream = new ChunkedStreamSubstream();
  7542. subStream.pos = subStream.start = start;
  7543. subStream.end = start + length || this.end;
  7544. subStream.dict = dict;
  7545. return subStream;
  7546. },
  7547. isStream: true
  7548. };
  7549. return ChunkedStream;
  7550. })();
  7551. var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {
  7552. function ChunkedStreamManager(length, chunkSize, url, args) {
  7553. this.stream = new ChunkedStream(length, chunkSize, this);
  7554. this.length = length;
  7555. this.chunkSize = chunkSize;
  7556. this.url = url;
  7557. this.disableAutoFetch = args.disableAutoFetch;
  7558. var msgHandler = this.msgHandler = args.msgHandler;
  7559. if (args.chunkedViewerLoading) {
  7560. msgHandler.on('OnDataRange', this.onReceiveData.bind(this));
  7561. msgHandler.on('OnDataProgress', this.onProgress.bind(this));
  7562. this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {
  7563. msgHandler.send('RequestDataRange', { begin: begin, end: end });
  7564. };
  7565. } else {
  7566. var getXhr = function getXhr() {
  7567. return new XMLHttpRequest();
  7568. };
  7569. this.networkManager = new NetworkManager(this.url, {
  7570. getXhr: getXhr,
  7571. httpHeaders: args.httpHeaders,
  7572. withCredentials: args.withCredentials
  7573. });
  7574. this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {
  7575. this.networkManager.requestRange(begin, end, {
  7576. onDone: this.onReceiveData.bind(this),
  7577. onProgress: this.onProgress.bind(this)
  7578. });
  7579. };
  7580. }
  7581. this.currRequestId = 0;
  7582. this.chunksNeededByRequest = {};
  7583. this.requestsByChunk = {};
  7584. this.callbacksByRequest = {};
  7585. this.progressiveDataLength = 0;
  7586. this._loadedStreamCapability = createPromiseCapability();
  7587. if (args.initialData) {
  7588. this.onReceiveData({chunk: args.initialData});
  7589. }
  7590. }
  7591. ChunkedStreamManager.prototype = {
  7592. onLoadedStream: function ChunkedStreamManager_getLoadedStream() {
  7593. return this._loadedStreamCapability.promise;
  7594. },
  7595. // Get all the chunks that are not yet loaded and groups them into
  7596. // contiguous ranges to load in as few requests as possible
  7597. requestAllChunks: function ChunkedStreamManager_requestAllChunks() {
  7598. var missingChunks = this.stream.getMissingChunks();
  7599. this.requestChunks(missingChunks);
  7600. return this._loadedStreamCapability.promise;
  7601. },
  7602. requestChunks: function ChunkedStreamManager_requestChunks(chunks,
  7603. callback) {
  7604. var requestId = this.currRequestId++;
  7605. var chunksNeeded;
  7606. var i, ii;
  7607. this.chunksNeededByRequest[requestId] = chunksNeeded = {};
  7608. for (i = 0, ii = chunks.length; i < ii; i++) {
  7609. if (!this.stream.hasChunk(chunks[i])) {
  7610. chunksNeeded[chunks[i]] = true;
  7611. }
  7612. }
  7613. if (isEmptyObj(chunksNeeded)) {
  7614. if (callback) {
  7615. callback();
  7616. }
  7617. return;
  7618. }
  7619. this.callbacksByRequest[requestId] = callback;
  7620. var chunksToRequest = [];
  7621. for (var chunk in chunksNeeded) {
  7622. chunk = chunk | 0;
  7623. if (!(chunk in this.requestsByChunk)) {
  7624. this.requestsByChunk[chunk] = [];
  7625. chunksToRequest.push(chunk);
  7626. }
  7627. this.requestsByChunk[chunk].push(requestId);
  7628. }
  7629. if (!chunksToRequest.length) {
  7630. return;
  7631. }
  7632. var groupedChunksToRequest = this.groupChunks(chunksToRequest);
  7633. for (i = 0; i < groupedChunksToRequest.length; ++i) {
  7634. var groupedChunk = groupedChunksToRequest[i];
  7635. var begin = groupedChunk.beginChunk * this.chunkSize;
  7636. var end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
  7637. this.sendRequest(begin, end);
  7638. }
  7639. },
  7640. getStream: function ChunkedStreamManager_getStream() {
  7641. return this.stream;
  7642. },
  7643. // Loads any chunks in the requested range that are not yet loaded
  7644. requestRange: function ChunkedStreamManager_requestRange(
  7645. begin, end, callback) {
  7646. end = Math.min(end, this.length);
  7647. var beginChunk = this.getBeginChunk(begin);
  7648. var endChunk = this.getEndChunk(end);
  7649. var chunks = [];
  7650. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7651. chunks.push(chunk);
  7652. }
  7653. this.requestChunks(chunks, callback);
  7654. },
  7655. requestRanges: function ChunkedStreamManager_requestRanges(ranges,
  7656. callback) {
  7657. ranges = ranges || [];
  7658. var chunksToRequest = [];
  7659. for (var i = 0; i < ranges.length; i++) {
  7660. var beginChunk = this.getBeginChunk(ranges[i].begin);
  7661. var endChunk = this.getEndChunk(ranges[i].end);
  7662. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7663. if (chunksToRequest.indexOf(chunk) < 0) {
  7664. chunksToRequest.push(chunk);
  7665. }
  7666. }
  7667. }
  7668. chunksToRequest.sort(function(a, b) { return a - b; });
  7669. this.requestChunks(chunksToRequest, callback);
  7670. },
  7671. // Groups a sorted array of chunks into as few continguous larger
  7672. // chunks as possible
  7673. groupChunks: function ChunkedStreamManager_groupChunks(chunks) {
  7674. var groupedChunks = [];
  7675. var beginChunk = -1;
  7676. var prevChunk = -1;
  7677. for (var i = 0; i < chunks.length; ++i) {
  7678. var chunk = chunks[i];
  7679. if (beginChunk < 0) {
  7680. beginChunk = chunk;
  7681. }
  7682. if (prevChunk >= 0 && prevChunk + 1 !== chunk) {
  7683. groupedChunks.push({ beginChunk: beginChunk,
  7684. endChunk: prevChunk + 1 });
  7685. beginChunk = chunk;
  7686. }
  7687. if (i + 1 === chunks.length) {
  7688. groupedChunks.push({ beginChunk: beginChunk,
  7689. endChunk: chunk + 1 });
  7690. }
  7691. prevChunk = chunk;
  7692. }
  7693. return groupedChunks;
  7694. },
  7695. onProgress: function ChunkedStreamManager_onProgress(args) {
  7696. var bytesLoaded = (this.stream.numChunksLoaded * this.chunkSize +
  7697. args.loaded);
  7698. this.msgHandler.send('DocProgress', {
  7699. loaded: bytesLoaded,
  7700. total: this.length
  7701. });
  7702. },
  7703. onReceiveData: function ChunkedStreamManager_onReceiveData(args) {
  7704. var chunk = args.chunk;
  7705. var isProgressive = args.begin === undefined;
  7706. var begin = isProgressive ? this.progressiveDataLength : args.begin;
  7707. var end = begin + chunk.byteLength;
  7708. var beginChunk = Math.floor(begin / this.chunkSize);
  7709. var endChunk = end < this.length ? Math.floor(end / this.chunkSize) :
  7710. Math.ceil(end / this.chunkSize);
  7711. if (isProgressive) {
  7712. this.stream.onReceiveProgressiveData(chunk);
  7713. this.progressiveDataLength = end;
  7714. } else {
  7715. this.stream.onReceiveData(begin, chunk);
  7716. }
  7717. if (this.stream.allChunksLoaded()) {
  7718. this._loadedStreamCapability.resolve(this.stream);
  7719. }
  7720. var loadedRequests = [];
  7721. var i, requestId;
  7722. for (chunk = beginChunk; chunk < endChunk; ++chunk) {
  7723. // The server might return more chunks than requested
  7724. var requestIds = this.requestsByChunk[chunk] || [];
  7725. delete this.requestsByChunk[chunk];
  7726. for (i = 0; i < requestIds.length; ++i) {
  7727. requestId = requestIds[i];
  7728. var chunksNeeded = this.chunksNeededByRequest[requestId];
  7729. if (chunk in chunksNeeded) {
  7730. delete chunksNeeded[chunk];
  7731. }
  7732. if (!isEmptyObj(chunksNeeded)) {
  7733. continue;
  7734. }
  7735. loadedRequests.push(requestId);
  7736. }
  7737. }
  7738. // If there are no pending requests, automatically fetch the next
  7739. // unfetched chunk of the PDF
  7740. if (!this.disableAutoFetch && isEmptyObj(this.requestsByChunk)) {
  7741. var nextEmptyChunk;
  7742. if (this.stream.numChunksLoaded === 1) {
  7743. // This is a special optimization so that after fetching the first
  7744. // chunk, rather than fetching the second chunk, we fetch the last
  7745. // chunk.
  7746. var lastChunk = this.stream.numChunks - 1;
  7747. if (!this.stream.hasChunk(lastChunk)) {
  7748. nextEmptyChunk = lastChunk;
  7749. }
  7750. } else {
  7751. nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
  7752. }
  7753. if (isInt(nextEmptyChunk)) {
  7754. this.requestChunks([nextEmptyChunk]);
  7755. }
  7756. }
  7757. for (i = 0; i < loadedRequests.length; ++i) {
  7758. requestId = loadedRequests[i];
  7759. var callback = this.callbacksByRequest[requestId];
  7760. delete this.callbacksByRequest[requestId];
  7761. if (callback) {
  7762. callback();
  7763. }
  7764. }
  7765. this.msgHandler.send('DocProgress', {
  7766. loaded: this.stream.numChunksLoaded * this.chunkSize,
  7767. total: this.length
  7768. });
  7769. },
  7770. onError: function ChunkedStreamManager_onError(err) {
  7771. this._loadedStreamCapability.reject(err);
  7772. },
  7773. getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) {
  7774. var chunk = Math.floor(begin / this.chunkSize);
  7775. return chunk;
  7776. },
  7777. getEndChunk: function ChunkedStreamManager_getEndChunk(end) {
  7778. if (end % this.chunkSize === 0) {
  7779. return end / this.chunkSize;
  7780. }
  7781. // 0 -> 0
  7782. // 1 -> 1
  7783. // 99 -> 1
  7784. // 100 -> 1
  7785. // 101 -> 2
  7786. var chunk = Math.floor((end - 1) / this.chunkSize) + 1;
  7787. return chunk;
  7788. }
  7789. };
  7790. return ChunkedStreamManager;
  7791. })();
  7792. // The maximum number of bytes fetched per range request
  7793. var RANGE_CHUNK_SIZE = 65536;
  7794. // TODO(mack): Make use of PDFJS.Util.inherit() when it becomes available
  7795. var BasePdfManager = (function BasePdfManagerClosure() {
  7796. function BasePdfManager() {
  7797. throw new Error('Cannot initialize BaseManagerManager');
  7798. }
  7799. BasePdfManager.prototype = {
  7800. onLoadedStream: function BasePdfManager_onLoadedStream() {
  7801. throw new NotImplementedException();
  7802. },
  7803. ensureDoc: function BasePdfManager_ensureDoc(prop, args) {
  7804. return this.ensure(this.pdfDocument, prop, args);
  7805. },
  7806. ensureXRef: function BasePdfManager_ensureXRef(prop, args) {
  7807. return this.ensure(this.pdfDocument.xref, prop, args);
  7808. },
  7809. ensureCatalog: function BasePdfManager_ensureCatalog(prop, args) {
  7810. return this.ensure(this.pdfDocument.catalog, prop, args);
  7811. },
  7812. getPage: function BasePdfManager_pagePage(pageIndex) {
  7813. return this.pdfDocument.getPage(pageIndex);
  7814. },
  7815. cleanup: function BasePdfManager_cleanup() {
  7816. return this.pdfDocument.cleanup();
  7817. },
  7818. ensure: function BasePdfManager_ensure(obj, prop, args) {
  7819. return new NotImplementedException();
  7820. },
  7821. requestRange: function BasePdfManager_ensure(begin, end) {
  7822. return new NotImplementedException();
  7823. },
  7824. requestLoadedStream: function BasePdfManager_requestLoadedStream() {
  7825. return new NotImplementedException();
  7826. },
  7827. sendProgressiveData: function BasePdfManager_sendProgressiveData(chunk) {
  7828. return new NotImplementedException();
  7829. },
  7830. updatePassword: function BasePdfManager_updatePassword(password) {
  7831. this.pdfDocument.xref.password = this.password = password;
  7832. if (this._passwordChangedCapability) {
  7833. this._passwordChangedCapability.resolve();
  7834. }
  7835. },
  7836. passwordChanged: function BasePdfManager_passwordChanged() {
  7837. this._passwordChangedCapability = createPromiseCapability();
  7838. return this._passwordChangedCapability.promise;
  7839. },
  7840. terminate: function BasePdfManager_terminate() {
  7841. return new NotImplementedException();
  7842. }
  7843. };
  7844. return BasePdfManager;
  7845. })();
  7846. var LocalPdfManager = (function LocalPdfManagerClosure() {
  7847. function LocalPdfManager(data, password) {
  7848. var stream = new Stream(data);
  7849. this.pdfDocument = new PDFDocument(this, stream, password);
  7850. this._loadedStreamCapability = createPromiseCapability();
  7851. this._loadedStreamCapability.resolve(stream);
  7852. }
  7853. LocalPdfManager.prototype = Object.create(BasePdfManager.prototype);
  7854. LocalPdfManager.prototype.constructor = LocalPdfManager;
  7855. LocalPdfManager.prototype.ensure =
  7856. function LocalPdfManager_ensure(obj, prop, args) {
  7857. return new Promise(function (resolve, reject) {
  7858. try {
  7859. var value = obj[prop];
  7860. var result;
  7861. if (typeof value === 'function') {
  7862. result = value.apply(obj, args);
  7863. } else {
  7864. result = value;
  7865. }
  7866. resolve(result);
  7867. } catch (e) {
  7868. reject(e);
  7869. }
  7870. });
  7871. };
  7872. LocalPdfManager.prototype.requestRange =
  7873. function LocalPdfManager_requestRange(begin, end) {
  7874. return Promise.resolve();
  7875. };
  7876. LocalPdfManager.prototype.requestLoadedStream =
  7877. function LocalPdfManager_requestLoadedStream() {
  7878. };
  7879. LocalPdfManager.prototype.onLoadedStream =
  7880. function LocalPdfManager_getLoadedStream() {
  7881. return this._loadedStreamCapability.promise;
  7882. };
  7883. LocalPdfManager.prototype.terminate =
  7884. function LocalPdfManager_terminate() {
  7885. return;
  7886. };
  7887. return LocalPdfManager;
  7888. })();
  7889. var NetworkPdfManager = (function NetworkPdfManagerClosure() {
  7890. function NetworkPdfManager(args, msgHandler) {
  7891. this.msgHandler = msgHandler;
  7892. var params = {
  7893. msgHandler: msgHandler,
  7894. httpHeaders: args.httpHeaders,
  7895. withCredentials: args.withCredentials,
  7896. chunkedViewerLoading: args.chunkedViewerLoading,
  7897. disableAutoFetch: args.disableAutoFetch,
  7898. initialData: args.initialData
  7899. };
  7900. this.streamManager = new ChunkedStreamManager(args.length, RANGE_CHUNK_SIZE,
  7901. args.url, params);
  7902. this.pdfDocument = new PDFDocument(this, this.streamManager.getStream(),
  7903. args.password);
  7904. }
  7905. NetworkPdfManager.prototype = Object.create(BasePdfManager.prototype);
  7906. NetworkPdfManager.prototype.constructor = NetworkPdfManager;
  7907. NetworkPdfManager.prototype.ensure =
  7908. function NetworkPdfManager_ensure(obj, prop, args) {
  7909. var pdfManager = this;
  7910. return new Promise(function (resolve, reject) {
  7911. function ensureHelper() {
  7912. try {
  7913. var result;
  7914. var value = obj[prop];
  7915. if (typeof value === 'function') {
  7916. result = value.apply(obj, args);
  7917. } else {
  7918. result = value;
  7919. }
  7920. resolve(result);
  7921. } catch(e) {
  7922. if (!(e instanceof MissingDataException)) {
  7923. reject(e);
  7924. return;
  7925. }
  7926. pdfManager.streamManager.requestRange(e.begin, e.end, ensureHelper);
  7927. }
  7928. }
  7929. ensureHelper();
  7930. });
  7931. };
  7932. NetworkPdfManager.prototype.requestRange =
  7933. function NetworkPdfManager_requestRange(begin, end) {
  7934. return new Promise(function (resolve) {
  7935. this.streamManager.requestRange(begin, end, function() {
  7936. resolve();
  7937. });
  7938. }.bind(this));
  7939. };
  7940. NetworkPdfManager.prototype.requestLoadedStream =
  7941. function NetworkPdfManager_requestLoadedStream() {
  7942. this.streamManager.requestAllChunks();
  7943. };
  7944. NetworkPdfManager.prototype.sendProgressiveData =
  7945. function NetworkPdfManager_sendProgressiveData(chunk) {
  7946. this.streamManager.onReceiveData({ chunk: chunk });
  7947. };
  7948. NetworkPdfManager.prototype.onLoadedStream =
  7949. function NetworkPdfManager_getLoadedStream() {
  7950. return this.streamManager.onLoadedStream();
  7951. };
  7952. NetworkPdfManager.prototype.terminate =
  7953. function NetworkPdfManager_terminate() {
  7954. this.streamManager.networkManager.abortAllRequests();
  7955. };
  7956. return NetworkPdfManager;
  7957. })();
  7958. var Page = (function PageClosure() {
  7959. var LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
  7960. function Page(pdfManager, xref, pageIndex, pageDict, ref, fontCache) {
  7961. this.pdfManager = pdfManager;
  7962. this.pageIndex = pageIndex;
  7963. this.pageDict = pageDict;
  7964. this.xref = xref;
  7965. this.ref = ref;
  7966. this.fontCache = fontCache;
  7967. this.idCounters = {
  7968. obj: 0
  7969. };
  7970. this.resourcesPromise = null;
  7971. }
  7972. Page.prototype = {
  7973. getPageProp: function Page_getPageProp(key) {
  7974. return this.pageDict.get(key);
  7975. },
  7976. getInheritedPageProp: function Page_getInheritedPageProp(key) {
  7977. var dict = this.pageDict, valueArray = null, loopCount = 0;
  7978. var MAX_LOOP_COUNT = 100;
  7979. // Always walk up the entire parent chain, to be able to find
  7980. // e.g. \Resources placed on multiple levels of the tree.
  7981. while (dict) {
  7982. var value = dict.get(key);
  7983. if (value) {
  7984. if (!valueArray) {
  7985. valueArray = [];
  7986. }
  7987. valueArray.push(value);
  7988. }
  7989. if (++loopCount > MAX_LOOP_COUNT) {
  7990. warn('Page_getInheritedPageProp: maximum loop count exceeded.');
  7991. break;
  7992. }
  7993. dict = dict.get('Parent');
  7994. }
  7995. if (!valueArray) {
  7996. return Dict.empty;
  7997. }
  7998. if (valueArray.length === 1 || !isDict(valueArray[0]) ||
  7999. loopCount > MAX_LOOP_COUNT) {
  8000. return valueArray[0];
  8001. }
  8002. return Dict.merge(this.xref, valueArray);
  8003. },
  8004. get content() {
  8005. return this.getPageProp('Contents');
  8006. },
  8007. get resources() {
  8008. // For robustness: The spec states that a \Resources entry has to be
  8009. // present, but can be empty. Some document omit it still, in this case
  8010. // we return an empty dictionary.
  8011. return shadow(this, 'resources', this.getInheritedPageProp('Resources'));
  8012. },
  8013. get mediaBox() {
  8014. var obj = this.getInheritedPageProp('MediaBox');
  8015. // Reset invalid media box to letter size.
  8016. if (!isArray(obj) || obj.length !== 4) {
  8017. obj = LETTER_SIZE_MEDIABOX;
  8018. }
  8019. return shadow(this, 'mediaBox', obj);
  8020. },
  8021. get view() {
  8022. var mediaBox = this.mediaBox;
  8023. var cropBox = this.getInheritedPageProp('CropBox');
  8024. if (!isArray(cropBox) || cropBox.length !== 4) {
  8025. return shadow(this, 'view', mediaBox);
  8026. }
  8027. // From the spec, 6th ed., p.963:
  8028. // "The crop, bleed, trim, and art boxes should not ordinarily
  8029. // extend beyond the boundaries of the media box. If they do, they are
  8030. // effectively reduced to their intersection with the media box."
  8031. cropBox = Util.intersect(cropBox, mediaBox);
  8032. if (!cropBox) {
  8033. return shadow(this, 'view', mediaBox);
  8034. }
  8035. return shadow(this, 'view', cropBox);
  8036. },
  8037. get annotationRefs() {
  8038. return shadow(this, 'annotationRefs',
  8039. this.getInheritedPageProp('Annots'));
  8040. },
  8041. get rotate() {
  8042. var rotate = this.getInheritedPageProp('Rotate') || 0;
  8043. // Normalize rotation so it's a multiple of 90 and between 0 and 270
  8044. if (rotate % 90 !== 0) {
  8045. rotate = 0;
  8046. } else if (rotate >= 360) {
  8047. rotate = rotate % 360;
  8048. } else if (rotate < 0) {
  8049. // The spec doesn't cover negatives, assume its counterclockwise
  8050. // rotation. The following is the other implementation of modulo.
  8051. rotate = ((rotate % 360) + 360) % 360;
  8052. }
  8053. return shadow(this, 'rotate', rotate);
  8054. },
  8055. getContentStream: function Page_getContentStream() {
  8056. var content = this.content;
  8057. var stream;
  8058. if (isArray(content)) {
  8059. // fetching items
  8060. var xref = this.xref;
  8061. var i, n = content.length;
  8062. var streams = [];
  8063. for (i = 0; i < n; ++i) {
  8064. streams.push(xref.fetchIfRef(content[i]));
  8065. }
  8066. stream = new StreamsSequenceStream(streams);
  8067. } else if (isStream(content)) {
  8068. stream = content;
  8069. } else {
  8070. // replacing non-existent page content with empty one
  8071. stream = new NullStream();
  8072. }
  8073. return stream;
  8074. },
  8075. loadResources: function Page_loadResources(keys) {
  8076. if (!this.resourcesPromise) {
  8077. // TODO: add async getInheritedPageProp and remove this.
  8078. this.resourcesPromise = this.pdfManager.ensure(this, 'resources');
  8079. }
  8080. return this.resourcesPromise.then(function resourceSuccess() {
  8081. var objectLoader = new ObjectLoader(this.resources.map,
  8082. keys,
  8083. this.xref);
  8084. return objectLoader.load();
  8085. }.bind(this));
  8086. },
  8087. getOperatorList: function Page_getOperatorList(handler, intent) {
  8088. var self = this;
  8089. var pdfManager = this.pdfManager;
  8090. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',
  8091. []);
  8092. var resourcesPromise = this.loadResources([
  8093. 'ExtGState',
  8094. 'ColorSpace',
  8095. 'Pattern',
  8096. 'Shading',
  8097. 'XObject',
  8098. 'Font'
  8099. // ProcSet
  8100. // Properties
  8101. ]);
  8102. var partialEvaluator = new PartialEvaluator(pdfManager, this.xref,
  8103. handler, this.pageIndex,
  8104. 'p' + this.pageIndex + '_',
  8105. this.idCounters,
  8106. this.fontCache);
  8107. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  8108. var pageListPromise = dataPromises.then(function(data) {
  8109. var contentStream = data[0];
  8110. var opList = new OperatorList(intent, handler, self.pageIndex);
  8111. handler.send('StartRenderPage', {
  8112. transparency: partialEvaluator.hasBlendModes(self.resources),
  8113. pageIndex: self.pageIndex,
  8114. intent: intent
  8115. });
  8116. return partialEvaluator.getOperatorList(contentStream, self.resources,
  8117. opList).then(function () {
  8118. return opList;
  8119. });
  8120. });
  8121. var annotationsPromise = pdfManager.ensure(this, 'annotations');
  8122. return Promise.all([pageListPromise, annotationsPromise]).then(
  8123. function(datas) {
  8124. var pageOpList = datas[0];
  8125. var annotations = datas[1];
  8126. if (annotations.length === 0) {
  8127. pageOpList.flush(true);
  8128. return pageOpList;
  8129. }
  8130. var annotationsReadyPromise = Annotation.appendToOperatorList(
  8131. annotations, pageOpList, pdfManager, partialEvaluator, intent);
  8132. return annotationsReadyPromise.then(function () {
  8133. pageOpList.flush(true);
  8134. return pageOpList;
  8135. });
  8136. });
  8137. },
  8138. extractTextContent: function Page_extractTextContent() {
  8139. var handler = {
  8140. on: function nullHandlerOn() {},
  8141. send: function nullHandlerSend() {}
  8142. };
  8143. var self = this;
  8144. var pdfManager = this.pdfManager;
  8145. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',
  8146. []);
  8147. var resourcesPromise = this.loadResources([
  8148. 'ExtGState',
  8149. 'XObject',
  8150. 'Font'
  8151. ]);
  8152. var dataPromises = Promise.all([contentStreamPromise,
  8153. resourcesPromise]);
  8154. return dataPromises.then(function(data) {
  8155. var contentStream = data[0];
  8156. var partialEvaluator = new PartialEvaluator(pdfManager, self.xref,
  8157. handler, self.pageIndex,
  8158. 'p' + self.pageIndex + '_',
  8159. self.idCounters,
  8160. self.fontCache);
  8161. return partialEvaluator.getTextContent(contentStream,
  8162. self.resources);
  8163. });
  8164. },
  8165. getAnnotationsData: function Page_getAnnotationsData() {
  8166. var annotations = this.annotations;
  8167. var annotationsData = [];
  8168. for (var i = 0, n = annotations.length; i < n; ++i) {
  8169. annotationsData.push(annotations[i].getData());
  8170. }
  8171. return annotationsData;
  8172. },
  8173. get annotations() {
  8174. var annotations = [];
  8175. var annotationRefs = (this.annotationRefs || []);
  8176. for (var i = 0, n = annotationRefs.length; i < n; ++i) {
  8177. var annotationRef = annotationRefs[i];
  8178. var annotation = Annotation.fromRef(this.xref, annotationRef);
  8179. if (annotation) {
  8180. annotations.push(annotation);
  8181. }
  8182. }
  8183. return shadow(this, 'annotations', annotations);
  8184. }
  8185. };
  8186. return Page;
  8187. })();
  8188. /**
  8189. * The `PDFDocument` holds all the data of the PDF file. Compared to the
  8190. * `PDFDoc`, this one doesn't have any job management code.
  8191. * Right now there exists one PDFDocument on the main thread + one object
  8192. * for each worker. If there is no worker support enabled, there are two
  8193. * `PDFDocument` objects on the main thread created.
  8194. */
  8195. var PDFDocument = (function PDFDocumentClosure() {
  8196. var FINGERPRINT_FIRST_BYTES = 1024;
  8197. var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' +
  8198. '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
  8199. function PDFDocument(pdfManager, arg, password) {
  8200. if (isStream(arg)) {
  8201. init.call(this, pdfManager, arg, password);
  8202. } else if (isArrayBuffer(arg)) {
  8203. init.call(this, pdfManager, new Stream(arg), password);
  8204. } else {
  8205. error('PDFDocument: Unknown argument type');
  8206. }
  8207. }
  8208. function init(pdfManager, stream, password) {
  8209. assert(stream.length > 0, 'stream must have data');
  8210. this.pdfManager = pdfManager;
  8211. this.stream = stream;
  8212. var xref = new XRef(this.stream, password, pdfManager);
  8213. this.xref = xref;
  8214. }
  8215. function find(stream, needle, limit, backwards) {
  8216. var pos = stream.pos;
  8217. var end = stream.end;
  8218. var strBuf = [];
  8219. if (pos + limit > end) {
  8220. limit = end - pos;
  8221. }
  8222. for (var n = 0; n < limit; ++n) {
  8223. strBuf.push(String.fromCharCode(stream.getByte()));
  8224. }
  8225. var str = strBuf.join('');
  8226. stream.pos = pos;
  8227. var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
  8228. if (index === -1) {
  8229. return false; /* not found */
  8230. }
  8231. stream.pos += index;
  8232. return true; /* found */
  8233. }
  8234. var DocumentInfoValidators = {
  8235. get entries() {
  8236. // Lazily build this since all the validation functions below are not
  8237. // defined until after this file loads.
  8238. return shadow(this, 'entries', {
  8239. Title: isString,
  8240. Author: isString,
  8241. Subject: isString,
  8242. Keywords: isString,
  8243. Creator: isString,
  8244. Producer: isString,
  8245. CreationDate: isString,
  8246. ModDate: isString,
  8247. Trapped: isName
  8248. });
  8249. }
  8250. };
  8251. PDFDocument.prototype = {
  8252. parse: function PDFDocument_parse(recoveryMode) {
  8253. this.setup(recoveryMode);
  8254. var version = this.catalog.catDict.get('Version');
  8255. if (isName(version)) {
  8256. this.pdfFormatVersion = version.name;
  8257. }
  8258. try {
  8259. // checking if AcroForm is present
  8260. this.acroForm = this.catalog.catDict.get('AcroForm');
  8261. if (this.acroForm) {
  8262. this.xfa = this.acroForm.get('XFA');
  8263. var fields = this.acroForm.get('Fields');
  8264. if ((!fields || !isArray(fields) || fields.length === 0) &&
  8265. !this.xfa) {
  8266. // no fields and no XFA -- not a form (?)
  8267. this.acroForm = null;
  8268. }
  8269. }
  8270. } catch (ex) {
  8271. info('Something wrong with AcroForm entry');
  8272. this.acroForm = null;
  8273. }
  8274. },
  8275. get linearization() {
  8276. var linearization = null;
  8277. if (this.stream.length) {
  8278. try {
  8279. linearization = Linearization.create(this.stream);
  8280. } catch (err) {
  8281. if (err instanceof MissingDataException) {
  8282. throw err;
  8283. }
  8284. info(err);
  8285. }
  8286. }
  8287. // shadow the prototype getter with a data property
  8288. return shadow(this, 'linearization', linearization);
  8289. },
  8290. get startXRef() {
  8291. var stream = this.stream;
  8292. var startXRef = 0;
  8293. var linearization = this.linearization;
  8294. if (linearization) {
  8295. // Find end of first obj.
  8296. stream.reset();
  8297. if (find(stream, 'endobj', 1024)) {
  8298. startXRef = stream.pos + 6;
  8299. }
  8300. } else {
  8301. // Find startxref by jumping backward from the end of the file.
  8302. var step = 1024;
  8303. var found = false, pos = stream.end;
  8304. while (!found && pos > 0) {
  8305. pos -= step - 'startxref'.length;
  8306. if (pos < 0) {
  8307. pos = 0;
  8308. }
  8309. stream.pos = pos;
  8310. found = find(stream, 'startxref', step, true);
  8311. }
  8312. if (found) {
  8313. stream.skip(9);
  8314. var ch;
  8315. do {
  8316. ch = stream.getByte();
  8317. } while (Lexer.isSpace(ch));
  8318. var str = '';
  8319. while (ch >= 0x20 && ch <= 0x39) { // < '9'
  8320. str += String.fromCharCode(ch);
  8321. ch = stream.getByte();
  8322. }
  8323. startXRef = parseInt(str, 10);
  8324. if (isNaN(startXRef)) {
  8325. startXRef = 0;
  8326. }
  8327. }
  8328. }
  8329. // shadow the prototype getter with a data property
  8330. return shadow(this, 'startXRef', startXRef);
  8331. },
  8332. get mainXRefEntriesOffset() {
  8333. var mainXRefEntriesOffset = 0;
  8334. var linearization = this.linearization;
  8335. if (linearization) {
  8336. mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
  8337. }
  8338. // shadow the prototype getter with a data property
  8339. return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
  8340. },
  8341. // Find the header, remove leading garbage and setup the stream
  8342. // starting from the header.
  8343. checkHeader: function PDFDocument_checkHeader() {
  8344. var stream = this.stream;
  8345. stream.reset();
  8346. if (find(stream, '%PDF-', 1024)) {
  8347. // Found the header, trim off any garbage before it.
  8348. stream.moveStart();
  8349. // Reading file format version
  8350. var MAX_VERSION_LENGTH = 12;
  8351. var version = '', ch;
  8352. while ((ch = stream.getByte()) > 0x20) { // SPACE
  8353. if (version.length >= MAX_VERSION_LENGTH) {
  8354. break;
  8355. }
  8356. version += String.fromCharCode(ch);
  8357. }
  8358. if (!this.pdfFormatVersion) {
  8359. // removing "%PDF-"-prefix
  8360. this.pdfFormatVersion = version.substring(5);
  8361. }
  8362. return;
  8363. }
  8364. // May not be a PDF file, continue anyway.
  8365. },
  8366. parseStartXRef: function PDFDocument_parseStartXRef() {
  8367. var startXRef = this.startXRef;
  8368. this.xref.setStartXRef(startXRef);
  8369. },
  8370. setup: function PDFDocument_setup(recoveryMode) {
  8371. this.xref.parse(recoveryMode);
  8372. this.catalog = new Catalog(this.pdfManager, this.xref);
  8373. },
  8374. get numPages() {
  8375. var linearization = this.linearization;
  8376. var num = linearization ? linearization.numPages : this.catalog.numPages;
  8377. // shadow the prototype getter
  8378. return shadow(this, 'numPages', num);
  8379. },
  8380. get documentInfo() {
  8381. var docInfo = {
  8382. PDFFormatVersion: this.pdfFormatVersion,
  8383. IsAcroFormPresent: !!this.acroForm,
  8384. IsXFAPresent: !!this.xfa
  8385. };
  8386. var infoDict;
  8387. try {
  8388. infoDict = this.xref.trailer.get('Info');
  8389. } catch (err) {
  8390. info('The document information dictionary is invalid.');
  8391. }
  8392. if (infoDict) {
  8393. var validEntries = DocumentInfoValidators.entries;
  8394. // Only fill the document info with valid entries from the spec.
  8395. for (var key in validEntries) {
  8396. if (infoDict.has(key)) {
  8397. var value = infoDict.get(key);
  8398. // Make sure the value conforms to the spec.
  8399. if (validEntries[key](value)) {
  8400. docInfo[key] = (typeof value !== 'string' ?
  8401. value : stringToPDFString(value));
  8402. } else {
  8403. info('Bad value in document info for "' + key + '"');
  8404. }
  8405. }
  8406. }
  8407. }
  8408. return shadow(this, 'documentInfo', docInfo);
  8409. },
  8410. get fingerprint() {
  8411. var xref = this.xref, idArray, hash, fileID = '';
  8412. if (xref.trailer.has('ID')) {
  8413. idArray = xref.trailer.get('ID');
  8414. }
  8415. if (idArray && isArray(idArray) && idArray[0] !== EMPTY_FINGERPRINT) {
  8416. hash = stringToBytes(idArray[0]);
  8417. } else {
  8418. if (this.stream.ensureRange) {
  8419. this.stream.ensureRange(0,
  8420. Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
  8421. }
  8422. hash = calculateMD5(this.stream.bytes.subarray(0,
  8423. FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  8424. }
  8425. for (var i = 0, n = hash.length; i < n; i++) {
  8426. var hex = hash[i].toString(16);
  8427. fileID += hex.length === 1 ? '0' + hex : hex;
  8428. }
  8429. return shadow(this, 'fingerprint', fileID);
  8430. },
  8431. getPage: function PDFDocument_getPage(pageIndex) {
  8432. return this.catalog.getPage(pageIndex);
  8433. },
  8434. cleanup: function PDFDocument_cleanup() {
  8435. return this.catalog.cleanup();
  8436. }
  8437. };
  8438. return PDFDocument;
  8439. })();
  8440. var Name = (function NameClosure() {
  8441. function Name(name) {
  8442. this.name = name;
  8443. }
  8444. Name.prototype = {};
  8445. var nameCache = {};
  8446. Name.get = function Name_get(name) {
  8447. var nameValue = nameCache[name];
  8448. return (nameValue ? nameValue : (nameCache[name] = new Name(name)));
  8449. };
  8450. return Name;
  8451. })();
  8452. var Cmd = (function CmdClosure() {
  8453. function Cmd(cmd) {
  8454. this.cmd = cmd;
  8455. }
  8456. Cmd.prototype = {};
  8457. var cmdCache = {};
  8458. Cmd.get = function Cmd_get(cmd) {
  8459. var cmdValue = cmdCache[cmd];
  8460. return (cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd)));
  8461. };
  8462. return Cmd;
  8463. })();
  8464. var Dict = (function DictClosure() {
  8465. var nonSerializable = function nonSerializableClosure() {
  8466. return nonSerializable; // creating closure on some variable
  8467. };
  8468. var GETALL_DICTIONARY_TYPES_WHITELIST = {
  8469. 'Background': true,
  8470. 'ExtGState': true,
  8471. 'Halftone': true,
  8472. 'Layout': true,
  8473. 'Mask': true,
  8474. 'Pagination': true,
  8475. 'Printing': true
  8476. };
  8477. function isRecursionAllowedFor(dict) {
  8478. if (!isName(dict.Type)) {
  8479. return true;
  8480. }
  8481. var dictType = dict.Type.name;
  8482. return GETALL_DICTIONARY_TYPES_WHITELIST[dictType] === true;
  8483. }
  8484. // xref is optional
  8485. function Dict(xref) {
  8486. // Map should only be used internally, use functions below to access.
  8487. this.map = Object.create(null);
  8488. this.xref = xref;
  8489. this.objId = null;
  8490. this.__nonSerializable__ = nonSerializable; // disable cloning of the Dict
  8491. }
  8492. Dict.prototype = {
  8493. assignXref: function Dict_assignXref(newXref) {
  8494. this.xref = newXref;
  8495. },
  8496. // automatically dereferences Ref objects
  8497. get: function Dict_get(key1, key2, key3) {
  8498. var value;
  8499. var xref = this.xref;
  8500. if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
  8501. typeof key2 === 'undefined') {
  8502. return xref ? xref.fetchIfRef(value) : value;
  8503. }
  8504. if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
  8505. typeof key3 === 'undefined') {
  8506. return xref ? xref.fetchIfRef(value) : value;
  8507. }
  8508. value = this.map[key3] || null;
  8509. return xref ? xref.fetchIfRef(value) : value;
  8510. },
  8511. // Same as get(), but returns a promise and uses fetchIfRefAsync().
  8512. getAsync: function Dict_getAsync(key1, key2, key3) {
  8513. var value;
  8514. var xref = this.xref;
  8515. if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
  8516. typeof key2 === 'undefined') {
  8517. if (xref) {
  8518. return xref.fetchIfRefAsync(value);
  8519. }
  8520. return Promise.resolve(value);
  8521. }
  8522. if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
  8523. typeof key3 === 'undefined') {
  8524. if (xref) {
  8525. return xref.fetchIfRefAsync(value);
  8526. }
  8527. return Promise.resolve(value);
  8528. }
  8529. value = this.map[key3] || null;
  8530. if (xref) {
  8531. return xref.fetchIfRefAsync(value);
  8532. }
  8533. return Promise.resolve(value);
  8534. },
  8535. // no dereferencing
  8536. getRaw: function Dict_getRaw(key) {
  8537. return this.map[key];
  8538. },
  8539. // creates new map and dereferences all Refs
  8540. getAll: function Dict_getAll() {
  8541. var all = Object.create(null);
  8542. var queue = null;
  8543. var key, obj;
  8544. for (key in this.map) {
  8545. obj = this.get(key);
  8546. if (obj instanceof Dict) {
  8547. if (isRecursionAllowedFor(obj)) {
  8548. (queue || (queue = [])).push({target: all, key: key, obj: obj});
  8549. } else {
  8550. all[key] = this.getRaw(key);
  8551. }
  8552. } else {
  8553. all[key] = obj;
  8554. }
  8555. }
  8556. if (!queue) {
  8557. return all;
  8558. }
  8559. // trying to take cyclic references into the account
  8560. var processed = Object.create(null);
  8561. while (queue.length > 0) {
  8562. var item = queue.shift();
  8563. var itemObj = item.obj;
  8564. var objId = itemObj.objId;
  8565. if (objId && objId in processed) {
  8566. item.target[item.key] = processed[objId];
  8567. continue;
  8568. }
  8569. var dereferenced = Object.create(null);
  8570. for (key in itemObj.map) {
  8571. obj = itemObj.get(key);
  8572. if (obj instanceof Dict) {
  8573. if (isRecursionAllowedFor(obj)) {
  8574. queue.push({target: dereferenced, key: key, obj: obj});
  8575. } else {
  8576. dereferenced[key] = itemObj.getRaw(key);
  8577. }
  8578. } else {
  8579. dereferenced[key] = obj;
  8580. }
  8581. }
  8582. if (objId) {
  8583. processed[objId] = dereferenced;
  8584. }
  8585. item.target[item.key] = dereferenced;
  8586. }
  8587. return all;
  8588. },
  8589. getKeys: function Dict_getKeys() {
  8590. return Object.keys(this.map);
  8591. },
  8592. set: function Dict_set(key, value) {
  8593. this.map[key] = value;
  8594. },
  8595. has: function Dict_has(key) {
  8596. return key in this.map;
  8597. },
  8598. forEach: function Dict_forEach(callback) {
  8599. for (var key in this.map) {
  8600. callback(key, this.get(key));
  8601. }
  8602. }
  8603. };
  8604. Dict.empty = new Dict(null);
  8605. Dict.merge = function Dict_merge(xref, dictArray) {
  8606. var mergedDict = new Dict(xref);
  8607. for (var i = 0, ii = dictArray.length; i < ii; i++) {
  8608. var dict = dictArray[i];
  8609. if (!isDict(dict)) {
  8610. continue;
  8611. }
  8612. for (var keyName in dict.map) {
  8613. if (mergedDict.map[keyName]) {
  8614. continue;
  8615. }
  8616. mergedDict.map[keyName] = dict.map[keyName];
  8617. }
  8618. }
  8619. return mergedDict;
  8620. };
  8621. return Dict;
  8622. })();
  8623. var Ref = (function RefClosure() {
  8624. function Ref(num, gen) {
  8625. this.num = num;
  8626. this.gen = gen;
  8627. }
  8628. Ref.prototype = {
  8629. toString: function Ref_toString() {
  8630. // This function is hot, so we make the string as compact as possible.
  8631. // |this.gen| is almost always zero, so we treat that case specially.
  8632. var str = this.num + 'R';
  8633. if (this.gen !== 0) {
  8634. str += this.gen;
  8635. }
  8636. return str;
  8637. }
  8638. };
  8639. return Ref;
  8640. })();
  8641. // The reference is identified by number and generation.
  8642. // This structure stores only one instance of the reference.
  8643. var RefSet = (function RefSetClosure() {
  8644. function RefSet() {
  8645. this.dict = {};
  8646. }
  8647. RefSet.prototype = {
  8648. has: function RefSet_has(ref) {
  8649. return ref.toString() in this.dict;
  8650. },
  8651. put: function RefSet_put(ref) {
  8652. this.dict[ref.toString()] = true;
  8653. },
  8654. remove: function RefSet_remove(ref) {
  8655. delete this.dict[ref.toString()];
  8656. }
  8657. };
  8658. return RefSet;
  8659. })();
  8660. var RefSetCache = (function RefSetCacheClosure() {
  8661. function RefSetCache() {
  8662. this.dict = Object.create(null);
  8663. }
  8664. RefSetCache.prototype = {
  8665. get: function RefSetCache_get(ref) {
  8666. return this.dict[ref.toString()];
  8667. },
  8668. has: function RefSetCache_has(ref) {
  8669. return ref.toString() in this.dict;
  8670. },
  8671. put: function RefSetCache_put(ref, obj) {
  8672. this.dict[ref.toString()] = obj;
  8673. },
  8674. putAlias: function RefSetCache_putAlias(ref, aliasRef) {
  8675. this.dict[ref.toString()] = this.get(aliasRef);
  8676. },
  8677. forEach: function RefSetCache_forEach(fn, thisArg) {
  8678. for (var i in this.dict) {
  8679. fn.call(thisArg, this.dict[i]);
  8680. }
  8681. },
  8682. clear: function RefSetCache_clear() {
  8683. this.dict = Object.create(null);
  8684. }
  8685. };
  8686. return RefSetCache;
  8687. })();
  8688. var Catalog = (function CatalogClosure() {
  8689. function Catalog(pdfManager, xref) {
  8690. this.pdfManager = pdfManager;
  8691. this.xref = xref;
  8692. this.catDict = xref.getCatalogObj();
  8693. this.fontCache = new RefSetCache();
  8694. assert(isDict(this.catDict),
  8695. 'catalog object is not a dictionary');
  8696. this.pagePromises = [];
  8697. }
  8698. Catalog.prototype = {
  8699. get metadata() {
  8700. var streamRef = this.catDict.getRaw('Metadata');
  8701. if (!isRef(streamRef)) {
  8702. return shadow(this, 'metadata', null);
  8703. }
  8704. var encryptMetadata = (!this.xref.encrypt ? false :
  8705. this.xref.encrypt.encryptMetadata);
  8706. var stream = this.xref.fetch(streamRef, !encryptMetadata);
  8707. var metadata;
  8708. if (stream && isDict(stream.dict)) {
  8709. var type = stream.dict.get('Type');
  8710. var subtype = stream.dict.get('Subtype');
  8711. if (isName(type) && isName(subtype) &&
  8712. type.name === 'Metadata' && subtype.name === 'XML') {
  8713. // XXX: This should examine the charset the XML document defines,
  8714. // however since there are currently no real means to decode
  8715. // arbitrary charsets, let's just hope that the author of the PDF
  8716. // was reasonable enough to stick with the XML default charset,
  8717. // which is UTF-8.
  8718. try {
  8719. metadata = stringToUTF8String(bytesToString(stream.getBytes()));
  8720. } catch (e) {
  8721. info('Skipping invalid metadata.');
  8722. }
  8723. }
  8724. }
  8725. return shadow(this, 'metadata', metadata);
  8726. },
  8727. get toplevelPagesDict() {
  8728. var pagesObj = this.catDict.get('Pages');
  8729. assert(isDict(pagesObj), 'invalid top-level pages dictionary');
  8730. // shadow the prototype getter
  8731. return shadow(this, 'toplevelPagesDict', pagesObj);
  8732. },
  8733. get documentOutline() {
  8734. var obj = null;
  8735. try {
  8736. obj = this.readDocumentOutline();
  8737. } catch (ex) {
  8738. if (ex instanceof MissingDataException) {
  8739. throw ex;
  8740. }
  8741. warn('Unable to read document outline');
  8742. }
  8743. return shadow(this, 'documentOutline', obj);
  8744. },
  8745. readDocumentOutline: function Catalog_readDocumentOutline() {
  8746. var xref = this.xref;
  8747. var obj = this.catDict.get('Outlines');
  8748. var root = { items: [] };
  8749. if (isDict(obj)) {
  8750. obj = obj.getRaw('First');
  8751. var processed = new RefSet();
  8752. if (isRef(obj)) {
  8753. var queue = [{obj: obj, parent: root}];
  8754. // to avoid recursion keeping track of the items
  8755. // in the processed dictionary
  8756. processed.put(obj);
  8757. while (queue.length > 0) {
  8758. var i = queue.shift();
  8759. var outlineDict = xref.fetchIfRef(i.obj);
  8760. if (outlineDict === null) {
  8761. continue;
  8762. }
  8763. if (!outlineDict.has('Title')) {
  8764. error('Invalid outline item');
  8765. }
  8766. var dest = outlineDict.get('A');
  8767. if (dest) {
  8768. dest = dest.get('D');
  8769. } else if (outlineDict.has('Dest')) {
  8770. dest = outlineDict.getRaw('Dest');
  8771. if (isName(dest)) {
  8772. dest = dest.name;
  8773. }
  8774. }
  8775. var title = outlineDict.get('Title');
  8776. var outlineItem = {
  8777. dest: dest,
  8778. title: stringToPDFString(title),
  8779. color: outlineDict.get('C') || [0, 0, 0],
  8780. count: outlineDict.get('Count'),
  8781. bold: !!(outlineDict.get('F') & 2),
  8782. italic: !!(outlineDict.get('F') & 1),
  8783. items: []
  8784. };
  8785. i.parent.items.push(outlineItem);
  8786. obj = outlineDict.getRaw('First');
  8787. if (isRef(obj) && !processed.has(obj)) {
  8788. queue.push({obj: obj, parent: outlineItem});
  8789. processed.put(obj);
  8790. }
  8791. obj = outlineDict.getRaw('Next');
  8792. if (isRef(obj) && !processed.has(obj)) {
  8793. queue.push({obj: obj, parent: i.parent});
  8794. processed.put(obj);
  8795. }
  8796. }
  8797. }
  8798. }
  8799. return (root.items.length > 0 ? root.items : null);
  8800. },
  8801. get numPages() {
  8802. var obj = this.toplevelPagesDict.get('Count');
  8803. assert(
  8804. isInt(obj),
  8805. 'page count in top level pages object is not an integer'
  8806. );
  8807. // shadow the prototype getter
  8808. return shadow(this, 'num', obj);
  8809. },
  8810. get destinations() {
  8811. function fetchDestination(dest) {
  8812. return isDict(dest) ? dest.get('D') : dest;
  8813. }
  8814. var xref = this.xref;
  8815. var dests = {}, nameTreeRef, nameDictionaryRef;
  8816. var obj = this.catDict.get('Names');
  8817. if (obj && obj.has('Dests')) {
  8818. nameTreeRef = obj.getRaw('Dests');
  8819. } else if (this.catDict.has('Dests')) {
  8820. nameDictionaryRef = this.catDict.get('Dests');
  8821. }
  8822. if (nameDictionaryRef) {
  8823. // reading simple destination dictionary
  8824. obj = nameDictionaryRef;
  8825. obj.forEach(function catalogForEach(key, value) {
  8826. if (!value) {
  8827. return;
  8828. }
  8829. dests[key] = fetchDestination(value);
  8830. });
  8831. }
  8832. if (nameTreeRef) {
  8833. var nameTree = new NameTree(nameTreeRef, xref);
  8834. var names = nameTree.getAll();
  8835. for (var name in names) {
  8836. if (!names.hasOwnProperty(name)) {
  8837. continue;
  8838. }
  8839. dests[name] = fetchDestination(names[name]);
  8840. }
  8841. }
  8842. return shadow(this, 'destinations', dests);
  8843. },
  8844. getDestination: function Catalog_getDestination(destinationId) {
  8845. function fetchDestination(dest) {
  8846. return isDict(dest) ? dest.get('D') : dest;
  8847. }
  8848. var xref = this.xref;
  8849. var dest, nameTreeRef, nameDictionaryRef;
  8850. var obj = this.catDict.get('Names');
  8851. if (obj && obj.has('Dests')) {
  8852. nameTreeRef = obj.getRaw('Dests');
  8853. } else if (this.catDict.has('Dests')) {
  8854. nameDictionaryRef = this.catDict.get('Dests');
  8855. }
  8856. if (nameDictionaryRef) {
  8857. // reading simple destination dictionary
  8858. obj = nameDictionaryRef;
  8859. obj.forEach(function catalogForEach(key, value) {
  8860. if (!value) {
  8861. return;
  8862. }
  8863. if (key === destinationId) {
  8864. dest = fetchDestination(value);
  8865. }
  8866. });
  8867. }
  8868. if (nameTreeRef) {
  8869. var nameTree = new NameTree(nameTreeRef, xref);
  8870. dest = fetchDestination(nameTree.get(destinationId));
  8871. }
  8872. return dest;
  8873. },
  8874. get attachments() {
  8875. var xref = this.xref;
  8876. var attachments = null, nameTreeRef;
  8877. var obj = this.catDict.get('Names');
  8878. if (obj) {
  8879. nameTreeRef = obj.getRaw('EmbeddedFiles');
  8880. }
  8881. if (nameTreeRef) {
  8882. var nameTree = new NameTree(nameTreeRef, xref);
  8883. var names = nameTree.getAll();
  8884. for (var name in names) {
  8885. if (!names.hasOwnProperty(name)) {
  8886. continue;
  8887. }
  8888. var fs = new FileSpec(names[name], xref);
  8889. if (!attachments) {
  8890. attachments = {};
  8891. }
  8892. attachments[stringToPDFString(name)] = fs.serializable;
  8893. }
  8894. }
  8895. return shadow(this, 'attachments', attachments);
  8896. },
  8897. get javaScript() {
  8898. var xref = this.xref;
  8899. var obj = this.catDict.get('Names');
  8900. var javaScript = [];
  8901. if (obj && obj.has('JavaScript')) {
  8902. var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);
  8903. var names = nameTree.getAll();
  8904. for (var name in names) {
  8905. if (!names.hasOwnProperty(name)) {
  8906. continue;
  8907. }
  8908. // We don't really use the JavaScript right now. This code is
  8909. // defensive so we don't cause errors on document load.
  8910. var jsDict = names[name];
  8911. if (!isDict(jsDict)) {
  8912. continue;
  8913. }
  8914. var type = jsDict.get('S');
  8915. if (!isName(type) || type.name !== 'JavaScript') {
  8916. continue;
  8917. }
  8918. var js = jsDict.get('JS');
  8919. if (!isString(js) && !isStream(js)) {
  8920. continue;
  8921. }
  8922. if (isStream(js)) {
  8923. js = bytesToString(js.getBytes());
  8924. }
  8925. javaScript.push(stringToPDFString(js));
  8926. }
  8927. }
  8928. // Append OpenAction actions to javaScript array
  8929. var openactionDict = this.catDict.get('OpenAction');
  8930. if (isDict(openactionDict)) {
  8931. var objType = openactionDict.get('Type');
  8932. var actionType = openactionDict.get('S');
  8933. var action = openactionDict.get('N');
  8934. var isPrintAction = (isName(objType) && objType.name === 'Action' &&
  8935. isName(actionType) && actionType.name === 'Named' &&
  8936. isName(action) && action.name === 'Print');
  8937. if (isPrintAction) {
  8938. javaScript.push('print(true);');
  8939. }
  8940. }
  8941. return shadow(this, 'javaScript', javaScript);
  8942. },
  8943. cleanup: function Catalog_cleanup() {
  8944. var promises = [];
  8945. this.fontCache.forEach(function (promise) {
  8946. promises.push(promise);
  8947. });
  8948. return Promise.all(promises).then(function (translatedFonts) {
  8949. for (var i = 0, ii = translatedFonts.length; i < ii; i++) {
  8950. var font = translatedFonts[i].dict;
  8951. delete font.translated;
  8952. }
  8953. this.fontCache.clear();
  8954. }.bind(this));
  8955. },
  8956. getPage: function Catalog_getPage(pageIndex) {
  8957. if (!(pageIndex in this.pagePromises)) {
  8958. this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(
  8959. function (a) {
  8960. var dict = a[0];
  8961. var ref = a[1];
  8962. return new Page(this.pdfManager, this.xref, pageIndex, dict, ref,
  8963. this.fontCache);
  8964. }.bind(this)
  8965. );
  8966. }
  8967. return this.pagePromises[pageIndex];
  8968. },
  8969. getPageDict: function Catalog_getPageDict(pageIndex) {
  8970. var capability = createPromiseCapability();
  8971. var nodesToVisit = [this.catDict.getRaw('Pages')];
  8972. var currentPageIndex = 0;
  8973. var xref = this.xref;
  8974. var checkAllKids = false;
  8975. function next() {
  8976. while (nodesToVisit.length) {
  8977. var currentNode = nodesToVisit.pop();
  8978. if (isRef(currentNode)) {
  8979. xref.fetchAsync(currentNode).then(function (obj) {
  8980. if (isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids'))) {
  8981. if (pageIndex === currentPageIndex) {
  8982. capability.resolve([obj, currentNode]);
  8983. } else {
  8984. currentPageIndex++;
  8985. next();
  8986. }
  8987. return;
  8988. }
  8989. nodesToVisit.push(obj);
  8990. next();
  8991. }, capability.reject);
  8992. return;
  8993. }
  8994. // Must be a child page dictionary.
  8995. assert(
  8996. isDict(currentNode),
  8997. 'page dictionary kid reference points to wrong type of object'
  8998. );
  8999. var count = currentNode.get('Count');
  9000. // If the current node doesn't have any children, avoid getting stuck
  9001. // in an empty node further down in the tree (see issue5644.pdf).
  9002. if (count === 0) {
  9003. checkAllKids = true;
  9004. }
  9005. // Skip nodes where the page can't be.
  9006. if (currentPageIndex + count <= pageIndex) {
  9007. currentPageIndex += count;
  9008. continue;
  9009. }
  9010. var kids = currentNode.get('Kids');
  9011. assert(isArray(kids), 'page dictionary kids object is not an array');
  9012. if (!checkAllKids && count === kids.length) {
  9013. // Nodes that don't have the page have been skipped and this is the
  9014. // bottom of the tree which means the page requested must be a
  9015. // descendant of this pages node. Ideally we would just resolve the
  9016. // promise with the page ref here, but there is the case where more
  9017. // pages nodes could link to single a page (see issue 3666 pdf). To
  9018. // handle this push it back on the queue so if it is a pages node it
  9019. // will be descended into.
  9020. nodesToVisit = [kids[pageIndex - currentPageIndex]];
  9021. currentPageIndex = pageIndex;
  9022. continue;
  9023. } else {
  9024. for (var last = kids.length - 1; last >= 0; last--) {
  9025. nodesToVisit.push(kids[last]);
  9026. }
  9027. }
  9028. }
  9029. capability.reject('Page index ' + pageIndex + ' not found.');
  9030. }
  9031. next();
  9032. return capability.promise;
  9033. },
  9034. getPageIndex: function Catalog_getPageIndex(ref) {
  9035. // The page tree nodes have the count of all the leaves below them. To get
  9036. // how many pages are before we just have to walk up the tree and keep
  9037. // adding the count of siblings to the left of the node.
  9038. var xref = this.xref;
  9039. function pagesBeforeRef(kidRef) {
  9040. var total = 0;
  9041. var parentRef;
  9042. return xref.fetchAsync(kidRef).then(function (node) {
  9043. if (!node) {
  9044. return null;
  9045. }
  9046. parentRef = node.getRaw('Parent');
  9047. return node.getAsync('Parent');
  9048. }).then(function (parent) {
  9049. if (!parent) {
  9050. return null;
  9051. }
  9052. return parent.getAsync('Kids');
  9053. }).then(function (kids) {
  9054. if (!kids) {
  9055. return null;
  9056. }
  9057. var kidPromises = [];
  9058. var found = false;
  9059. for (var i = 0; i < kids.length; i++) {
  9060. var kid = kids[i];
  9061. assert(isRef(kid), 'kids must be a ref');
  9062. if (kid.num === kidRef.num) {
  9063. found = true;
  9064. break;
  9065. }
  9066. kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
  9067. if (kid.has('Count')) {
  9068. var count = kid.get('Count');
  9069. total += count;
  9070. } else { // page leaf node
  9071. total++;
  9072. }
  9073. }));
  9074. }
  9075. if (!found) {
  9076. error('kid ref not found in parents kids');
  9077. }
  9078. return Promise.all(kidPromises).then(function () {
  9079. return [total, parentRef];
  9080. });
  9081. });
  9082. }
  9083. var total = 0;
  9084. function next(ref) {
  9085. return pagesBeforeRef(ref).then(function (args) {
  9086. if (!args) {
  9087. return total;
  9088. }
  9089. var count = args[0];
  9090. var parentRef = args[1];
  9091. total += count;
  9092. return next(parentRef);
  9093. });
  9094. }
  9095. return next(ref);
  9096. }
  9097. };
  9098. return Catalog;
  9099. })();
  9100. var XRef = (function XRefClosure() {
  9101. function XRef(stream, password) {
  9102. this.stream = stream;
  9103. this.entries = [];
  9104. this.xrefstms = {};
  9105. // prepare the XRef cache
  9106. this.cache = [];
  9107. this.password = password;
  9108. this.stats = {
  9109. streamTypes: [],
  9110. fontTypes: []
  9111. };
  9112. }
  9113. XRef.prototype = {
  9114. setStartXRef: function XRef_setStartXRef(startXRef) {
  9115. // Store the starting positions of xref tables as we process them
  9116. // so we can recover from missing data errors
  9117. this.startXRefQueue = [startXRef];
  9118. },
  9119. parse: function XRef_parse(recoveryMode) {
  9120. var trailerDict;
  9121. if (!recoveryMode) {
  9122. trailerDict = this.readXRef();
  9123. } else {
  9124. warn('Indexing all PDF objects');
  9125. trailerDict = this.indexObjects();
  9126. }
  9127. trailerDict.assignXref(this);
  9128. this.trailer = trailerDict;
  9129. var encrypt = trailerDict.get('Encrypt');
  9130. if (encrypt) {
  9131. var ids = trailerDict.get('ID');
  9132. var fileId = (ids && ids.length) ? ids[0] : '';
  9133. this.encrypt = new CipherTransformFactory(encrypt, fileId,
  9134. this.password);
  9135. }
  9136. // get the root dictionary (catalog) object
  9137. if (!(this.root = trailerDict.get('Root'))) {
  9138. error('Invalid root reference');
  9139. }
  9140. },
  9141. processXRefTable: function XRef_processXRefTable(parser) {
  9142. if (!('tableState' in this)) {
  9143. // Stores state of the table as we process it so we can resume
  9144. // from middle of table in case of missing data error
  9145. this.tableState = {
  9146. entryNum: 0,
  9147. streamPos: parser.lexer.stream.pos,
  9148. parserBuf1: parser.buf1,
  9149. parserBuf2: parser.buf2
  9150. };
  9151. }
  9152. var obj = this.readXRefTable(parser);
  9153. // Sanity check
  9154. if (!isCmd(obj, 'trailer')) {
  9155. error('Invalid XRef table: could not find trailer dictionary');
  9156. }
  9157. // Read trailer dictionary, e.g.
  9158. // trailer
  9159. // << /Size 22
  9160. // /Root 20R
  9161. // /Info 10R
  9162. // /ID [ <81b14aafa313db63dbd6f981e49f94f4> ]
  9163. // >>
  9164. // The parser goes through the entire stream << ... >> and provides
  9165. // a getter interface for the key-value table
  9166. var dict = parser.getObj();
  9167. // The pdflib PDF generator can generate a nested trailer dictionary
  9168. if (!isDict(dict) && dict.dict) {
  9169. dict = dict.dict;
  9170. }
  9171. if (!isDict(dict)) {
  9172. error('Invalid XRef table: could not parse trailer dictionary');
  9173. }
  9174. delete this.tableState;
  9175. return dict;
  9176. },
  9177. readXRefTable: function XRef_readXRefTable(parser) {
  9178. // Example of cross-reference table:
  9179. // xref
  9180. // 0 1 <-- subsection header (first obj #, obj count)
  9181. // 0000000000 65535 f <-- actual object (offset, generation #, f/n)
  9182. // 23 2 <-- subsection header ... and so on ...
  9183. // 0000025518 00002 n
  9184. // 0000025635 00000 n
  9185. // trailer
  9186. // ...
  9187. var stream = parser.lexer.stream;
  9188. var tableState = this.tableState;
  9189. stream.pos = tableState.streamPos;
  9190. parser.buf1 = tableState.parserBuf1;
  9191. parser.buf2 = tableState.parserBuf2;
  9192. // Outer loop is over subsection headers
  9193. var obj;
  9194. while (true) {
  9195. if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {
  9196. if (isCmd(obj = parser.getObj(), 'trailer')) {
  9197. break;
  9198. }
  9199. tableState.firstEntryNum = obj;
  9200. tableState.entryCount = parser.getObj();
  9201. }
  9202. var first = tableState.firstEntryNum;
  9203. var count = tableState.entryCount;
  9204. if (!isInt(first) || !isInt(count)) {
  9205. error('Invalid XRef table: wrong types in subsection header');
  9206. }
  9207. // Inner loop is over objects themselves
  9208. for (var i = tableState.entryNum; i < count; i++) {
  9209. tableState.streamPos = stream.pos;
  9210. tableState.entryNum = i;
  9211. tableState.parserBuf1 = parser.buf1;
  9212. tableState.parserBuf2 = parser.buf2;
  9213. var entry = {};
  9214. entry.offset = parser.getObj();
  9215. entry.gen = parser.getObj();
  9216. var type = parser.getObj();
  9217. if (isCmd(type, 'f')) {
  9218. entry.free = true;
  9219. } else if (isCmd(type, 'n')) {
  9220. entry.uncompressed = true;
  9221. }
  9222. // Validate entry obj
  9223. if (!isInt(entry.offset) || !isInt(entry.gen) ||
  9224. !(entry.free || entry.uncompressed)) {
  9225. error('Invalid entry in XRef subsection: ' + first + ', ' + count);
  9226. }
  9227. if (!this.entries[i + first]) {
  9228. this.entries[i + first] = entry;
  9229. }
  9230. }
  9231. tableState.entryNum = 0;
  9232. tableState.streamPos = stream.pos;
  9233. tableState.parserBuf1 = parser.buf1;
  9234. tableState.parserBuf2 = parser.buf2;
  9235. delete tableState.firstEntryNum;
  9236. delete tableState.entryCount;
  9237. }
  9238. // Per issue 3248: hp scanners generate bad XRef
  9239. if (first === 1 && this.entries[1] && this.entries[1].free) {
  9240. // shifting the entries
  9241. this.entries.shift();
  9242. }
  9243. // Sanity check: as per spec, first object must be free
  9244. if (this.entries[0] && !this.entries[0].free) {
  9245. error('Invalid XRef table: unexpected first object');
  9246. }
  9247. return obj;
  9248. },
  9249. processXRefStream: function XRef_processXRefStream(stream) {
  9250. if (!('streamState' in this)) {
  9251. // Stores state of the stream as we process it so we can resume
  9252. // from middle of stream in case of missing data error
  9253. var streamParameters = stream.dict;
  9254. var byteWidths = streamParameters.get('W');
  9255. var range = streamParameters.get('Index');
  9256. if (!range) {
  9257. range = [0, streamParameters.get('Size')];
  9258. }
  9259. this.streamState = {
  9260. entryRanges: range,
  9261. byteWidths: byteWidths,
  9262. entryNum: 0,
  9263. streamPos: stream.pos
  9264. };
  9265. }
  9266. this.readXRefStream(stream);
  9267. delete this.streamState;
  9268. return stream.dict;
  9269. },
  9270. readXRefStream: function XRef_readXRefStream(stream) {
  9271. var i, j;
  9272. var streamState = this.streamState;
  9273. stream.pos = streamState.streamPos;
  9274. var byteWidths = streamState.byteWidths;
  9275. var typeFieldWidth = byteWidths[0];
  9276. var offsetFieldWidth = byteWidths[1];
  9277. var generationFieldWidth = byteWidths[2];
  9278. var entryRanges = streamState.entryRanges;
  9279. while (entryRanges.length > 0) {
  9280. var first = entryRanges[0];
  9281. var n = entryRanges[1];
  9282. if (!isInt(first) || !isInt(n)) {
  9283. error('Invalid XRef range fields: ' + first + ', ' + n);
  9284. }
  9285. if (!isInt(typeFieldWidth) || !isInt(offsetFieldWidth) ||
  9286. !isInt(generationFieldWidth)) {
  9287. error('Invalid XRef entry fields length: ' + first + ', ' + n);
  9288. }
  9289. for (i = streamState.entryNum; i < n; ++i) {
  9290. streamState.entryNum = i;
  9291. streamState.streamPos = stream.pos;
  9292. var type = 0, offset = 0, generation = 0;
  9293. for (j = 0; j < typeFieldWidth; ++j) {
  9294. type = (type << 8) | stream.getByte();
  9295. }
  9296. // if type field is absent, its default value is 1
  9297. if (typeFieldWidth === 0) {
  9298. type = 1;
  9299. }
  9300. for (j = 0; j < offsetFieldWidth; ++j) {
  9301. offset = (offset << 8) | stream.getByte();
  9302. }
  9303. for (j = 0; j < generationFieldWidth; ++j) {
  9304. generation = (generation << 8) | stream.getByte();
  9305. }
  9306. var entry = {};
  9307. entry.offset = offset;
  9308. entry.gen = generation;
  9309. switch (type) {
  9310. case 0:
  9311. entry.free = true;
  9312. break;
  9313. case 1:
  9314. entry.uncompressed = true;
  9315. break;
  9316. case 2:
  9317. break;
  9318. default:
  9319. error('Invalid XRef entry type: ' + type);
  9320. }
  9321. if (!this.entries[first + i]) {
  9322. this.entries[first + i] = entry;
  9323. }
  9324. }
  9325. streamState.entryNum = 0;
  9326. streamState.streamPos = stream.pos;
  9327. entryRanges.splice(0, 2);
  9328. }
  9329. },
  9330. indexObjects: function XRef_indexObjects() {
  9331. // Simple scan through the PDF content to find objects,
  9332. // trailers and XRef streams.
  9333. function readToken(data, offset) {
  9334. var token = '', ch = data[offset];
  9335. while (ch !== 13 && ch !== 10) {
  9336. if (++offset >= data.length) {
  9337. break;
  9338. }
  9339. token += String.fromCharCode(ch);
  9340. ch = data[offset];
  9341. }
  9342. return token;
  9343. }
  9344. function skipUntil(data, offset, what) {
  9345. var length = what.length, dataLength = data.length;
  9346. var skipped = 0;
  9347. // finding byte sequence
  9348. while (offset < dataLength) {
  9349. var i = 0;
  9350. while (i < length && data[offset + i] === what[i]) {
  9351. ++i;
  9352. }
  9353. if (i >= length) {
  9354. break; // sequence found
  9355. }
  9356. offset++;
  9357. skipped++;
  9358. }
  9359. return skipped;
  9360. }
  9361. var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
  9362. var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114,
  9363. 101, 102]);
  9364. var endobjBytes = new Uint8Array([101, 110, 100, 111, 98, 106]);
  9365. var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
  9366. var stream = this.stream;
  9367. stream.pos = 0;
  9368. var buffer = stream.getBytes();
  9369. var position = stream.start, length = buffer.length;
  9370. var trailers = [], xrefStms = [];
  9371. while (position < length) {
  9372. var ch = buffer[position];
  9373. if (ch === 32 || ch === 9 || ch === 13 || ch === 10) {
  9374. ++position;
  9375. continue;
  9376. }
  9377. if (ch === 37) { // %-comment
  9378. do {
  9379. ++position;
  9380. if (position >= length) {
  9381. break;
  9382. }
  9383. ch = buffer[position];
  9384. } while (ch !== 13 && ch !== 10);
  9385. continue;
  9386. }
  9387. var token = readToken(buffer, position);
  9388. var m;
  9389. if (token === 'xref') {
  9390. position += skipUntil(buffer, position, trailerBytes);
  9391. trailers.push(position);
  9392. position += skipUntil(buffer, position, startxrefBytes);
  9393. } else if ((m = /^(\d+)\s+(\d+)\s+obj\b/.exec(token))) {
  9394. if (typeof this.entries[m[1]] === 'undefined') {
  9395. this.entries[m[1]] = {
  9396. offset: position - stream.start,
  9397. gen: m[2] | 0,
  9398. uncompressed: true
  9399. };
  9400. }
  9401. var contentLength = skipUntil(buffer, position, endobjBytes) + 7;
  9402. var content = buffer.subarray(position, position + contentLength);
  9403. // checking XRef stream suspect
  9404. // (it shall have '/XRef' and next char is not a letter)
  9405. var xrefTagOffset = skipUntil(content, 0, xrefBytes);
  9406. if (xrefTagOffset < contentLength &&
  9407. content[xrefTagOffset + 5] < 64) {
  9408. xrefStms.push(position - stream.start);
  9409. this.xrefstms[position - stream.start] = 1; // Avoid recursion
  9410. }
  9411. position += contentLength;
  9412. } else {
  9413. position += token.length + 1;
  9414. }
  9415. }
  9416. // reading XRef streams
  9417. var i, ii;
  9418. for (i = 0, ii = xrefStms.length; i < ii; ++i) {
  9419. this.startXRefQueue.push(xrefStms[i]);
  9420. this.readXRef(/* recoveryMode */ true);
  9421. }
  9422. // finding main trailer
  9423. var dict;
  9424. for (i = 0, ii = trailers.length; i < ii; ++i) {
  9425. stream.pos = trailers[i];
  9426. var parser = new Parser(new Lexer(stream), true, this);
  9427. var obj = parser.getObj();
  9428. if (!isCmd(obj, 'trailer')) {
  9429. continue;
  9430. }
  9431. // read the trailer dictionary
  9432. if (!isDict(dict = parser.getObj())) {
  9433. continue;
  9434. }
  9435. // taking the first one with 'ID'
  9436. if (dict.has('ID')) {
  9437. return dict;
  9438. }
  9439. }
  9440. // no tailer with 'ID', taking last one (if exists)
  9441. if (dict) {
  9442. return dict;
  9443. }
  9444. // nothing helps
  9445. // calling error() would reject worker with an UnknownErrorException.
  9446. throw new InvalidPDFException('Invalid PDF structure');
  9447. },
  9448. readXRef: function XRef_readXRef(recoveryMode) {
  9449. var stream = this.stream;
  9450. try {
  9451. while (this.startXRefQueue.length) {
  9452. var startXRef = this.startXRefQueue[0];
  9453. stream.pos = startXRef + stream.start;
  9454. var parser = new Parser(new Lexer(stream), true, this);
  9455. var obj = parser.getObj();
  9456. var dict;
  9457. // Get dictionary
  9458. if (isCmd(obj, 'xref')) {
  9459. // Parse end-of-file XRef
  9460. dict = this.processXRefTable(parser);
  9461. if (!this.topDict) {
  9462. this.topDict = dict;
  9463. }
  9464. // Recursively get other XRefs 'XRefStm', if any
  9465. obj = dict.get('XRefStm');
  9466. if (isInt(obj)) {
  9467. var pos = obj;
  9468. // ignore previously loaded xref streams
  9469. // (possible infinite recursion)
  9470. if (!(pos in this.xrefstms)) {
  9471. this.xrefstms[pos] = 1;
  9472. this.startXRefQueue.push(pos);
  9473. }
  9474. }
  9475. } else if (isInt(obj)) {
  9476. // Parse in-stream XRef
  9477. if (!isInt(parser.getObj()) ||
  9478. !isCmd(parser.getObj(), 'obj') ||
  9479. !isStream(obj = parser.getObj())) {
  9480. error('Invalid XRef stream');
  9481. }
  9482. dict = this.processXRefStream(obj);
  9483. if (!this.topDict) {
  9484. this.topDict = dict;
  9485. }
  9486. if (!dict) {
  9487. error('Failed to read XRef stream');
  9488. }
  9489. } else {
  9490. error('Invalid XRef stream header');
  9491. }
  9492. // Recursively get previous dictionary, if any
  9493. obj = dict.get('Prev');
  9494. if (isInt(obj)) {
  9495. this.startXRefQueue.push(obj);
  9496. } else if (isRef(obj)) {
  9497. // The spec says Prev must not be a reference, i.e. "/Prev NNN"
  9498. // This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R"
  9499. this.startXRefQueue.push(obj.num);
  9500. }
  9501. this.startXRefQueue.shift();
  9502. }
  9503. return this.topDict;
  9504. } catch (e) {
  9505. if (e instanceof MissingDataException) {
  9506. throw e;
  9507. }
  9508. info('(while reading XRef): ' + e);
  9509. }
  9510. if (recoveryMode) {
  9511. return;
  9512. }
  9513. throw new XRefParseException();
  9514. },
  9515. getEntry: function XRef_getEntry(i) {
  9516. var xrefEntry = this.entries[i];
  9517. if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
  9518. return xrefEntry;
  9519. }
  9520. return null;
  9521. },
  9522. fetchIfRef: function XRef_fetchIfRef(obj) {
  9523. if (!isRef(obj)) {
  9524. return obj;
  9525. }
  9526. return this.fetch(obj);
  9527. },
  9528. fetch: function XRef_fetch(ref, suppressEncryption) {
  9529. assert(isRef(ref), 'ref object is not a reference');
  9530. var num = ref.num;
  9531. if (num in this.cache) {
  9532. var cacheEntry = this.cache[num];
  9533. return cacheEntry;
  9534. }
  9535. var xrefEntry = this.getEntry(num);
  9536. // the referenced entry can be free
  9537. if (xrefEntry === null) {
  9538. return (this.cache[num] = null);
  9539. }
  9540. if (xrefEntry.uncompressed) {
  9541. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  9542. } else {
  9543. xrefEntry = this.fetchCompressed(xrefEntry, suppressEncryption);
  9544. }
  9545. if (isDict(xrefEntry)){
  9546. xrefEntry.objId = ref.toString();
  9547. } else if (isStream(xrefEntry)) {
  9548. xrefEntry.dict.objId = ref.toString();
  9549. }
  9550. return xrefEntry;
  9551. },
  9552. fetchUncompressed: function XRef_fetchUncompressed(ref, xrefEntry,
  9553. suppressEncryption) {
  9554. var gen = ref.gen;
  9555. var num = ref.num;
  9556. if (xrefEntry.gen !== gen) {
  9557. error('inconsistent generation in XRef');
  9558. }
  9559. var stream = this.stream.makeSubStream(xrefEntry.offset +
  9560. this.stream.start);
  9561. var parser = new Parser(new Lexer(stream), true, this);
  9562. var obj1 = parser.getObj();
  9563. var obj2 = parser.getObj();
  9564. var obj3 = parser.getObj();
  9565. if (!isInt(obj1) || parseInt(obj1, 10) !== num ||
  9566. !isInt(obj2) || parseInt(obj2, 10) !== gen ||
  9567. !isCmd(obj3)) {
  9568. error('bad XRef entry');
  9569. }
  9570. if (!isCmd(obj3, 'obj')) {
  9571. // some bad PDFs use "obj1234" and really mean 1234
  9572. if (obj3.cmd.indexOf('obj') === 0) {
  9573. num = parseInt(obj3.cmd.substring(3), 10);
  9574. if (!isNaN(num)) {
  9575. return num;
  9576. }
  9577. }
  9578. error('bad XRef entry');
  9579. }
  9580. if (this.encrypt && !suppressEncryption) {
  9581. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  9582. } else {
  9583. xrefEntry = parser.getObj();
  9584. }
  9585. if (!isStream(xrefEntry)) {
  9586. this.cache[num] = xrefEntry;
  9587. }
  9588. return xrefEntry;
  9589. },
  9590. fetchCompressed: function XRef_fetchCompressed(xrefEntry,
  9591. suppressEncryption) {
  9592. var tableOffset = xrefEntry.offset;
  9593. var stream = this.fetch(new Ref(tableOffset, 0));
  9594. if (!isStream(stream)) {
  9595. error('bad ObjStm stream');
  9596. }
  9597. var first = stream.dict.get('First');
  9598. var n = stream.dict.get('N');
  9599. if (!isInt(first) || !isInt(n)) {
  9600. error('invalid first and n parameters for ObjStm stream');
  9601. }
  9602. var parser = new Parser(new Lexer(stream), false, this);
  9603. parser.allowStreams = true;
  9604. var i, entries = [], num, nums = [];
  9605. // read the object numbers to populate cache
  9606. for (i = 0; i < n; ++i) {
  9607. num = parser.getObj();
  9608. if (!isInt(num)) {
  9609. error('invalid object number in the ObjStm stream: ' + num);
  9610. }
  9611. nums.push(num);
  9612. var offset = parser.getObj();
  9613. if (!isInt(offset)) {
  9614. error('invalid object offset in the ObjStm stream: ' + offset);
  9615. }
  9616. }
  9617. // read stream objects for cache
  9618. for (i = 0; i < n; ++i) {
  9619. entries.push(parser.getObj());
  9620. num = nums[i];
  9621. var entry = this.entries[num];
  9622. if (entry && entry.offset === tableOffset && entry.gen === i) {
  9623. this.cache[num] = entries[i];
  9624. }
  9625. }
  9626. xrefEntry = entries[xrefEntry.gen];
  9627. if (xrefEntry === undefined) {
  9628. error('bad XRef entry for compressed object');
  9629. }
  9630. return xrefEntry;
  9631. },
  9632. fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) {
  9633. if (!isRef(obj)) {
  9634. return Promise.resolve(obj);
  9635. }
  9636. return this.fetchAsync(obj);
  9637. },
  9638. fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
  9639. var streamManager = this.stream.manager;
  9640. var xref = this;
  9641. return new Promise(function tryFetch(resolve, reject) {
  9642. try {
  9643. resolve(xref.fetch(ref, suppressEncryption));
  9644. } catch (e) {
  9645. if (e instanceof MissingDataException) {
  9646. streamManager.requestRange(e.begin, e.end, function () {
  9647. tryFetch(resolve, reject);
  9648. });
  9649. return;
  9650. }
  9651. reject(e);
  9652. }
  9653. });
  9654. },
  9655. getCatalogObj: function XRef_getCatalogObj() {
  9656. return this.root;
  9657. }
  9658. };
  9659. return XRef;
  9660. })();
  9661. /**
  9662. * A NameTree is like a Dict but has some advantageous properties, see the
  9663. * spec (7.9.6) for more details.
  9664. * TODO: implement all the Dict functions and make this more efficent.
  9665. */
  9666. var NameTree = (function NameTreeClosure() {
  9667. function NameTree(root, xref) {
  9668. this.root = root;
  9669. this.xref = xref;
  9670. }
  9671. NameTree.prototype = {
  9672. getAll: function NameTree_getAll() {
  9673. var dict = {};
  9674. if (!this.root) {
  9675. return dict;
  9676. }
  9677. var xref = this.xref;
  9678. // reading name tree
  9679. var processed = new RefSet();
  9680. processed.put(this.root);
  9681. var queue = [this.root];
  9682. while (queue.length > 0) {
  9683. var i, n;
  9684. var obj = xref.fetchIfRef(queue.shift());
  9685. if (!isDict(obj)) {
  9686. continue;
  9687. }
  9688. if (obj.has('Kids')) {
  9689. var kids = obj.get('Kids');
  9690. for (i = 0, n = kids.length; i < n; i++) {
  9691. var kid = kids[i];
  9692. if (processed.has(kid)) {
  9693. error('invalid destinations');
  9694. }
  9695. queue.push(kid);
  9696. processed.put(kid);
  9697. }
  9698. continue;
  9699. }
  9700. var names = obj.get('Names');
  9701. if (names) {
  9702. for (i = 0, n = names.length; i < n; i += 2) {
  9703. dict[names[i]] = xref.fetchIfRef(names[i + 1]);
  9704. }
  9705. }
  9706. }
  9707. return dict;
  9708. },
  9709. get: function NameTree_get(destinationId) {
  9710. if (!this.root) {
  9711. return null;
  9712. }
  9713. var xref = this.xref;
  9714. var kidsOrNames = xref.fetchIfRef(this.root);
  9715. var loopCount = 0;
  9716. var MAX_NAMES_LEVELS = 10;
  9717. var l, r, m;
  9718. // Perform a binary search to quickly find the entry that
  9719. // contains the named destination we are looking for.
  9720. while (kidsOrNames.has('Kids')) {
  9721. loopCount++;
  9722. if (loopCount > MAX_NAMES_LEVELS) {
  9723. warn('Search depth limit for named destionations has been reached.');
  9724. return null;
  9725. }
  9726. var kids = kidsOrNames.get('Kids');
  9727. if (!isArray(kids)) {
  9728. return null;
  9729. }
  9730. l = 0;
  9731. r = kids.length - 1;
  9732. while (l <= r) {
  9733. m = (l + r) >> 1;
  9734. var kid = xref.fetchIfRef(kids[m]);
  9735. var limits = kid.get('Limits');
  9736. if (destinationId < limits[0]) {
  9737. r = m - 1;
  9738. } else if (destinationId > limits[1]) {
  9739. l = m + 1;
  9740. } else {
  9741. kidsOrNames = xref.fetchIfRef(kids[m]);
  9742. break;
  9743. }
  9744. }
  9745. if (l > r) {
  9746. return null;
  9747. }
  9748. }
  9749. // If we get here, then we have found the right entry. Now
  9750. // go through the named destinations in the Named dictionary
  9751. // until we find the exact destination we're looking for.
  9752. var names = kidsOrNames.get('Names');
  9753. if (isArray(names)) {
  9754. // Perform a binary search to reduce the lookup time.
  9755. l = 0;
  9756. r = names.length - 2;
  9757. while (l <= r) {
  9758. // Check only even indices (0, 2, 4, ...) because the
  9759. // odd indices contain the actual D array.
  9760. m = (l + r) & ~1;
  9761. if (destinationId < names[m]) {
  9762. r = m - 2;
  9763. } else if (destinationId > names[m]) {
  9764. l = m + 2;
  9765. } else {
  9766. return xref.fetchIfRef(names[m + 1]);
  9767. }
  9768. }
  9769. }
  9770. return null;
  9771. }
  9772. };
  9773. return NameTree;
  9774. })();
  9775. /**
  9776. * "A PDF file can refer to the contents of another file by using a File
  9777. * Specification (PDF 1.1)", see the spec (7.11) for more details.
  9778. * NOTE: Only embedded files are supported (as part of the attachments support)
  9779. * TODO: support the 'URL' file system (with caching if !/V), portable
  9780. * collections attributes and related files (/RF)
  9781. */
  9782. var FileSpec = (function FileSpecClosure() {
  9783. function FileSpec(root, xref) {
  9784. if (!root || !isDict(root)) {
  9785. return;
  9786. }
  9787. this.xref = xref;
  9788. this.root = root;
  9789. if (root.has('FS')) {
  9790. this.fs = root.get('FS');
  9791. }
  9792. this.description = root.has('Desc') ?
  9793. stringToPDFString(root.get('Desc')) :
  9794. '';
  9795. if (root.has('RF')) {
  9796. warn('Related file specifications are not supported');
  9797. }
  9798. this.contentAvailable = true;
  9799. if (!root.has('EF')) {
  9800. this.contentAvailable = false;
  9801. warn('Non-embedded file specifications are not supported');
  9802. }
  9803. }
  9804. function pickPlatformItem(dict) {
  9805. // Look for the filename in this order:
  9806. // UF, F, Unix, Mac, DOS
  9807. if (dict.has('UF')) {
  9808. return dict.get('UF');
  9809. } else if (dict.has('F')) {
  9810. return dict.get('F');
  9811. } else if (dict.has('Unix')) {
  9812. return dict.get('Unix');
  9813. } else if (dict.has('Mac')) {
  9814. return dict.get('Mac');
  9815. } else if (dict.has('DOS')) {
  9816. return dict.get('DOS');
  9817. } else {
  9818. return null;
  9819. }
  9820. }
  9821. FileSpec.prototype = {
  9822. get filename() {
  9823. if (!this._filename && this.root) {
  9824. var filename = pickPlatformItem(this.root) || 'unnamed';
  9825. this._filename = stringToPDFString(filename).
  9826. replace(/\\\\/g, '\\').
  9827. replace(/\\\//g, '/').
  9828. replace(/\\/g, '/');
  9829. }
  9830. return this._filename;
  9831. },
  9832. get content() {
  9833. if (!this.contentAvailable) {
  9834. return null;
  9835. }
  9836. if (!this.contentRef && this.root) {
  9837. this.contentRef = pickPlatformItem(this.root.get('EF'));
  9838. }
  9839. var content = null;
  9840. if (this.contentRef) {
  9841. var xref = this.xref;
  9842. var fileObj = xref.fetchIfRef(this.contentRef);
  9843. if (fileObj && isStream(fileObj)) {
  9844. content = fileObj.getBytes();
  9845. } else {
  9846. warn('Embedded file specification points to non-existing/invalid ' +
  9847. 'content');
  9848. }
  9849. } else {
  9850. warn('Embedded file specification does not have a content');
  9851. }
  9852. return content;
  9853. },
  9854. get serializable() {
  9855. return {
  9856. filename: this.filename,
  9857. content: this.content
  9858. };
  9859. }
  9860. };
  9861. return FileSpec;
  9862. })();
  9863. /**
  9864. * A helper for loading missing data in object graphs. It traverses the graph
  9865. * depth first and queues up any objects that have missing data. Once it has
  9866. * has traversed as many objects that are available it attempts to bundle the
  9867. * missing data requests and then resume from the nodes that weren't ready.
  9868. *
  9869. * NOTE: It provides protection from circular references by keeping track of
  9870. * of loaded references. However, you must be careful not to load any graphs
  9871. * that have references to the catalog or other pages since that will cause the
  9872. * entire PDF document object graph to be traversed.
  9873. */
  9874. var ObjectLoader = (function() {
  9875. function mayHaveChildren(value) {
  9876. return isRef(value) || isDict(value) || isArray(value) || isStream(value);
  9877. }
  9878. function addChildren(node, nodesToVisit) {
  9879. var value;
  9880. if (isDict(node) || isStream(node)) {
  9881. var map;
  9882. if (isDict(node)) {
  9883. map = node.map;
  9884. } else {
  9885. map = node.dict.map;
  9886. }
  9887. for (var key in map) {
  9888. value = map[key];
  9889. if (mayHaveChildren(value)) {
  9890. nodesToVisit.push(value);
  9891. }
  9892. }
  9893. } else if (isArray(node)) {
  9894. for (var i = 0, ii = node.length; i < ii; i++) {
  9895. value = node[i];
  9896. if (mayHaveChildren(value)) {
  9897. nodesToVisit.push(value);
  9898. }
  9899. }
  9900. }
  9901. }
  9902. function ObjectLoader(obj, keys, xref) {
  9903. this.obj = obj;
  9904. this.keys = keys;
  9905. this.xref = xref;
  9906. this.refSet = null;
  9907. }
  9908. ObjectLoader.prototype = {
  9909. load: function ObjectLoader_load() {
  9910. var keys = this.keys;
  9911. this.capability = createPromiseCapability();
  9912. // Don't walk the graph if all the data is already loaded.
  9913. if (!(this.xref.stream instanceof ChunkedStream) ||
  9914. this.xref.stream.getMissingChunks().length === 0) {
  9915. this.capability.resolve();
  9916. return this.capability.promise;
  9917. }
  9918. this.refSet = new RefSet();
  9919. // Setup the initial nodes to visit.
  9920. var nodesToVisit = [];
  9921. for (var i = 0; i < keys.length; i++) {
  9922. nodesToVisit.push(this.obj[keys[i]]);
  9923. }
  9924. this.walk(nodesToVisit);
  9925. return this.capability.promise;
  9926. },
  9927. walk: function ObjectLoader_walk(nodesToVisit) {
  9928. var nodesToRevisit = [];
  9929. var pendingRequests = [];
  9930. // DFS walk of the object graph.
  9931. while (nodesToVisit.length) {
  9932. var currentNode = nodesToVisit.pop();
  9933. // Only references or chunked streams can cause missing data exceptions.
  9934. if (isRef(currentNode)) {
  9935. // Skip nodes that have already been visited.
  9936. if (this.refSet.has(currentNode)) {
  9937. continue;
  9938. }
  9939. try {
  9940. var ref = currentNode;
  9941. this.refSet.put(ref);
  9942. currentNode = this.xref.fetch(currentNode);
  9943. } catch (e) {
  9944. if (!(e instanceof MissingDataException)) {
  9945. throw e;
  9946. }
  9947. nodesToRevisit.push(currentNode);
  9948. pendingRequests.push({ begin: e.begin, end: e.end });
  9949. }
  9950. }
  9951. if (currentNode && currentNode.getBaseStreams) {
  9952. var baseStreams = currentNode.getBaseStreams();
  9953. var foundMissingData = false;
  9954. for (var i = 0; i < baseStreams.length; i++) {
  9955. var stream = baseStreams[i];
  9956. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  9957. foundMissingData = true;
  9958. pendingRequests.push({
  9959. begin: stream.start,
  9960. end: stream.end
  9961. });
  9962. }
  9963. }
  9964. if (foundMissingData) {
  9965. nodesToRevisit.push(currentNode);
  9966. }
  9967. }
  9968. addChildren(currentNode, nodesToVisit);
  9969. }
  9970. if (pendingRequests.length) {
  9971. this.xref.stream.manager.requestRanges(pendingRequests,
  9972. function pendingRequestCallback() {
  9973. nodesToVisit = nodesToRevisit;
  9974. for (var i = 0; i < nodesToRevisit.length; i++) {
  9975. var node = nodesToRevisit[i];
  9976. // Remove any reference nodes from the currrent refset so they
  9977. // aren't skipped when we revist them.
  9978. if (isRef(node)) {
  9979. this.refSet.remove(node);
  9980. }
  9981. }
  9982. this.walk(nodesToVisit);
  9983. }.bind(this));
  9984. return;
  9985. }
  9986. // Everything is loaded.
  9987. this.refSet = null;
  9988. this.capability.resolve();
  9989. }
  9990. };
  9991. return ObjectLoader;
  9992. })();
  9993. var ISOAdobeCharset = [
  9994. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar',
  9995. 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright',
  9996. 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero',
  9997. 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
  9998. 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question',
  9999. 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  10000. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  10001. 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
  10002. 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  10003. 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  10004. 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
  10005. 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  10006. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  10007. 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
  10008. 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase',
  10009. 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
  10010. 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde',
  10011. 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla',
  10012. 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine',
  10013. 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash',
  10014. 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu',
  10015. 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter',
  10016. 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior',
  10017. 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright',
  10018. 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde',
  10019. 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute',
  10020. 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex',
  10021. 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex',
  10022. 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute',
  10023. 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla',
  10024. 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex',
  10025. 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis',
  10026. 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis',
  10027. 'ugrave', 'yacute', 'ydieresis', 'zcaron'
  10028. ];
  10029. var ExpertCharset = [
  10030. '.notdef', 'space', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle',
  10031. 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
  10032. 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
  10033. 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
  10034. 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
  10035. 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle',
  10036. 'colon', 'semicolon', 'commasuperior', 'threequartersemdash',
  10037. 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior',
  10038. 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  10039. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  10040. 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
  10041. 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
  10042. 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
  10043. 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
  10044. 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
  10045. 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
  10046. 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle',
  10047. 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall',
  10048. 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall',
  10049. 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall',
  10050. 'Cedillasmall', 'onequarter', 'onehalf', 'threequarters',
  10051. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
  10052. 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
  10053. 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  10054. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  10055. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
  10056. 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
  10057. 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
  10058. 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall',
  10059. 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall',
  10060. 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
  10061. 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  10062. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
  10063. 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
  10064. 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  10065. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
  10066. 'Ydieresissmall'
  10067. ];
  10068. var ExpertSubsetCharset = [
  10069. '.notdef', 'space', 'dollaroldstyle', 'dollarsuperior',
  10070. 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  10071. 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction',
  10072. 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle',
  10073. 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle',
  10074. 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior',
  10075. 'threequartersemdash', 'periodsuperior', 'asuperior', 'bsuperior',
  10076. 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  10077. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  10078. 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
  10079. 'parenrightinferior', 'hyphensuperior', 'colonmonetary', 'onefitted',
  10080. 'rupiah', 'centoldstyle', 'figuredash', 'hypheninferior', 'onequarter',
  10081. 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
  10082. 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
  10083. 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  10084. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  10085. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
  10086. 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
  10087. 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
  10088. 'periodinferior', 'commainferior'
  10089. ];
  10090. var DEFAULT_ICON_SIZE = 22; // px
  10091. var SUPPORTED_TYPES = ['Link', 'Text', 'Widget'];
  10092. var Annotation = (function AnnotationClosure() {
  10093. // 12.5.5: Algorithm: Appearance streams
  10094. function getTransformMatrix(rect, bbox, matrix) {
  10095. var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);
  10096. var minX = bounds[0];
  10097. var minY = bounds[1];
  10098. var maxX = bounds[2];
  10099. var maxY = bounds[3];
  10100. if (minX === maxX || minY === maxY) {
  10101. // From real-life file, bbox was [0, 0, 0, 0]. In this case,
  10102. // just apply the transform for rect
  10103. return [1, 0, 0, 1, rect[0], rect[1]];
  10104. }
  10105. var xRatio = (rect[2] - rect[0]) / (maxX - minX);
  10106. var yRatio = (rect[3] - rect[1]) / (maxY - minY);
  10107. return [
  10108. xRatio,
  10109. 0,
  10110. 0,
  10111. yRatio,
  10112. rect[0] - minX * xRatio,
  10113. rect[1] - minY * yRatio
  10114. ];
  10115. }
  10116. function getDefaultAppearance(dict) {
  10117. var appearanceState = dict.get('AP');
  10118. if (!isDict(appearanceState)) {
  10119. return;
  10120. }
  10121. var appearance;
  10122. var appearances = appearanceState.get('N');
  10123. if (isDict(appearances)) {
  10124. var as = dict.get('AS');
  10125. if (as && appearances.has(as.name)) {
  10126. appearance = appearances.get(as.name);
  10127. }
  10128. } else {
  10129. appearance = appearances;
  10130. }
  10131. return appearance;
  10132. }
  10133. function Annotation(params) {
  10134. var dict = params.dict;
  10135. var data = this.data = {};
  10136. data.subtype = dict.get('Subtype').name;
  10137. var rect = dict.get('Rect') || [0, 0, 0, 0];
  10138. data.rect = Util.normalizeRect(rect);
  10139. data.annotationFlags = dict.get('F');
  10140. var color = dict.get('C');
  10141. if (!color) {
  10142. // The PDF spec does not mention how a missing color array is interpreted.
  10143. // Adobe Reader seems to default to black in this case.
  10144. data.color = [0, 0, 0];
  10145. } else if (isArray(color)) {
  10146. switch (color.length) {
  10147. case 0:
  10148. // Empty array denotes transparent border.
  10149. data.color = null;
  10150. break;
  10151. case 1:
  10152. // TODO: implement DeviceGray
  10153. break;
  10154. case 3:
  10155. data.color = color;
  10156. break;
  10157. case 4:
  10158. // TODO: implement DeviceCMYK
  10159. break;
  10160. }
  10161. }
  10162. this.borderStyle = data.borderStyle = new AnnotationBorderStyle();
  10163. this.setBorderStyle(dict);
  10164. this.appearance = getDefaultAppearance(dict);
  10165. data.hasAppearance = !!this.appearance;
  10166. data.id = params.ref.num;
  10167. }
  10168. Annotation.prototype = {
  10169. /**
  10170. * Set the border style (as AnnotationBorderStyle object).
  10171. *
  10172. * @public
  10173. * @memberof Annotation
  10174. * @param {Dict} borderStyle - The border style dictionary
  10175. */
  10176. setBorderStyle: function Annotation_setBorderStyle(borderStyle) {
  10177. if (!isDict(borderStyle)) {
  10178. return;
  10179. }
  10180. if (borderStyle.has('BS')) {
  10181. var dict = borderStyle.get('BS');
  10182. var dictType;
  10183. if (!dict.has('Type') || (isName(dictType = dict.get('Type')) &&
  10184. dictType.name === 'Border')) {
  10185. this.borderStyle.setWidth(dict.get('W'));
  10186. this.borderStyle.setStyle(dict.get('S'));
  10187. this.borderStyle.setDashArray(dict.get('D'));
  10188. }
  10189. } else if (borderStyle.has('Border')) {
  10190. var array = borderStyle.get('Border');
  10191. if (isArray(array) && array.length >= 3) {
  10192. this.borderStyle.setHorizontalCornerRadius(array[0]);
  10193. this.borderStyle.setVerticalCornerRadius(array[1]);
  10194. this.borderStyle.setWidth(array[2]);
  10195. this.borderStyle.setStyle('S');
  10196. if (array.length === 4) { // Dash array available
  10197. this.borderStyle.setDashArray(array[3]);
  10198. }
  10199. }
  10200. } else {
  10201. // There are no border entries in the dictionary. According to the
  10202. // specification, we should draw a solid border of width 1 in that
  10203. // case, but Adobe Reader did not implement that part of the
  10204. // specification and instead draws no border at all, so we do the same.
  10205. // See also https://github.com/mozilla/pdf.js/issues/6179.
  10206. this.borderStyle.setWidth(0);
  10207. }
  10208. },
  10209. getData: function Annotation_getData() {
  10210. return this.data;
  10211. },
  10212. isInvisible: function Annotation_isInvisible() {
  10213. var data = this.data;
  10214. if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) {
  10215. return false;
  10216. } else {
  10217. return !!(data &&
  10218. data.annotationFlags && // Default: not invisible
  10219. data.annotationFlags & 0x1); // Invisible
  10220. }
  10221. },
  10222. isViewable: function Annotation_isViewable() {
  10223. var data = this.data;
  10224. return !!(!this.isInvisible() &&
  10225. data &&
  10226. (!data.annotationFlags ||
  10227. !(data.annotationFlags & 0x22)) && // Hidden or NoView
  10228. data.rect); // rectangle is necessary
  10229. },
  10230. isPrintable: function Annotation_isPrintable() {
  10231. var data = this.data;
  10232. return !!(!this.isInvisible() &&
  10233. data &&
  10234. data.annotationFlags && // Default: not printable
  10235. data.annotationFlags & 0x4 && // Print
  10236. !(data.annotationFlags & 0x2) && // Hidden
  10237. data.rect); // rectangle is necessary
  10238. },
  10239. loadResources: function Annotation_loadResources(keys) {
  10240. return new Promise(function (resolve, reject) {
  10241. this.appearance.dict.getAsync('Resources').then(function (resources) {
  10242. if (!resources) {
  10243. resolve();
  10244. return;
  10245. }
  10246. var objectLoader = new ObjectLoader(resources.map,
  10247. keys,
  10248. resources.xref);
  10249. objectLoader.load().then(function() {
  10250. resolve(resources);
  10251. }, reject);
  10252. }, reject);
  10253. }.bind(this));
  10254. },
  10255. getOperatorList: function Annotation_getOperatorList(evaluator) {
  10256. if (!this.appearance) {
  10257. return Promise.resolve(new OperatorList());
  10258. }
  10259. var data = this.data;
  10260. var appearanceDict = this.appearance.dict;
  10261. var resourcesPromise = this.loadResources([
  10262. 'ExtGState',
  10263. 'ColorSpace',
  10264. 'Pattern',
  10265. 'Shading',
  10266. 'XObject',
  10267. 'Font'
  10268. // ProcSet
  10269. // Properties
  10270. ]);
  10271. var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];
  10272. var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];
  10273. var transform = getTransformMatrix(data.rect, bbox, matrix);
  10274. var self = this;
  10275. return resourcesPromise.then(function(resources) {
  10276. var opList = new OperatorList();
  10277. opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
  10278. return evaluator.getOperatorList(self.appearance, resources, opList).
  10279. then(function () {
  10280. opList.addOp(OPS.endAnnotation, []);
  10281. self.appearance.reset();
  10282. return opList;
  10283. });
  10284. });
  10285. }
  10286. };
  10287. Annotation.getConstructor =
  10288. function Annotation_getConstructor(subtype, fieldType) {
  10289. if (!subtype) {
  10290. return;
  10291. }
  10292. // TODO(mack): Implement FreeText annotations
  10293. if (subtype === 'Link') {
  10294. return LinkAnnotation;
  10295. } else if (subtype === 'Text') {
  10296. return TextAnnotation;
  10297. } else if (subtype === 'Widget') {
  10298. if (!fieldType) {
  10299. return;
  10300. }
  10301. if (fieldType === 'Tx') {
  10302. return TextWidgetAnnotation;
  10303. } else {
  10304. return WidgetAnnotation;
  10305. }
  10306. } else {
  10307. return Annotation;
  10308. }
  10309. };
  10310. Annotation.fromRef = function Annotation_fromRef(xref, ref) {
  10311. var dict = xref.fetchIfRef(ref);
  10312. if (!isDict(dict)) {
  10313. return;
  10314. }
  10315. var subtype = dict.get('Subtype');
  10316. subtype = isName(subtype) ? subtype.name : '';
  10317. if (!subtype) {
  10318. return;
  10319. }
  10320. var fieldType = Util.getInheritableProperty(dict, 'FT');
  10321. fieldType = isName(fieldType) ? fieldType.name : '';
  10322. var Constructor = Annotation.getConstructor(subtype, fieldType);
  10323. if (!Constructor) {
  10324. return;
  10325. }
  10326. var params = {
  10327. dict: dict,
  10328. ref: ref,
  10329. };
  10330. var annotation = new Constructor(params);
  10331. if (annotation.isViewable() || annotation.isPrintable()) {
  10332. return annotation;
  10333. } else {
  10334. if (SUPPORTED_TYPES.indexOf(subtype) === -1) {
  10335. warn('unimplemented annotation type: ' + subtype);
  10336. }
  10337. }
  10338. };
  10339. Annotation.appendToOperatorList = function Annotation_appendToOperatorList(
  10340. annotations, opList, pdfManager, partialEvaluator, intent) {
  10341. function reject(e) {
  10342. annotationsReadyCapability.reject(e);
  10343. }
  10344. var annotationsReadyCapability = createPromiseCapability();
  10345. var annotationPromises = [];
  10346. for (var i = 0, n = annotations.length; i < n; ++i) {
  10347. if (intent === 'display' && annotations[i].isViewable() ||
  10348. intent === 'print' && annotations[i].isPrintable()) {
  10349. annotationPromises.push(
  10350. annotations[i].getOperatorList(partialEvaluator));
  10351. }
  10352. }
  10353. Promise.all(annotationPromises).then(function(datas) {
  10354. opList.addOp(OPS.beginAnnotations, []);
  10355. for (var i = 0, n = datas.length; i < n; ++i) {
  10356. var annotOpList = datas[i];
  10357. opList.addOpList(annotOpList);
  10358. }
  10359. opList.addOp(OPS.endAnnotations, []);
  10360. annotationsReadyCapability.resolve();
  10361. }, reject);
  10362. return annotationsReadyCapability.promise;
  10363. };
  10364. return Annotation;
  10365. })();
  10366. /**
  10367. * Contains all data regarding an annotation's border style.
  10368. *
  10369. * @class
  10370. */
  10371. var AnnotationBorderStyle = (function AnnotationBorderStyleClosure() {
  10372. /**
  10373. * @constructor
  10374. * @private
  10375. */
  10376. function AnnotationBorderStyle() {
  10377. this.width = 1;
  10378. this.style = AnnotationBorderStyleType.SOLID;
  10379. this.dashArray = [3];
  10380. this.horizontalCornerRadius = 0;
  10381. this.verticalCornerRadius = 0;
  10382. }
  10383. AnnotationBorderStyle.prototype = {
  10384. /**
  10385. * Set the width.
  10386. *
  10387. * @public
  10388. * @memberof AnnotationBorderStyle
  10389. * @param {integer} width - The width
  10390. */
  10391. setWidth: function AnnotationBorderStyle_setWidth(width) {
  10392. if (width === (width | 0)) {
  10393. this.width = width;
  10394. }
  10395. },
  10396. /**
  10397. * Set the style.
  10398. *
  10399. * @public
  10400. * @memberof AnnotationBorderStyle
  10401. * @param {Object} style - The style object
  10402. * @see {@link shared/util.js}
  10403. */
  10404. setStyle: function AnnotationBorderStyle_setStyle(style) {
  10405. if (!style) {
  10406. return;
  10407. }
  10408. switch (style.name) {
  10409. case 'S':
  10410. this.style = AnnotationBorderStyleType.SOLID;
  10411. break;
  10412. case 'D':
  10413. this.style = AnnotationBorderStyleType.DASHED;
  10414. break;
  10415. case 'B':
  10416. this.style = AnnotationBorderStyleType.BEVELED;
  10417. break;
  10418. case 'I':
  10419. this.style = AnnotationBorderStyleType.INSET;
  10420. break;
  10421. case 'U':
  10422. this.style = AnnotationBorderStyleType.UNDERLINE;
  10423. break;
  10424. default:
  10425. break;
  10426. }
  10427. },
  10428. /**
  10429. * Set the dash array.
  10430. *
  10431. * @public
  10432. * @memberof AnnotationBorderStyle
  10433. * @param {Array} dashArray - The dash array with at least one element
  10434. */
  10435. setDashArray: function AnnotationBorderStyle_setDashArray(dashArray) {
  10436. // We validate the dash array, but we do not use it because CSS does not
  10437. // allow us to change spacing of dashes. For more information, visit
  10438. // http://www.w3.org/TR/css3-background/#the-border-style.
  10439. if (isArray(dashArray) && dashArray.length > 0) {
  10440. // According to the PDF specification: the elements in a dashArray
  10441. // shall be numbers that are nonnegative and not all equal to zero.
  10442. var isValid = true;
  10443. var allZeros = true;
  10444. for (var i = 0, len = dashArray.length; i < len; i++) {
  10445. var element = dashArray[i];
  10446. var validNumber = (+element >= 0);
  10447. if (!validNumber) {
  10448. isValid = false;
  10449. break;
  10450. } else if (element > 0) {
  10451. allZeros = false;
  10452. }
  10453. }
  10454. if (isValid && !allZeros) {
  10455. this.dashArray = dashArray;
  10456. } else {
  10457. this.width = 0; // Adobe behavior when the array is invalid.
  10458. }
  10459. } else if (dashArray) {
  10460. this.width = 0; // Adobe behavior when the array is invalid.
  10461. }
  10462. },
  10463. /**
  10464. * Set the horizontal corner radius (from a Border dictionary).
  10465. *
  10466. * @public
  10467. * @memberof AnnotationBorderStyle
  10468. * @param {integer} radius - The horizontal corner radius
  10469. */
  10470. setHorizontalCornerRadius:
  10471. function AnnotationBorderStyle_setHorizontalCornerRadius(radius) {
  10472. if (radius === (radius | 0)) {
  10473. this.horizontalCornerRadius = radius;
  10474. }
  10475. },
  10476. /**
  10477. * Set the vertical corner radius (from a Border dictionary).
  10478. *
  10479. * @public
  10480. * @memberof AnnotationBorderStyle
  10481. * @param {integer} radius - The vertical corner radius
  10482. */
  10483. setVerticalCornerRadius:
  10484. function AnnotationBorderStyle_setVerticalCornerRadius(radius) {
  10485. if (radius === (radius | 0)) {
  10486. this.verticalCornerRadius = radius;
  10487. }
  10488. }
  10489. };
  10490. return AnnotationBorderStyle;
  10491. })();
  10492. var WidgetAnnotation = (function WidgetAnnotationClosure() {
  10493. function WidgetAnnotation(params) {
  10494. Annotation.call(this, params);
  10495. var dict = params.dict;
  10496. var data = this.data;
  10497. data.fieldValue = stringToPDFString(
  10498. Util.getInheritableProperty(dict, 'V') || '');
  10499. data.alternativeText = stringToPDFString(dict.get('TU') || '');
  10500. data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';
  10501. var fieldType = Util.getInheritableProperty(dict, 'FT');
  10502. data.fieldType = isName(fieldType) ? fieldType.name : '';
  10503. data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;
  10504. this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;
  10505. // Building the full field name by collecting the field and
  10506. // its ancestors 'T' data and joining them using '.'.
  10507. var fieldName = [];
  10508. var namedItem = dict;
  10509. var ref = params.ref;
  10510. while (namedItem) {
  10511. var parent = namedItem.get('Parent');
  10512. var parentRef = namedItem.getRaw('Parent');
  10513. var name = namedItem.get('T');
  10514. if (name) {
  10515. fieldName.unshift(stringToPDFString(name));
  10516. } else if (parent && ref) {
  10517. // The field name is absent, that means more than one field
  10518. // with the same name may exist. Replacing the empty name
  10519. // with the '`' plus index in the parent's 'Kids' array.
  10520. // This is not in the PDF spec but necessary to id the
  10521. // the input controls.
  10522. var kids = parent.get('Kids');
  10523. var j, jj;
  10524. for (j = 0, jj = kids.length; j < jj; j++) {
  10525. var kidRef = kids[j];
  10526. if (kidRef.num === ref.num && kidRef.gen === ref.gen) {
  10527. break;
  10528. }
  10529. }
  10530. fieldName.unshift('`' + j);
  10531. }
  10532. namedItem = parent;
  10533. ref = parentRef;
  10534. }
  10535. data.fullName = fieldName.join('.');
  10536. }
  10537. var parent = Annotation.prototype;
  10538. Util.inherit(WidgetAnnotation, Annotation, {
  10539. isViewable: function WidgetAnnotation_isViewable() {
  10540. if (this.data.fieldType === 'Sig') {
  10541. warn('unimplemented annotation type: Widget signature');
  10542. return false;
  10543. }
  10544. return parent.isViewable.call(this);
  10545. }
  10546. });
  10547. return WidgetAnnotation;
  10548. })();
  10549. var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
  10550. function TextWidgetAnnotation(params) {
  10551. WidgetAnnotation.call(this, params);
  10552. this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');
  10553. this.data.annotationType = AnnotationType.WIDGET;
  10554. this.data.hasHtml = !this.data.hasAppearance && !!this.data.fieldValue;
  10555. }
  10556. Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
  10557. getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {
  10558. if (this.appearance) {
  10559. return Annotation.prototype.getOperatorList.call(this, evaluator);
  10560. }
  10561. var opList = new OperatorList();
  10562. var data = this.data;
  10563. // Even if there is an appearance stream, ignore it. This is the
  10564. // behaviour used by Adobe Reader.
  10565. if (!data.defaultAppearance) {
  10566. return Promise.resolve(opList);
  10567. }
  10568. var stream = new Stream(stringToBytes(data.defaultAppearance));
  10569. return evaluator.getOperatorList(stream, this.fieldResources, opList).
  10570. then(function () {
  10571. return opList;
  10572. });
  10573. }
  10574. });
  10575. return TextWidgetAnnotation;
  10576. })();
  10577. var TextAnnotation = (function TextAnnotationClosure() {
  10578. function TextAnnotation(params) {
  10579. Annotation.call(this, params);
  10580. var dict = params.dict;
  10581. var data = this.data;
  10582. var content = dict.get('Contents');
  10583. var title = dict.get('T');
  10584. data.annotationType = AnnotationType.TEXT;
  10585. data.content = stringToPDFString(content || '');
  10586. data.title = stringToPDFString(title || '');
  10587. data.hasHtml = true;
  10588. if (data.hasAppearance) {
  10589. data.name = 'NoIcon';
  10590. } else {
  10591. data.rect[1] = data.rect[3] - DEFAULT_ICON_SIZE;
  10592. data.rect[2] = data.rect[0] + DEFAULT_ICON_SIZE;
  10593. data.name = dict.has('Name') ? dict.get('Name').name : 'Note';
  10594. }
  10595. if (dict.has('C')) {
  10596. data.hasBgColor = true;
  10597. }
  10598. }
  10599. Util.inherit(TextAnnotation, Annotation, { });
  10600. return TextAnnotation;
  10601. })();
  10602. var LinkAnnotation = (function LinkAnnotationClosure() {
  10603. function LinkAnnotation(params) {
  10604. Annotation.call(this, params);
  10605. var dict = params.dict;
  10606. var data = this.data;
  10607. data.annotationType = AnnotationType.LINK;
  10608. data.hasHtml = true;
  10609. var action = dict.get('A');
  10610. if (action && isDict(action)) {
  10611. var linkType = action.get('S').name;
  10612. if (linkType === 'URI') {
  10613. var url = action.get('URI');
  10614. if (isName(url)) {
  10615. // Some bad PDFs do not put parentheses around relative URLs.
  10616. url = '/' + url.name;
  10617. } else if (url) {
  10618. url = addDefaultProtocolToUrl(url);
  10619. }
  10620. // TODO: pdf spec mentions urls can be relative to a Base
  10621. // entry in the dictionary.
  10622. if (!isValidUrl(url, false)) {
  10623. url = '';
  10624. }
  10625. // According to ISO 32000-1:2008, section 12.6.4.7,
  10626. // URI should to be encoded in 7-bit ASCII.
  10627. // Some bad PDFs may have URIs in UTF-8 encoding, see Bugzilla 1122280.
  10628. try {
  10629. data.url = stringToUTF8String(url);
  10630. } catch (e) {
  10631. // Fall back to a simple copy.
  10632. data.url = url;
  10633. }
  10634. } else if (linkType === 'GoTo') {
  10635. data.dest = action.get('D');
  10636. } else if (linkType === 'GoToR') {
  10637. var urlDict = action.get('F');
  10638. if (isDict(urlDict)) {
  10639. // We assume that the 'url' is a Filspec dictionary
  10640. // and fetch the url without checking any further
  10641. url = urlDict.get('F') || '';
  10642. }
  10643. // TODO: pdf reference says that GoToR
  10644. // can also have 'NewWindow' attribute
  10645. if (!isValidUrl(url, false)) {
  10646. url = '';
  10647. }
  10648. data.url = url;
  10649. data.dest = action.get('D');
  10650. } else if (linkType === 'Named') {
  10651. data.action = action.get('N').name;
  10652. } else {
  10653. warn('unrecognized link type: ' + linkType);
  10654. }
  10655. } else if (dict.has('Dest')) {
  10656. // simple destination link
  10657. var dest = dict.get('Dest');
  10658. data.dest = isName(dest) ? dest.name : dest;
  10659. }
  10660. }
  10661. // Lets URLs beginning with 'www.' default to using the 'http://' protocol.
  10662. function addDefaultProtocolToUrl(url) {
  10663. if (url && url.indexOf('www.') === 0) {
  10664. return ('http://' + url);
  10665. }
  10666. return url;
  10667. }
  10668. Util.inherit(LinkAnnotation, Annotation, { });
  10669. return LinkAnnotation;
  10670. })();
  10671. var PDFFunction = (function PDFFunctionClosure() {
  10672. var CONSTRUCT_SAMPLED = 0;
  10673. var CONSTRUCT_INTERPOLATED = 2;
  10674. var CONSTRUCT_STICHED = 3;
  10675. var CONSTRUCT_POSTSCRIPT = 4;
  10676. return {
  10677. getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,
  10678. str) {
  10679. var i, ii;
  10680. var length = 1;
  10681. for (i = 0, ii = size.length; i < ii; i++) {
  10682. length *= size[i];
  10683. }
  10684. length *= outputSize;
  10685. var array = new Array(length);
  10686. var codeSize = 0;
  10687. var codeBuf = 0;
  10688. // 32 is a valid bps so shifting won't work
  10689. var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);
  10690. var strBytes = str.getBytes((length * bps + 7) / 8);
  10691. var strIdx = 0;
  10692. for (i = 0; i < length; i++) {
  10693. while (codeSize < bps) {
  10694. codeBuf <<= 8;
  10695. codeBuf |= strBytes[strIdx++];
  10696. codeSize += 8;
  10697. }
  10698. codeSize -= bps;
  10699. array[i] = (codeBuf >> codeSize) * sampleMul;
  10700. codeBuf &= (1 << codeSize) - 1;
  10701. }
  10702. return array;
  10703. },
  10704. getIR: function PDFFunction_getIR(xref, fn) {
  10705. var dict = fn.dict;
  10706. if (!dict) {
  10707. dict = fn;
  10708. }
  10709. var types = [this.constructSampled,
  10710. null,
  10711. this.constructInterpolated,
  10712. this.constructStiched,
  10713. this.constructPostScript];
  10714. var typeNum = dict.get('FunctionType');
  10715. var typeFn = types[typeNum];
  10716. if (!typeFn) {
  10717. error('Unknown type of function');
  10718. }
  10719. return typeFn.call(this, fn, dict, xref);
  10720. },
  10721. fromIR: function PDFFunction_fromIR(IR) {
  10722. var type = IR[0];
  10723. switch (type) {
  10724. case CONSTRUCT_SAMPLED:
  10725. return this.constructSampledFromIR(IR);
  10726. case CONSTRUCT_INTERPOLATED:
  10727. return this.constructInterpolatedFromIR(IR);
  10728. case CONSTRUCT_STICHED:
  10729. return this.constructStichedFromIR(IR);
  10730. //case CONSTRUCT_POSTSCRIPT:
  10731. default:
  10732. return this.constructPostScriptFromIR(IR);
  10733. }
  10734. },
  10735. parse: function PDFFunction_parse(xref, fn) {
  10736. var IR = this.getIR(xref, fn);
  10737. return this.fromIR(IR);
  10738. },
  10739. parseArray: function PDFFunction_parseArray(xref, fnObj) {
  10740. if (!isArray(fnObj)) {
  10741. // not an array -- parsing as regular function
  10742. return this.parse(xref, fnObj);
  10743. }
  10744. var fnArray = [];
  10745. for (var j = 0, jj = fnObj.length; j < jj; j++) {
  10746. var obj = xref.fetchIfRef(fnObj[j]);
  10747. fnArray.push(PDFFunction.parse(xref, obj));
  10748. }
  10749. return function (src, srcOffset, dest, destOffset) {
  10750. for (var i = 0, ii = fnArray.length; i < ii; i++) {
  10751. fnArray[i](src, srcOffset, dest, destOffset + i);
  10752. }
  10753. };
  10754. },
  10755. constructSampled: function PDFFunction_constructSampled(str, dict) {
  10756. function toMultiArray(arr) {
  10757. var inputLength = arr.length;
  10758. var out = [];
  10759. var index = 0;
  10760. for (var i = 0; i < inputLength; i += 2) {
  10761. out[index] = [arr[i], arr[i + 1]];
  10762. ++index;
  10763. }
  10764. return out;
  10765. }
  10766. var domain = dict.get('Domain');
  10767. var range = dict.get('Range');
  10768. if (!domain || !range) {
  10769. error('No domain or range');
  10770. }
  10771. var inputSize = domain.length / 2;
  10772. var outputSize = range.length / 2;
  10773. domain = toMultiArray(domain);
  10774. range = toMultiArray(range);
  10775. var size = dict.get('Size');
  10776. var bps = dict.get('BitsPerSample');
  10777. var order = dict.get('Order') || 1;
  10778. if (order !== 1) {
  10779. // No description how cubic spline interpolation works in PDF32000:2008
  10780. // As in poppler, ignoring order, linear interpolation may work as good
  10781. info('No support for cubic spline interpolation: ' + order);
  10782. }
  10783. var encode = dict.get('Encode');
  10784. if (!encode) {
  10785. encode = [];
  10786. for (var i = 0; i < inputSize; ++i) {
  10787. encode.push(0);
  10788. encode.push(size[i] - 1);
  10789. }
  10790. }
  10791. encode = toMultiArray(encode);
  10792. var decode = dict.get('Decode');
  10793. if (!decode) {
  10794. decode = range;
  10795. } else {
  10796. decode = toMultiArray(decode);
  10797. }
  10798. var samples = this.getSampleArray(size, outputSize, bps, str);
  10799. return [
  10800. CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,
  10801. outputSize, Math.pow(2, bps) - 1, range
  10802. ];
  10803. },
  10804. constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {
  10805. // See chapter 3, page 109 of the PDF reference
  10806. function interpolate(x, xmin, xmax, ymin, ymax) {
  10807. return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));
  10808. }
  10809. return function constructSampledFromIRResult(src, srcOffset,
  10810. dest, destOffset) {
  10811. // See chapter 3, page 110 of the PDF reference.
  10812. var m = IR[1];
  10813. var domain = IR[2];
  10814. var encode = IR[3];
  10815. var decode = IR[4];
  10816. var samples = IR[5];
  10817. var size = IR[6];
  10818. var n = IR[7];
  10819. //var mask = IR[8];
  10820. var range = IR[9];
  10821. // Building the cube vertices: its part and sample index
  10822. // http://rjwagner49.com/Mathematics/Interpolation.pdf
  10823. var cubeVertices = 1 << m;
  10824. var cubeN = new Float64Array(cubeVertices);
  10825. var cubeVertex = new Uint32Array(cubeVertices);
  10826. var i, j;
  10827. for (j = 0; j < cubeVertices; j++) {
  10828. cubeN[j] = 1;
  10829. }
  10830. var k = n, pos = 1;
  10831. // Map x_i to y_j for 0 <= i < m using the sampled function.
  10832. for (i = 0; i < m; ++i) {
  10833. // x_i' = min(max(x_i, Domain_2i), Domain_2i+1)
  10834. var domain_2i = domain[i][0];
  10835. var domain_2i_1 = domain[i][1];
  10836. var xi = Math.min(Math.max(src[srcOffset +i], domain_2i),
  10837. domain_2i_1);
  10838. // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,
  10839. // Encode_2i, Encode_2i+1)
  10840. var e = interpolate(xi, domain_2i, domain_2i_1,
  10841. encode[i][0], encode[i][1]);
  10842. // e_i' = min(max(e_i, 0), Size_i - 1)
  10843. var size_i = size[i];
  10844. e = Math.min(Math.max(e, 0), size_i - 1);
  10845. // Adjusting the cube: N and vertex sample index
  10846. var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;
  10847. var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);
  10848. var n1 = e - e0; // (e - e0) / (e1 - e0);
  10849. var offset0 = e0 * k;
  10850. var offset1 = offset0 + k; // e1 * k
  10851. for (j = 0; j < cubeVertices; j++) {
  10852. if (j & pos) {
  10853. cubeN[j] *= n1;
  10854. cubeVertex[j] += offset1;
  10855. } else {
  10856. cubeN[j] *= n0;
  10857. cubeVertex[j] += offset0;
  10858. }
  10859. }
  10860. k *= size_i;
  10861. pos <<= 1;
  10862. }
  10863. for (j = 0; j < n; ++j) {
  10864. // Sum all cube vertices' samples portions
  10865. var rj = 0;
  10866. for (i = 0; i < cubeVertices; i++) {
  10867. rj += samples[cubeVertex[i] + j] * cubeN[i];
  10868. }
  10869. // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,
  10870. // Decode_2j, Decode_2j+1)
  10871. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  10872. // y_j = min(max(r_j, range_2j), range_2j+1)
  10873. dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]),
  10874. range[j][1]);
  10875. }
  10876. };
  10877. },
  10878. constructInterpolated: function PDFFunction_constructInterpolated(str,
  10879. dict) {
  10880. var c0 = dict.get('C0') || [0];
  10881. var c1 = dict.get('C1') || [1];
  10882. var n = dict.get('N');
  10883. if (!isArray(c0) || !isArray(c1)) {
  10884. error('Illegal dictionary for interpolated function');
  10885. }
  10886. var length = c0.length;
  10887. var diff = [];
  10888. for (var i = 0; i < length; ++i) {
  10889. diff.push(c1[i] - c0[i]);
  10890. }
  10891. return [CONSTRUCT_INTERPOLATED, c0, diff, n];
  10892. },
  10893. constructInterpolatedFromIR:
  10894. function PDFFunction_constructInterpolatedFromIR(IR) {
  10895. var c0 = IR[1];
  10896. var diff = IR[2];
  10897. var n = IR[3];
  10898. var length = diff.length;
  10899. return function constructInterpolatedFromIRResult(src, srcOffset,
  10900. dest, destOffset) {
  10901. var x = n === 1 ? src[srcOffset] : Math.pow(src[srcOffset], n);
  10902. for (var j = 0; j < length; ++j) {
  10903. dest[destOffset + j] = c0[j] + (x * diff[j]);
  10904. }
  10905. };
  10906. },
  10907. constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {
  10908. var domain = dict.get('Domain');
  10909. if (!domain) {
  10910. error('No domain');
  10911. }
  10912. var inputSize = domain.length / 2;
  10913. if (inputSize !== 1) {
  10914. error('Bad domain for stiched function');
  10915. }
  10916. var fnRefs = dict.get('Functions');
  10917. var fns = [];
  10918. for (var i = 0, ii = fnRefs.length; i < ii; ++i) {
  10919. fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));
  10920. }
  10921. var bounds = dict.get('Bounds');
  10922. var encode = dict.get('Encode');
  10923. return [CONSTRUCT_STICHED, domain, bounds, encode, fns];
  10924. },
  10925. constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {
  10926. var domain = IR[1];
  10927. var bounds = IR[2];
  10928. var encode = IR[3];
  10929. var fnsIR = IR[4];
  10930. var fns = [];
  10931. var tmpBuf = new Float32Array(1);
  10932. for (var i = 0, ii = fnsIR.length; i < ii; i++) {
  10933. fns.push(PDFFunction.fromIR(fnsIR[i]));
  10934. }
  10935. return function constructStichedFromIRResult(src, srcOffset,
  10936. dest, destOffset) {
  10937. var clip = function constructStichedFromIRClip(v, min, max) {
  10938. if (v > max) {
  10939. v = max;
  10940. } else if (v < min) {
  10941. v = min;
  10942. }
  10943. return v;
  10944. };
  10945. // clip to domain
  10946. var v = clip(src[srcOffset], domain[0], domain[1]);
  10947. // calulate which bound the value is in
  10948. for (var i = 0, ii = bounds.length; i < ii; ++i) {
  10949. if (v < bounds[i]) {
  10950. break;
  10951. }
  10952. }
  10953. // encode value into domain of function
  10954. var dmin = domain[0];
  10955. if (i > 0) {
  10956. dmin = bounds[i - 1];
  10957. }
  10958. var dmax = domain[1];
  10959. if (i < bounds.length) {
  10960. dmax = bounds[i];
  10961. }
  10962. var rmin = encode[2 * i];
  10963. var rmax = encode[2 * i + 1];
  10964. // Prevent the value from becoming NaN as a result
  10965. // of division by zero (fixes issue6113.pdf).
  10966. tmpBuf[0] = dmin === dmax ? rmin :
  10967. rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  10968. // call the appropriate function
  10969. fns[i](tmpBuf, 0, dest, destOffset);
  10970. };
  10971. },
  10972. constructPostScript: function PDFFunction_constructPostScript(fn, dict,
  10973. xref) {
  10974. var domain = dict.get('Domain');
  10975. var range = dict.get('Range');
  10976. if (!domain) {
  10977. error('No domain.');
  10978. }
  10979. if (!range) {
  10980. error('No range.');
  10981. }
  10982. var lexer = new PostScriptLexer(fn);
  10983. var parser = new PostScriptParser(lexer);
  10984. var code = parser.parse();
  10985. return [CONSTRUCT_POSTSCRIPT, domain, range, code];
  10986. },
  10987. constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(
  10988. IR) {
  10989. var domain = IR[1];
  10990. var range = IR[2];
  10991. var code = IR[3];
  10992. var compiled = (new PostScriptCompiler()).compile(code, domain, range);
  10993. if (compiled) {
  10994. // Compiled function consists of simple expressions such as addition,
  10995. // subtraction, Math.max, and also contains 'var' and 'return'
  10996. // statements. See the generation in the PostScriptCompiler below.
  10997. /*jshint -W054 */
  10998. return new Function('src', 'srcOffset', 'dest', 'destOffset', compiled);
  10999. }
  11000. info('Unable to compile PS function');
  11001. var numOutputs = range.length >> 1;
  11002. var numInputs = domain.length >> 1;
  11003. var evaluator = new PostScriptEvaluator(code);
  11004. // Cache the values for a big speed up, the cache size is limited though
  11005. // since the number of possible values can be huge from a PS function.
  11006. var cache = {};
  11007. // The MAX_CACHE_SIZE is set to ~4x the maximum number of distinct values
  11008. // seen in our tests.
  11009. var MAX_CACHE_SIZE = 2048 * 4;
  11010. var cache_available = MAX_CACHE_SIZE;
  11011. var tmpBuf = new Float32Array(numInputs);
  11012. return function constructPostScriptFromIRResult(src, srcOffset,
  11013. dest, destOffset) {
  11014. var i, value;
  11015. var key = '';
  11016. var input = tmpBuf;
  11017. for (i = 0; i < numInputs; i++) {
  11018. value = src[srcOffset + i];
  11019. input[i] = value;
  11020. key += value + '_';
  11021. }
  11022. var cachedValue = cache[key];
  11023. if (cachedValue !== undefined) {
  11024. dest.set(cachedValue, destOffset);
  11025. return;
  11026. }
  11027. var output = new Float32Array(numOutputs);
  11028. var stack = evaluator.execute(input);
  11029. var stackIndex = stack.length - numOutputs;
  11030. for (i = 0; i < numOutputs; i++) {
  11031. value = stack[stackIndex + i];
  11032. var bound = range[i * 2];
  11033. if (value < bound) {
  11034. value = bound;
  11035. } else {
  11036. bound = range[i * 2 +1];
  11037. if (value > bound) {
  11038. value = bound;
  11039. }
  11040. }
  11041. output[i] = value;
  11042. }
  11043. if (cache_available > 0) {
  11044. cache_available--;
  11045. cache[key] = output;
  11046. }
  11047. dest.set(output, destOffset);
  11048. };
  11049. }
  11050. };
  11051. })();
  11052. function isPDFFunction(v) {
  11053. var fnDict;
  11054. if (typeof v !== 'object') {
  11055. return false;
  11056. } else if (isDict(v)) {
  11057. fnDict = v;
  11058. } else if (isStream(v)) {
  11059. fnDict = v.dict;
  11060. } else {
  11061. return false;
  11062. }
  11063. return fnDict.has('FunctionType');
  11064. }
  11065. var PostScriptStack = (function PostScriptStackClosure() {
  11066. var MAX_STACK_SIZE = 100;
  11067. function PostScriptStack(initialStack) {
  11068. this.stack = !initialStack ? [] :
  11069. Array.prototype.slice.call(initialStack, 0);
  11070. }
  11071. PostScriptStack.prototype = {
  11072. push: function PostScriptStack_push(value) {
  11073. if (this.stack.length >= MAX_STACK_SIZE) {
  11074. error('PostScript function stack overflow.');
  11075. }
  11076. this.stack.push(value);
  11077. },
  11078. pop: function PostScriptStack_pop() {
  11079. if (this.stack.length <= 0) {
  11080. error('PostScript function stack underflow.');
  11081. }
  11082. return this.stack.pop();
  11083. },
  11084. copy: function PostScriptStack_copy(n) {
  11085. if (this.stack.length + n >= MAX_STACK_SIZE) {
  11086. error('PostScript function stack overflow.');
  11087. }
  11088. var stack = this.stack;
  11089. for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  11090. stack.push(stack[i]);
  11091. }
  11092. },
  11093. index: function PostScriptStack_index(n) {
  11094. this.push(this.stack[this.stack.length - n - 1]);
  11095. },
  11096. // rotate the last n stack elements p times
  11097. roll: function PostScriptStack_roll(n, p) {
  11098. var stack = this.stack;
  11099. var l = stack.length - n;
  11100. var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;
  11101. for (i = l, j = r; i < j; i++, j--) {
  11102. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  11103. }
  11104. for (i = l, j = c - 1; i < j; i++, j--) {
  11105. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  11106. }
  11107. for (i = c, j = r; i < j; i++, j--) {
  11108. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  11109. }
  11110. }
  11111. };
  11112. return PostScriptStack;
  11113. })();
  11114. var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {
  11115. function PostScriptEvaluator(operators) {
  11116. this.operators = operators;
  11117. }
  11118. PostScriptEvaluator.prototype = {
  11119. execute: function PostScriptEvaluator_execute(initialStack) {
  11120. var stack = new PostScriptStack(initialStack);
  11121. var counter = 0;
  11122. var operators = this.operators;
  11123. var length = operators.length;
  11124. var operator, a, b;
  11125. while (counter < length) {
  11126. operator = operators[counter++];
  11127. if (typeof operator === 'number') {
  11128. // Operator is really an operand and should be pushed to the stack.
  11129. stack.push(operator);
  11130. continue;
  11131. }
  11132. switch (operator) {
  11133. // non standard ps operators
  11134. case 'jz': // jump if false
  11135. b = stack.pop();
  11136. a = stack.pop();
  11137. if (!a) {
  11138. counter = b;
  11139. }
  11140. break;
  11141. case 'j': // jump
  11142. a = stack.pop();
  11143. counter = a;
  11144. break;
  11145. // all ps operators in alphabetical order (excluding if/ifelse)
  11146. case 'abs':
  11147. a = stack.pop();
  11148. stack.push(Math.abs(a));
  11149. break;
  11150. case 'add':
  11151. b = stack.pop();
  11152. a = stack.pop();
  11153. stack.push(a + b);
  11154. break;
  11155. case 'and':
  11156. b = stack.pop();
  11157. a = stack.pop();
  11158. if (isBool(a) && isBool(b)) {
  11159. stack.push(a && b);
  11160. } else {
  11161. stack.push(a & b);
  11162. }
  11163. break;
  11164. case 'atan':
  11165. a = stack.pop();
  11166. stack.push(Math.atan(a));
  11167. break;
  11168. case 'bitshift':
  11169. b = stack.pop();
  11170. a = stack.pop();
  11171. if (a > 0) {
  11172. stack.push(a << b);
  11173. } else {
  11174. stack.push(a >> b);
  11175. }
  11176. break;
  11177. case 'ceiling':
  11178. a = stack.pop();
  11179. stack.push(Math.ceil(a));
  11180. break;
  11181. case 'copy':
  11182. a = stack.pop();
  11183. stack.copy(a);
  11184. break;
  11185. case 'cos':
  11186. a = stack.pop();
  11187. stack.push(Math.cos(a));
  11188. break;
  11189. case 'cvi':
  11190. a = stack.pop() | 0;
  11191. stack.push(a);
  11192. break;
  11193. case 'cvr':
  11194. // noop
  11195. break;
  11196. case 'div':
  11197. b = stack.pop();
  11198. a = stack.pop();
  11199. stack.push(a / b);
  11200. break;
  11201. case 'dup':
  11202. stack.copy(1);
  11203. break;
  11204. case 'eq':
  11205. b = stack.pop();
  11206. a = stack.pop();
  11207. stack.push(a === b);
  11208. break;
  11209. case 'exch':
  11210. stack.roll(2, 1);
  11211. break;
  11212. case 'exp':
  11213. b = stack.pop();
  11214. a = stack.pop();
  11215. stack.push(Math.pow(a, b));
  11216. break;
  11217. case 'false':
  11218. stack.push(false);
  11219. break;
  11220. case 'floor':
  11221. a = stack.pop();
  11222. stack.push(Math.floor(a));
  11223. break;
  11224. case 'ge':
  11225. b = stack.pop();
  11226. a = stack.pop();
  11227. stack.push(a >= b);
  11228. break;
  11229. case 'gt':
  11230. b = stack.pop();
  11231. a = stack.pop();
  11232. stack.push(a > b);
  11233. break;
  11234. case 'idiv':
  11235. b = stack.pop();
  11236. a = stack.pop();
  11237. stack.push((a / b) | 0);
  11238. break;
  11239. case 'index':
  11240. a = stack.pop();
  11241. stack.index(a);
  11242. break;
  11243. case 'le':
  11244. b = stack.pop();
  11245. a = stack.pop();
  11246. stack.push(a <= b);
  11247. break;
  11248. case 'ln':
  11249. a = stack.pop();
  11250. stack.push(Math.log(a));
  11251. break;
  11252. case 'log':
  11253. a = stack.pop();
  11254. stack.push(Math.log(a) / Math.LN10);
  11255. break;
  11256. case 'lt':
  11257. b = stack.pop();
  11258. a = stack.pop();
  11259. stack.push(a < b);
  11260. break;
  11261. case 'mod':
  11262. b = stack.pop();
  11263. a = stack.pop();
  11264. stack.push(a % b);
  11265. break;
  11266. case 'mul':
  11267. b = stack.pop();
  11268. a = stack.pop();
  11269. stack.push(a * b);
  11270. break;
  11271. case 'ne':
  11272. b = stack.pop();
  11273. a = stack.pop();
  11274. stack.push(a !== b);
  11275. break;
  11276. case 'neg':
  11277. a = stack.pop();
  11278. stack.push(-a);
  11279. break;
  11280. case 'not':
  11281. a = stack.pop();
  11282. if (isBool(a)) {
  11283. stack.push(!a);
  11284. } else {
  11285. stack.push(~a);
  11286. }
  11287. break;
  11288. case 'or':
  11289. b = stack.pop();
  11290. a = stack.pop();
  11291. if (isBool(a) && isBool(b)) {
  11292. stack.push(a || b);
  11293. } else {
  11294. stack.push(a | b);
  11295. }
  11296. break;
  11297. case 'pop':
  11298. stack.pop();
  11299. break;
  11300. case 'roll':
  11301. b = stack.pop();
  11302. a = stack.pop();
  11303. stack.roll(a, b);
  11304. break;
  11305. case 'round':
  11306. a = stack.pop();
  11307. stack.push(Math.round(a));
  11308. break;
  11309. case 'sin':
  11310. a = stack.pop();
  11311. stack.push(Math.sin(a));
  11312. break;
  11313. case 'sqrt':
  11314. a = stack.pop();
  11315. stack.push(Math.sqrt(a));
  11316. break;
  11317. case 'sub':
  11318. b = stack.pop();
  11319. a = stack.pop();
  11320. stack.push(a - b);
  11321. break;
  11322. case 'true':
  11323. stack.push(true);
  11324. break;
  11325. case 'truncate':
  11326. a = stack.pop();
  11327. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  11328. stack.push(a);
  11329. break;
  11330. case 'xor':
  11331. b = stack.pop();
  11332. a = stack.pop();
  11333. if (isBool(a) && isBool(b)) {
  11334. stack.push(a !== b);
  11335. } else {
  11336. stack.push(a ^ b);
  11337. }
  11338. break;
  11339. default:
  11340. error('Unknown operator ' + operator);
  11341. break;
  11342. }
  11343. }
  11344. return stack.stack;
  11345. }
  11346. };
  11347. return PostScriptEvaluator;
  11348. })();
  11349. // Most of the PDFs functions consist of simple operations such as:
  11350. // roll, exch, sub, cvr, pop, index, dup, mul, if, gt, add.
  11351. //
  11352. // We can compile most of such programs, and at the same moment, we can
  11353. // optimize some expressions using basic math properties. Keeping track of
  11354. // min/max values will allow us to avoid extra Math.min/Math.max calls.
  11355. var PostScriptCompiler = (function PostScriptCompilerClosure() {
  11356. function AstNode(type) {
  11357. this.type = type;
  11358. }
  11359. AstNode.prototype.visit = function (visitor) {
  11360. throw new Error('abstract method');
  11361. };
  11362. function AstArgument(index, min, max) {
  11363. AstNode.call(this, 'args');
  11364. this.index = index;
  11365. this.min = min;
  11366. this.max = max;
  11367. }
  11368. AstArgument.prototype = Object.create(AstNode.prototype);
  11369. AstArgument.prototype.visit = function (visitor) {
  11370. visitor.visitArgument(this);
  11371. };
  11372. function AstLiteral(number) {
  11373. AstNode.call(this, 'literal');
  11374. this.number = number;
  11375. this.min = number;
  11376. this.max = number;
  11377. }
  11378. AstLiteral.prototype = Object.create(AstNode.prototype);
  11379. AstLiteral.prototype.visit = function (visitor) {
  11380. visitor.visitLiteral(this);
  11381. };
  11382. function AstBinaryOperation(op, arg1, arg2, min, max) {
  11383. AstNode.call(this, 'binary');
  11384. this.op = op;
  11385. this.arg1 = arg1;
  11386. this.arg2 = arg2;
  11387. this.min = min;
  11388. this.max = max;
  11389. }
  11390. AstBinaryOperation.prototype = Object.create(AstNode.prototype);
  11391. AstBinaryOperation.prototype.visit = function (visitor) {
  11392. visitor.visitBinaryOperation(this);
  11393. };
  11394. function AstMin(arg, max) {
  11395. AstNode.call(this, 'max');
  11396. this.arg = arg;
  11397. this.min = arg.min;
  11398. this.max = max;
  11399. }
  11400. AstMin.prototype = Object.create(AstNode.prototype);
  11401. AstMin.prototype.visit = function (visitor) {
  11402. visitor.visitMin(this);
  11403. };
  11404. function AstVariable(index, min, max) {
  11405. AstNode.call(this, 'var');
  11406. this.index = index;
  11407. this.min = min;
  11408. this.max = max;
  11409. }
  11410. AstVariable.prototype = Object.create(AstNode.prototype);
  11411. AstVariable.prototype.visit = function (visitor) {
  11412. visitor.visitVariable(this);
  11413. };
  11414. function AstVariableDefinition(variable, arg) {
  11415. AstNode.call(this, 'definition');
  11416. this.variable = variable;
  11417. this.arg = arg;
  11418. }
  11419. AstVariableDefinition.prototype = Object.create(AstNode.prototype);
  11420. AstVariableDefinition.prototype.visit = function (visitor) {
  11421. visitor.visitVariableDefinition(this);
  11422. };
  11423. function ExpressionBuilderVisitor() {
  11424. this.parts = [];
  11425. }
  11426. ExpressionBuilderVisitor.prototype = {
  11427. visitArgument: function (arg) {
  11428. this.parts.push('Math.max(', arg.min, ', Math.min(',
  11429. arg.max, ', src[srcOffset + ', arg.index, ']))');
  11430. },
  11431. visitVariable: function (variable) {
  11432. this.parts.push('v', variable.index);
  11433. },
  11434. visitLiteral: function (literal) {
  11435. this.parts.push(literal.number);
  11436. },
  11437. visitBinaryOperation: function (operation) {
  11438. this.parts.push('(');
  11439. operation.arg1.visit(this);
  11440. this.parts.push(' ', operation.op, ' ');
  11441. operation.arg2.visit(this);
  11442. this.parts.push(')');
  11443. },
  11444. visitVariableDefinition: function (definition) {
  11445. this.parts.push('var ');
  11446. definition.variable.visit(this);
  11447. this.parts.push(' = ');
  11448. definition.arg.visit(this);
  11449. this.parts.push(';');
  11450. },
  11451. visitMin: function (max) {
  11452. this.parts.push('Math.min(');
  11453. max.arg.visit(this);
  11454. this.parts.push(', ', max.max, ')');
  11455. },
  11456. toString: function () {
  11457. return this.parts.join('');
  11458. }
  11459. };
  11460. function buildAddOperation(num1, num2) {
  11461. if (num2.type === 'literal' && num2.number === 0) {
  11462. // optimization: second operand is 0
  11463. return num1;
  11464. }
  11465. if (num1.type === 'literal' && num1.number === 0) {
  11466. // optimization: first operand is 0
  11467. return num2;
  11468. }
  11469. if (num2.type === 'literal' && num1.type === 'literal') {
  11470. // optimization: operands operand are literals
  11471. return new AstLiteral(num1.number + num2.number);
  11472. }
  11473. return new AstBinaryOperation('+', num1, num2,
  11474. num1.min + num2.min, num1.max + num2.max);
  11475. }
  11476. function buildMulOperation(num1, num2) {
  11477. if (num2.type === 'literal') {
  11478. // optimization: second operands is a literal...
  11479. if (num2.number === 0) {
  11480. return new AstLiteral(0); // and it's 0
  11481. } else if (num2.number === 1) {
  11482. return num1; // and it's 1
  11483. } else if (num1.type === 'literal') {
  11484. // ... and first operands is a literal too
  11485. return new AstLiteral(num1.number * num2.number);
  11486. }
  11487. }
  11488. if (num1.type === 'literal') {
  11489. // optimization: first operands is a literal...
  11490. if (num1.number === 0) {
  11491. return new AstLiteral(0); // and it's 0
  11492. } else if (num1.number === 1) {
  11493. return num2; // and it's 1
  11494. }
  11495. }
  11496. var min = Math.min(num1.min * num2.min, num1.min * num2.max,
  11497. num1.max * num2.min, num1.max * num2.max);
  11498. var max = Math.max(num1.min * num2.min, num1.min * num2.max,
  11499. num1.max * num2.min, num1.max * num2.max);
  11500. return new AstBinaryOperation('*', num1, num2, min, max);
  11501. }
  11502. function buildSubOperation(num1, num2) {
  11503. if (num2.type === 'literal') {
  11504. // optimization: second operands is a literal...
  11505. if (num2.number === 0) {
  11506. return num1; // ... and it's 0
  11507. } else if (num1.type === 'literal') {
  11508. // ... and first operands is a literal too
  11509. return new AstLiteral(num1.number - num2.number);
  11510. }
  11511. }
  11512. if (num2.type === 'binary' && num2.op === '-' &&
  11513. num1.type === 'literal' && num1.number === 1 &&
  11514. num2.arg1.type === 'literal' && num2.arg1.number === 1) {
  11515. // optimization for case: 1 - (1 - x)
  11516. return num2.arg2;
  11517. }
  11518. return new AstBinaryOperation('-', num1, num2,
  11519. num1.min - num2.max, num1.max - num2.min);
  11520. }
  11521. function buildMinOperation(num1, max) {
  11522. if (num1.min >= max) {
  11523. // optimization: num1 min value is not less than required max
  11524. return new AstLiteral(max); // just returning max
  11525. } else if (num1.max <= max) {
  11526. // optimization: num1 max value is not greater than required max
  11527. return num1; // just returning an argument
  11528. }
  11529. return new AstMin(num1, max);
  11530. }
  11531. function PostScriptCompiler() {}
  11532. PostScriptCompiler.prototype = {
  11533. compile: function PostScriptCompiler_compile(code, domain, range) {
  11534. var stack = [];
  11535. var i, ii;
  11536. var instructions = [];
  11537. var inputSize = domain.length >> 1, outputSize = range.length >> 1;
  11538. var lastRegister = 0;
  11539. var n, j, min, max;
  11540. var num1, num2, ast1, ast2, tmpVar, item;
  11541. for (i = 0; i < inputSize; i++) {
  11542. stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
  11543. }
  11544. for (i = 0, ii = code.length; i < ii; i++) {
  11545. item = code[i];
  11546. if (typeof item === 'number') {
  11547. stack.push(new AstLiteral(item));
  11548. continue;
  11549. }
  11550. switch (item) {
  11551. case 'add':
  11552. if (stack.length < 2) {
  11553. return null;
  11554. }
  11555. num2 = stack.pop();
  11556. num1 = stack.pop();
  11557. stack.push(buildAddOperation(num1, num2));
  11558. break;
  11559. case 'cvr':
  11560. if (stack.length < 1) {
  11561. return null;
  11562. }
  11563. break;
  11564. case 'mul':
  11565. if (stack.length < 2) {
  11566. return null;
  11567. }
  11568. num2 = stack.pop();
  11569. num1 = stack.pop();
  11570. stack.push(buildMulOperation(num1, num2));
  11571. break;
  11572. case 'sub':
  11573. if (stack.length < 2) {
  11574. return null;
  11575. }
  11576. num2 = stack.pop();
  11577. num1 = stack.pop();
  11578. stack.push(buildSubOperation(num1, num2));
  11579. break;
  11580. case 'exch':
  11581. if (stack.length < 2) {
  11582. return null;
  11583. }
  11584. ast1 = stack.pop(); ast2 = stack.pop();
  11585. stack.push(ast1, ast2);
  11586. break;
  11587. case 'pop':
  11588. if (stack.length < 1) {
  11589. return null;
  11590. }
  11591. stack.pop();
  11592. break;
  11593. case 'index':
  11594. if (stack.length < 1) {
  11595. return null;
  11596. }
  11597. num1 = stack.pop();
  11598. if (num1.type !== 'literal') {
  11599. return null;
  11600. }
  11601. n = num1.number;
  11602. if (n < 0 || (n|0) !== n || stack.length < n) {
  11603. return null;
  11604. }
  11605. ast1 = stack[stack.length - n - 1];
  11606. if (ast1.type === 'literal' || ast1.type === 'var') {
  11607. stack.push(ast1);
  11608. break;
  11609. }
  11610. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  11611. stack[stack.length - n - 1] = tmpVar;
  11612. stack.push(tmpVar);
  11613. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  11614. break;
  11615. case 'dup':
  11616. if (stack.length < 1) {
  11617. return null;
  11618. }
  11619. if (typeof code[i + 1] === 'number' && code[i + 2] === 'gt' &&
  11620. code[i + 3] === i + 7 && code[i + 4] === 'jz' &&
  11621. code[i + 5] === 'pop' && code[i + 6] === code[i + 1]) {
  11622. // special case of the commands sequence for the min operation
  11623. num1 = stack.pop();
  11624. stack.push(buildMinOperation(num1, code[i + 1]));
  11625. i += 6;
  11626. break;
  11627. }
  11628. ast1 = stack[stack.length - 1];
  11629. if (ast1.type === 'literal' || ast1.type === 'var') {
  11630. // we don't have to save into intermediate variable a literal or
  11631. // variable.
  11632. stack.push(ast1);
  11633. break;
  11634. }
  11635. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  11636. stack[stack.length - 1] = tmpVar;
  11637. stack.push(tmpVar);
  11638. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  11639. break;
  11640. case 'roll':
  11641. if (stack.length < 2) {
  11642. return null;
  11643. }
  11644. num2 = stack.pop();
  11645. num1 = stack.pop();
  11646. if (num2.type !== 'literal' || num1.type !== 'literal') {
  11647. // both roll operands must be numbers
  11648. return null;
  11649. }
  11650. j = num2.number;
  11651. n = num1.number;
  11652. if (n <= 0 || (n|0) !== n || (j|0) !== j || stack.length < n) {
  11653. // ... and integers
  11654. return null;
  11655. }
  11656. j = ((j % n) + n) % n;
  11657. if (j === 0) {
  11658. break; // just skipping -- there are nothing to rotate
  11659. }
  11660. Array.prototype.push.apply(stack,
  11661. stack.splice(stack.length - n, n - j));
  11662. break;
  11663. default:
  11664. return null; // unsupported operator
  11665. }
  11666. }
  11667. if (stack.length !== outputSize) {
  11668. return null;
  11669. }
  11670. var result = [];
  11671. instructions.forEach(function (instruction) {
  11672. var statementBuilder = new ExpressionBuilderVisitor();
  11673. instruction.visit(statementBuilder);
  11674. result.push(statementBuilder.toString());
  11675. });
  11676. stack.forEach(function (expr, i) {
  11677. var statementBuilder = new ExpressionBuilderVisitor();
  11678. expr.visit(statementBuilder);
  11679. var min = range[i * 2], max = range[i * 2 + 1];
  11680. var out = [statementBuilder.toString()];
  11681. if (min > expr.min) {
  11682. out.unshift('Math.max(', min, ', ');
  11683. out.push(')');
  11684. }
  11685. if (max < expr.max) {
  11686. out.unshift('Math.min(', max, ', ');
  11687. out.push(')');
  11688. }
  11689. out.unshift('dest[destOffset + ', i, '] = ');
  11690. out.push(';');
  11691. result.push(out.join(''));
  11692. });
  11693. return result.join('\n');
  11694. }
  11695. };
  11696. return PostScriptCompiler;
  11697. })();
  11698. var ColorSpace = (function ColorSpaceClosure() {
  11699. // Constructor should define this.numComps, this.defaultColor, this.name
  11700. function ColorSpace() {
  11701. error('should not call ColorSpace constructor');
  11702. }
  11703. ColorSpace.prototype = {
  11704. /**
  11705. * Converts the color value to the RGB color. The color components are
  11706. * located in the src array starting from the srcOffset. Returns the array
  11707. * of the rgb components, each value ranging from [0,255].
  11708. */
  11709. getRgb: function ColorSpace_getRgb(src, srcOffset) {
  11710. var rgb = new Uint8Array(3);
  11711. this.getRgbItem(src, srcOffset, rgb, 0);
  11712. return rgb;
  11713. },
  11714. /**
  11715. * Converts the color value to the RGB color, similar to the getRgb method.
  11716. * The result placed into the dest array starting from the destOffset.
  11717. */
  11718. getRgbItem: function ColorSpace_getRgbItem(src, srcOffset,
  11719. dest, destOffset) {
  11720. error('Should not call ColorSpace.getRgbItem');
  11721. },
  11722. /**
  11723. * Converts the specified number of the color values to the RGB colors.
  11724. * The colors are located in the src array starting from the srcOffset.
  11725. * The result is placed into the dest array starting from the destOffset.
  11726. * The src array items shall be in [0,2^bits) range, the dest array items
  11727. * will be in [0,255] range. alpha01 indicates how many alpha components
  11728. * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA
  11729. * array).
  11730. */
  11731. getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,
  11732. dest, destOffset, bits,
  11733. alpha01) {
  11734. error('Should not call ColorSpace.getRgbBuffer');
  11735. },
  11736. /**
  11737. * Determines the number of bytes required to store the result of the
  11738. * conversion done by the getRgbBuffer method. As in getRgbBuffer,
  11739. * |alpha01| is either 0 (RGB output) or 1 (RGBA output).
  11740. */
  11741. getOutputLength: function ColorSpace_getOutputLength(inputLength,
  11742. alpha01) {
  11743. error('Should not call ColorSpace.getOutputLength');
  11744. },
  11745. /**
  11746. * Returns true if source data will be equal the result/output data.
  11747. */
  11748. isPassthrough: function ColorSpace_isPassthrough(bits) {
  11749. return false;
  11750. },
  11751. /**
  11752. * Fills in the RGB colors in the destination buffer. alpha01 indicates
  11753. * how many alpha components there are in the dest array; it will be either
  11754. * 0 (RGB array) or 1 (RGBA array).
  11755. */
  11756. fillRgb: function ColorSpace_fillRgb(dest, originalWidth,
  11757. originalHeight, width, height,
  11758. actualHeight, bpc, comps, alpha01) {
  11759. var count = originalWidth * originalHeight;
  11760. var rgbBuf = null;
  11761. var numComponentColors = 1 << bpc;
  11762. var needsResizing = originalHeight !== height || originalWidth !== width;
  11763. var i, ii;
  11764. if (this.isPassthrough(bpc)) {
  11765. rgbBuf = comps;
  11766. } else if (this.numComps === 1 && count > numComponentColors &&
  11767. this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {
  11768. // Optimization: create a color map when there is just one component and
  11769. // we are converting more colors than the size of the color map. We
  11770. // don't build the map if the colorspace is gray or rgb since those
  11771. // methods are faster than building a map. This mainly offers big speed
  11772. // ups for indexed and alternate colorspaces.
  11773. //
  11774. // TODO it may be worth while to cache the color map. While running
  11775. // testing I never hit a cache so I will leave that out for now (perhaps
  11776. // we are reparsing colorspaces too much?).
  11777. var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) :
  11778. new Uint16Array(numComponentColors);
  11779. var key;
  11780. for (i = 0; i < numComponentColors; i++) {
  11781. allColors[i] = i;
  11782. }
  11783. var colorMap = new Uint8Array(numComponentColors * 3);
  11784. this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,
  11785. /* alpha01 = */ 0);
  11786. var destPos, rgbPos;
  11787. if (!needsResizing) {
  11788. // Fill in the RGB values directly into |dest|.
  11789. destPos = 0;
  11790. for (i = 0; i < count; ++i) {
  11791. key = comps[i] * 3;
  11792. dest[destPos++] = colorMap[key];
  11793. dest[destPos++] = colorMap[key + 1];
  11794. dest[destPos++] = colorMap[key + 2];
  11795. destPos += alpha01;
  11796. }
  11797. } else {
  11798. rgbBuf = new Uint8Array(count * 3);
  11799. rgbPos = 0;
  11800. for (i = 0; i < count; ++i) {
  11801. key = comps[i] * 3;
  11802. rgbBuf[rgbPos++] = colorMap[key];
  11803. rgbBuf[rgbPos++] = colorMap[key + 1];
  11804. rgbBuf[rgbPos++] = colorMap[key + 2];
  11805. }
  11806. }
  11807. } else {
  11808. if (!needsResizing) {
  11809. // Fill in the RGB values directly into |dest|.
  11810. this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc,
  11811. alpha01);
  11812. } else {
  11813. rgbBuf = new Uint8Array(count * 3);
  11814. this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc,
  11815. /* alpha01 = */ 0);
  11816. }
  11817. }
  11818. if (rgbBuf) {
  11819. if (needsResizing) {
  11820. PDFImage.resize(rgbBuf, bpc, 3, originalWidth, originalHeight, width,
  11821. height, dest, alpha01);
  11822. } else {
  11823. rgbPos = 0;
  11824. destPos = 0;
  11825. for (i = 0, ii = width * actualHeight; i < ii; i++) {
  11826. dest[destPos++] = rgbBuf[rgbPos++];
  11827. dest[destPos++] = rgbBuf[rgbPos++];
  11828. dest[destPos++] = rgbBuf[rgbPos++];
  11829. destPos += alpha01;
  11830. }
  11831. }
  11832. }
  11833. },
  11834. /**
  11835. * True if the colorspace has components in the default range of [0, 1].
  11836. * This should be true for all colorspaces except for lab color spaces
  11837. * which are [0,100], [-128, 127], [-128, 127].
  11838. */
  11839. usesZeroToOneRange: true
  11840. };
  11841. ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {
  11842. var IR = ColorSpace.parseToIR(cs, xref, res);
  11843. if (IR instanceof AlternateCS) {
  11844. return IR;
  11845. }
  11846. return ColorSpace.fromIR(IR);
  11847. };
  11848. ColorSpace.fromIR = function ColorSpace_fromIR(IR) {
  11849. var name = isArray(IR) ? IR[0] : IR;
  11850. var whitePoint, blackPoint, gamma;
  11851. switch (name) {
  11852. case 'DeviceGrayCS':
  11853. return this.singletons.gray;
  11854. case 'DeviceRgbCS':
  11855. return this.singletons.rgb;
  11856. case 'DeviceCmykCS':
  11857. return this.singletons.cmyk;
  11858. case 'CalGrayCS':
  11859. whitePoint = IR[1].WhitePoint;
  11860. blackPoint = IR[1].BlackPoint;
  11861. gamma = IR[1].Gamma;
  11862. return new CalGrayCS(whitePoint, blackPoint, gamma);
  11863. case 'CalRGBCS':
  11864. whitePoint = IR[1].WhitePoint;
  11865. blackPoint = IR[1].BlackPoint;
  11866. gamma = IR[1].Gamma;
  11867. var matrix = IR[1].Matrix;
  11868. return new CalRGBCS(whitePoint, blackPoint, gamma, matrix);
  11869. case 'PatternCS':
  11870. var basePatternCS = IR[1];
  11871. if (basePatternCS) {
  11872. basePatternCS = ColorSpace.fromIR(basePatternCS);
  11873. }
  11874. return new PatternCS(basePatternCS);
  11875. case 'IndexedCS':
  11876. var baseIndexedCS = IR[1];
  11877. var hiVal = IR[2];
  11878. var lookup = IR[3];
  11879. return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);
  11880. case 'AlternateCS':
  11881. var numComps = IR[1];
  11882. var alt = IR[2];
  11883. var tintFnIR = IR[3];
  11884. return new AlternateCS(numComps, ColorSpace.fromIR(alt),
  11885. PDFFunction.fromIR(tintFnIR));
  11886. case 'LabCS':
  11887. whitePoint = IR[1].WhitePoint;
  11888. blackPoint = IR[1].BlackPoint;
  11889. var range = IR[1].Range;
  11890. return new LabCS(whitePoint, blackPoint, range);
  11891. default:
  11892. error('Unknown name ' + name);
  11893. }
  11894. return null;
  11895. };
  11896. ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
  11897. if (isName(cs)) {
  11898. var colorSpaces = res.get('ColorSpace');
  11899. if (isDict(colorSpaces)) {
  11900. var refcs = colorSpaces.get(cs.name);
  11901. if (refcs) {
  11902. cs = refcs;
  11903. }
  11904. }
  11905. }
  11906. cs = xref.fetchIfRef(cs);
  11907. var mode;
  11908. if (isName(cs)) {
  11909. mode = cs.name;
  11910. this.mode = mode;
  11911. switch (mode) {
  11912. case 'DeviceGray':
  11913. case 'G':
  11914. return 'DeviceGrayCS';
  11915. case 'DeviceRGB':
  11916. case 'RGB':
  11917. return 'DeviceRgbCS';
  11918. case 'DeviceCMYK':
  11919. case 'CMYK':
  11920. return 'DeviceCmykCS';
  11921. case 'Pattern':
  11922. return ['PatternCS', null];
  11923. default:
  11924. error('unrecognized colorspace ' + mode);
  11925. }
  11926. } else if (isArray(cs)) {
  11927. mode = xref.fetchIfRef(cs[0]).name;
  11928. this.mode = mode;
  11929. var numComps, params, alt;
  11930. switch (mode) {
  11931. case 'DeviceGray':
  11932. case 'G':
  11933. return 'DeviceGrayCS';
  11934. case 'DeviceRGB':
  11935. case 'RGB':
  11936. return 'DeviceRgbCS';
  11937. case 'DeviceCMYK':
  11938. case 'CMYK':
  11939. return 'DeviceCmykCS';
  11940. case 'CalGray':
  11941. params = xref.fetchIfRef(cs[1]).getAll();
  11942. return ['CalGrayCS', params];
  11943. case 'CalRGB':
  11944. params = xref.fetchIfRef(cs[1]).getAll();
  11945. return ['CalRGBCS', params];
  11946. case 'ICCBased':
  11947. var stream = xref.fetchIfRef(cs[1]);
  11948. var dict = stream.dict;
  11949. numComps = dict.get('N');
  11950. alt = dict.get('Alternate');
  11951. if (alt) {
  11952. var altIR = ColorSpace.parseToIR(alt, xref, res);
  11953. // Parse the /Alternate CS to ensure that the number of components
  11954. // are correct, and also (indirectly) that it is not a PatternCS.
  11955. var altCS = ColorSpace.fromIR(altIR);
  11956. if (altCS.numComps === numComps) {
  11957. return altIR;
  11958. }
  11959. warn('ICCBased color space: Ignoring incorrect /Alternate entry.');
  11960. }
  11961. if (numComps === 1) {
  11962. return 'DeviceGrayCS';
  11963. } else if (numComps === 3) {
  11964. return 'DeviceRgbCS';
  11965. } else if (numComps === 4) {
  11966. return 'DeviceCmykCS';
  11967. }
  11968. break;
  11969. case 'Pattern':
  11970. var basePatternCS = cs[1] || null;
  11971. if (basePatternCS) {
  11972. basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);
  11973. }
  11974. return ['PatternCS', basePatternCS];
  11975. case 'Indexed':
  11976. case 'I':
  11977. var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);
  11978. var hiVal = xref.fetchIfRef(cs[2]) + 1;
  11979. var lookup = xref.fetchIfRef(cs[3]);
  11980. if (isStream(lookup)) {
  11981. lookup = lookup.getBytes();
  11982. }
  11983. return ['IndexedCS', baseIndexedCS, hiVal, lookup];
  11984. case 'Separation':
  11985. case 'DeviceN':
  11986. var name = xref.fetchIfRef(cs[1]);
  11987. numComps = 1;
  11988. if (isName(name)) {
  11989. numComps = 1;
  11990. } else if (isArray(name)) {
  11991. numComps = name.length;
  11992. }
  11993. alt = ColorSpace.parseToIR(cs[2], xref, res);
  11994. var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));
  11995. return ['AlternateCS', numComps, alt, tintFnIR];
  11996. case 'Lab':
  11997. params = xref.fetchIfRef(cs[1]).getAll();
  11998. return ['LabCS', params];
  11999. default:
  12000. error('unimplemented color space object "' + mode + '"');
  12001. }
  12002. } else {
  12003. error('unrecognized color space object: "' + cs + '"');
  12004. }
  12005. return null;
  12006. };
  12007. /**
  12008. * Checks if a decode map matches the default decode map for a color space.
  12009. * This handles the general decode maps where there are two values per
  12010. * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color.
  12011. * This does not handle Lab, Indexed, or Pattern decode maps since they are
  12012. * slightly different.
  12013. * @param {Array} decode Decode map (usually from an image).
  12014. * @param {Number} n Number of components the color space has.
  12015. */
  12016. ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {
  12017. if (!decode) {
  12018. return true;
  12019. }
  12020. if (n * 2 !== decode.length) {
  12021. warn('The decode map is not the correct length');
  12022. return true;
  12023. }
  12024. for (var i = 0, ii = decode.length; i < ii; i += 2) {
  12025. if (decode[i] !== 0 || decode[i + 1] !== 1) {
  12026. return false;
  12027. }
  12028. }
  12029. return true;
  12030. };
  12031. ColorSpace.singletons = {
  12032. get gray() {
  12033. return shadow(this, 'gray', new DeviceGrayCS());
  12034. },
  12035. get rgb() {
  12036. return shadow(this, 'rgb', new DeviceRgbCS());
  12037. },
  12038. get cmyk() {
  12039. return shadow(this, 'cmyk', new DeviceCmykCS());
  12040. }
  12041. };
  12042. return ColorSpace;
  12043. })();
  12044. /**
  12045. * Alternate color space handles both Separation and DeviceN color spaces. A
  12046. * Separation color space is actually just a DeviceN with one color component.
  12047. * Both color spaces use a tinting function to convert colors to a base color
  12048. * space.
  12049. */
  12050. var AlternateCS = (function AlternateCSClosure() {
  12051. function AlternateCS(numComps, base, tintFn) {
  12052. this.name = 'Alternate';
  12053. this.numComps = numComps;
  12054. this.defaultColor = new Float32Array(numComps);
  12055. for (var i = 0; i < numComps; ++i) {
  12056. this.defaultColor[i] = 1;
  12057. }
  12058. this.base = base;
  12059. this.tintFn = tintFn;
  12060. this.tmpBuf = new Float32Array(base.numComps);
  12061. }
  12062. AlternateCS.prototype = {
  12063. getRgb: ColorSpace.prototype.getRgb,
  12064. getRgbItem: function AlternateCS_getRgbItem(src, srcOffset,
  12065. dest, destOffset) {
  12066. var tmpBuf = this.tmpBuf;
  12067. this.tintFn(src, srcOffset, tmpBuf, 0);
  12068. this.base.getRgbItem(tmpBuf, 0, dest, destOffset);
  12069. },
  12070. getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count,
  12071. dest, destOffset, bits,
  12072. alpha01) {
  12073. var tintFn = this.tintFn;
  12074. var base = this.base;
  12075. var scale = 1 / ((1 << bits) - 1);
  12076. var baseNumComps = base.numComps;
  12077. var usesZeroToOneRange = base.usesZeroToOneRange;
  12078. var isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) &&
  12079. alpha01 === 0;
  12080. var pos = isPassthrough ? destOffset : 0;
  12081. var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count);
  12082. var numComps = this.numComps;
  12083. var scaled = new Float32Array(numComps);
  12084. var tinted = new Float32Array(baseNumComps);
  12085. var i, j;
  12086. if (usesZeroToOneRange) {
  12087. for (i = 0; i < count; i++) {
  12088. for (j = 0; j < numComps; j++) {
  12089. scaled[j] = src[srcOffset++] * scale;
  12090. }
  12091. tintFn(scaled, 0, tinted, 0);
  12092. for (j = 0; j < baseNumComps; j++) {
  12093. baseBuf[pos++] = tinted[j] * 255;
  12094. }
  12095. }
  12096. } else {
  12097. for (i = 0; i < count; i++) {
  12098. for (j = 0; j < numComps; j++) {
  12099. scaled[j] = src[srcOffset++] * scale;
  12100. }
  12101. tintFn(scaled, 0, tinted, 0);
  12102. base.getRgbItem(tinted, 0, baseBuf, pos);
  12103. pos += baseNumComps;
  12104. }
  12105. }
  12106. if (!isPassthrough) {
  12107. base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
  12108. }
  12109. },
  12110. getOutputLength: function AlternateCS_getOutputLength(inputLength,
  12111. alpha01) {
  12112. return this.base.getOutputLength(inputLength *
  12113. this.base.numComps / this.numComps,
  12114. alpha01);
  12115. },
  12116. isPassthrough: ColorSpace.prototype.isPassthrough,
  12117. fillRgb: ColorSpace.prototype.fillRgb,
  12118. isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {
  12119. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12120. },
  12121. usesZeroToOneRange: true
  12122. };
  12123. return AlternateCS;
  12124. })();
  12125. var PatternCS = (function PatternCSClosure() {
  12126. function PatternCS(baseCS) {
  12127. this.name = 'Pattern';
  12128. this.base = baseCS;
  12129. }
  12130. PatternCS.prototype = {};
  12131. return PatternCS;
  12132. })();
  12133. var IndexedCS = (function IndexedCSClosure() {
  12134. function IndexedCS(base, highVal, lookup) {
  12135. this.name = 'Indexed';
  12136. this.numComps = 1;
  12137. this.defaultColor = new Uint8Array([0]);
  12138. this.base = base;
  12139. this.highVal = highVal;
  12140. var baseNumComps = base.numComps;
  12141. var length = baseNumComps * highVal;
  12142. var lookupArray;
  12143. if (isStream(lookup)) {
  12144. lookupArray = new Uint8Array(length);
  12145. var bytes = lookup.getBytes(length);
  12146. lookupArray.set(bytes);
  12147. } else if (isString(lookup)) {
  12148. lookupArray = new Uint8Array(length);
  12149. for (var i = 0; i < length; ++i) {
  12150. lookupArray[i] = lookup.charCodeAt(i);
  12151. }
  12152. } else if (lookup instanceof Uint8Array || lookup instanceof Array) {
  12153. lookupArray = lookup;
  12154. } else {
  12155. error('Unrecognized lookup table: ' + lookup);
  12156. }
  12157. this.lookup = lookupArray;
  12158. }
  12159. IndexedCS.prototype = {
  12160. getRgb: ColorSpace.prototype.getRgb,
  12161. getRgbItem: function IndexedCS_getRgbItem(src, srcOffset,
  12162. dest, destOffset) {
  12163. var numComps = this.base.numComps;
  12164. var start = src[srcOffset] * numComps;
  12165. this.base.getRgbItem(this.lookup, start, dest, destOffset);
  12166. },
  12167. getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count,
  12168. dest, destOffset, bits,
  12169. alpha01) {
  12170. var base = this.base;
  12171. var numComps = base.numComps;
  12172. var outputDelta = base.getOutputLength(numComps, alpha01);
  12173. var lookup = this.lookup;
  12174. for (var i = 0; i < count; ++i) {
  12175. var lookupPos = src[srcOffset++] * numComps;
  12176. base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);
  12177. destOffset += outputDelta;
  12178. }
  12179. },
  12180. getOutputLength: function IndexedCS_getOutputLength(inputLength, alpha01) {
  12181. return this.base.getOutputLength(inputLength * this.base.numComps,
  12182. alpha01);
  12183. },
  12184. isPassthrough: ColorSpace.prototype.isPassthrough,
  12185. fillRgb: ColorSpace.prototype.fillRgb,
  12186. isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {
  12187. // indexed color maps shouldn't be changed
  12188. return true;
  12189. },
  12190. usesZeroToOneRange: true
  12191. };
  12192. return IndexedCS;
  12193. })();
  12194. var DeviceGrayCS = (function DeviceGrayCSClosure() {
  12195. function DeviceGrayCS() {
  12196. this.name = 'DeviceGray';
  12197. this.numComps = 1;
  12198. this.defaultColor = new Float32Array([0]);
  12199. }
  12200. DeviceGrayCS.prototype = {
  12201. getRgb: ColorSpace.prototype.getRgb,
  12202. getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset,
  12203. dest, destOffset) {
  12204. var c = (src[srcOffset] * 255) | 0;
  12205. c = c < 0 ? 0 : c > 255 ? 255 : c;
  12206. dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;
  12207. },
  12208. getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count,
  12209. dest, destOffset, bits,
  12210. alpha01) {
  12211. var scale = 255 / ((1 << bits) - 1);
  12212. var j = srcOffset, q = destOffset;
  12213. for (var i = 0; i < count; ++i) {
  12214. var c = (scale * src[j++]) | 0;
  12215. dest[q++] = c;
  12216. dest[q++] = c;
  12217. dest[q++] = c;
  12218. q += alpha01;
  12219. }
  12220. },
  12221. getOutputLength: function DeviceGrayCS_getOutputLength(inputLength,
  12222. alpha01) {
  12223. return inputLength * (3 + alpha01);
  12224. },
  12225. isPassthrough: ColorSpace.prototype.isPassthrough,
  12226. fillRgb: ColorSpace.prototype.fillRgb,
  12227. isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {
  12228. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12229. },
  12230. usesZeroToOneRange: true
  12231. };
  12232. return DeviceGrayCS;
  12233. })();
  12234. var DeviceRgbCS = (function DeviceRgbCSClosure() {
  12235. function DeviceRgbCS() {
  12236. this.name = 'DeviceRGB';
  12237. this.numComps = 3;
  12238. this.defaultColor = new Float32Array([0, 0, 0]);
  12239. }
  12240. DeviceRgbCS.prototype = {
  12241. getRgb: ColorSpace.prototype.getRgb,
  12242. getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset,
  12243. dest, destOffset) {
  12244. var r = (src[srcOffset] * 255) | 0;
  12245. var g = (src[srcOffset + 1] * 255) | 0;
  12246. var b = (src[srcOffset + 2] * 255) | 0;
  12247. dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r;
  12248. dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g;
  12249. dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b;
  12250. },
  12251. getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count,
  12252. dest, destOffset, bits,
  12253. alpha01) {
  12254. if (bits === 8 && alpha01 === 0) {
  12255. dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);
  12256. return;
  12257. }
  12258. var scale = 255 / ((1 << bits) - 1);
  12259. var j = srcOffset, q = destOffset;
  12260. for (var i = 0; i < count; ++i) {
  12261. dest[q++] = (scale * src[j++]) | 0;
  12262. dest[q++] = (scale * src[j++]) | 0;
  12263. dest[q++] = (scale * src[j++]) | 0;
  12264. q += alpha01;
  12265. }
  12266. },
  12267. getOutputLength: function DeviceRgbCS_getOutputLength(inputLength,
  12268. alpha01) {
  12269. return (inputLength * (3 + alpha01) / 3) | 0;
  12270. },
  12271. isPassthrough: function DeviceRgbCS_isPassthrough(bits) {
  12272. return bits === 8;
  12273. },
  12274. fillRgb: ColorSpace.prototype.fillRgb,
  12275. isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {
  12276. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12277. },
  12278. usesZeroToOneRange: true
  12279. };
  12280. return DeviceRgbCS;
  12281. })();
  12282. var DeviceCmykCS = (function DeviceCmykCSClosure() {
  12283. // The coefficients below was found using numerical analysis: the method of
  12284. // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,
  12285. // where color_value is the tabular value from the table of sampled RGB colors
  12286. // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding
  12287. // CMYK color conversion using the estimation below:
  12288. // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255
  12289. function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {
  12290. var c = src[srcOffset + 0] * srcScale;
  12291. var m = src[srcOffset + 1] * srcScale;
  12292. var y = src[srcOffset + 2] * srcScale;
  12293. var k = src[srcOffset + 3] * srcScale;
  12294. var r =
  12295. (c * (-4.387332384609988 * c + 54.48615194189176 * m +
  12296. 18.82290502165302 * y + 212.25662451639585 * k +
  12297. -285.2331026137004) +
  12298. m * (1.7149763477362134 * m - 5.6096736904047315 * y +
  12299. -17.873870861415444 * k - 5.497006427196366) +
  12300. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  12301. 17.5119270841813) +
  12302. k * (-21.86122147463605 * k - 189.48180835922747) + 255) | 0;
  12303. var g =
  12304. (c * (8.841041422036149 * c + 60.118027045597366 * m +
  12305. 6.871425592049007 * y + 31.159100130055922 * k +
  12306. -79.2970844816548) +
  12307. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  12308. 131.35250912493976 * k - 190.9453302588951) +
  12309. y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +
  12310. k * (-20.737325471181034 * k - 187.80453709719578) + 255) | 0;
  12311. var b =
  12312. (c * (0.8842522430003296 * c + 8.078677503112928 * m +
  12313. 30.89978309703729 * y - 0.23883238689178934 * k +
  12314. -14.183576799673286) +
  12315. m * (10.49593273432072 * m + 63.02378494754052 * y +
  12316. 50.606957656360734 * k - 112.23884253719248) +
  12317. y * (0.03296041114873217 * y + 115.60384449646641 * k +
  12318. -193.58209356861505) +
  12319. k * (-22.33816807309886 * k - 180.12613974708367) + 255) | 0;
  12320. dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r;
  12321. dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;
  12322. dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;
  12323. }
  12324. function DeviceCmykCS() {
  12325. this.name = 'DeviceCMYK';
  12326. this.numComps = 4;
  12327. this.defaultColor = new Float32Array([0, 0, 0, 1]);
  12328. }
  12329. DeviceCmykCS.prototype = {
  12330. getRgb: ColorSpace.prototype.getRgb,
  12331. getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset,
  12332. dest, destOffset) {
  12333. convertToRgb(src, srcOffset, 1, dest, destOffset);
  12334. },
  12335. getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count,
  12336. dest, destOffset, bits,
  12337. alpha01) {
  12338. var scale = 1 / ((1 << bits) - 1);
  12339. for (var i = 0; i < count; i++) {
  12340. convertToRgb(src, srcOffset, scale, dest, destOffset);
  12341. srcOffset += 4;
  12342. destOffset += 3 + alpha01;
  12343. }
  12344. },
  12345. getOutputLength: function DeviceCmykCS_getOutputLength(inputLength,
  12346. alpha01) {
  12347. return (inputLength / 4 * (3 + alpha01)) | 0;
  12348. },
  12349. isPassthrough: ColorSpace.prototype.isPassthrough,
  12350. fillRgb: ColorSpace.prototype.fillRgb,
  12351. isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {
  12352. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12353. },
  12354. usesZeroToOneRange: true
  12355. };
  12356. return DeviceCmykCS;
  12357. })();
  12358. //
  12359. // CalGrayCS: Based on "PDF Reference, Sixth Ed", p.245
  12360. //
  12361. var CalGrayCS = (function CalGrayCSClosure() {
  12362. function CalGrayCS(whitePoint, blackPoint, gamma) {
  12363. this.name = 'CalGray';
  12364. this.numComps = 1;
  12365. this.defaultColor = new Float32Array([0]);
  12366. if (!whitePoint) {
  12367. error('WhitePoint missing - required for color space CalGray');
  12368. }
  12369. blackPoint = blackPoint || [0, 0, 0];
  12370. gamma = gamma || 1;
  12371. // Translate arguments to spec variables.
  12372. this.XW = whitePoint[0];
  12373. this.YW = whitePoint[1];
  12374. this.ZW = whitePoint[2];
  12375. this.XB = blackPoint[0];
  12376. this.YB = blackPoint[1];
  12377. this.ZB = blackPoint[2];
  12378. this.G = gamma;
  12379. // Validate variables as per spec.
  12380. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  12381. error('Invalid WhitePoint components for ' + this.name +
  12382. ', no fallback available');
  12383. }
  12384. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  12385. info('Invalid BlackPoint for ' + this.name + ', falling back to default');
  12386. this.XB = this.YB = this.ZB = 0;
  12387. }
  12388. if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
  12389. warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB +
  12390. ', ZB: ' + this.ZB + ', only default values are supported.');
  12391. }
  12392. if (this.G < 1) {
  12393. info('Invalid Gamma: ' + this.G + ' for ' + this.name +
  12394. ', falling back to default');
  12395. this.G = 1;
  12396. }
  12397. }
  12398. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  12399. // A represents a gray component of a calibrated gray space.
  12400. // A <---> AG in the spec
  12401. var A = src[srcOffset] * scale;
  12402. var AG = Math.pow(A, cs.G);
  12403. // Computes L as per spec. ( = cs.YW * AG )
  12404. // Except if other than default BlackPoint values are used.
  12405. var L = cs.YW * AG;
  12406. // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4.
  12407. // Convert values to rgb range [0, 255].
  12408. var val = Math.max(295.8 * Math.pow(L, 0.333333333333333333) - 40.8, 0) | 0;
  12409. dest[destOffset] = val;
  12410. dest[destOffset + 1] = val;
  12411. dest[destOffset + 2] = val;
  12412. }
  12413. CalGrayCS.prototype = {
  12414. getRgb: ColorSpace.prototype.getRgb,
  12415. getRgbItem: function CalGrayCS_getRgbItem(src, srcOffset,
  12416. dest, destOffset) {
  12417. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  12418. },
  12419. getRgbBuffer: function CalGrayCS_getRgbBuffer(src, srcOffset, count,
  12420. dest, destOffset, bits,
  12421. alpha01) {
  12422. var scale = 1 / ((1 << bits) - 1);
  12423. for (var i = 0; i < count; ++i) {
  12424. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  12425. srcOffset += 1;
  12426. destOffset += 3 + alpha01;
  12427. }
  12428. },
  12429. getOutputLength: function CalGrayCS_getOutputLength(inputLength, alpha01) {
  12430. return inputLength * (3 + alpha01);
  12431. },
  12432. isPassthrough: ColorSpace.prototype.isPassthrough,
  12433. fillRgb: ColorSpace.prototype.fillRgb,
  12434. isDefaultDecode: function CalGrayCS_isDefaultDecode(decodeMap) {
  12435. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12436. },
  12437. usesZeroToOneRange: true
  12438. };
  12439. return CalGrayCS;
  12440. })();
  12441. //
  12442. // CalRGBCS: Based on "PDF Reference, Sixth Ed", p.247
  12443. //
  12444. var CalRGBCS = (function CalRGBCSClosure() {
  12445. // See http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html for these
  12446. // matrices.
  12447. var BRADFORD_SCALE_MATRIX = new Float32Array([
  12448. 0.8951, 0.2664, -0.1614,
  12449. -0.7502, 1.7135, 0.0367,
  12450. 0.0389, -0.0685, 1.0296]);
  12451. var BRADFORD_SCALE_INVERSE_MATRIX = new Float32Array([
  12452. 0.9869929, -0.1470543, 0.1599627,
  12453. 0.4323053, 0.5183603, 0.0492912,
  12454. -0.0085287, 0.0400428, 0.9684867]);
  12455. // See http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html.
  12456. var SRGB_D65_XYZ_TO_RGB_MATRIX = new Float32Array([
  12457. 3.2404542, -1.5371385, -0.4985314,
  12458. -0.9692660, 1.8760108, 0.0415560,
  12459. 0.0556434, -0.2040259, 1.0572252]);
  12460. var FLAT_WHITEPOINT_MATRIX = new Float32Array([1, 1, 1]);
  12461. var tempNormalizeMatrix = new Float32Array(3);
  12462. var tempConvertMatrix1 = new Float32Array(3);
  12463. var tempConvertMatrix2 = new Float32Array(3);
  12464. var DECODE_L_CONSTANT = Math.pow(((8 + 16) / 116), 3) / 8.0;
  12465. function CalRGBCS(whitePoint, blackPoint, gamma, matrix) {
  12466. this.name = 'CalRGB';
  12467. this.numComps = 3;
  12468. this.defaultColor = new Float32Array(3);
  12469. if (!whitePoint) {
  12470. error('WhitePoint missing - required for color space CalRGB');
  12471. }
  12472. blackPoint = blackPoint || new Float32Array(3);
  12473. gamma = gamma || new Float32Array([1, 1, 1]);
  12474. matrix = matrix || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  12475. // Translate arguments to spec variables.
  12476. var XW = whitePoint[0];
  12477. var YW = whitePoint[1];
  12478. var ZW = whitePoint[2];
  12479. this.whitePoint = whitePoint;
  12480. var XB = blackPoint[0];
  12481. var YB = blackPoint[1];
  12482. var ZB = blackPoint[2];
  12483. this.blackPoint = blackPoint;
  12484. this.GR = gamma[0];
  12485. this.GG = gamma[1];
  12486. this.GB = gamma[2];
  12487. this.MXA = matrix[0];
  12488. this.MYA = matrix[1];
  12489. this.MZA = matrix[2];
  12490. this.MXB = matrix[3];
  12491. this.MYB = matrix[4];
  12492. this.MZB = matrix[5];
  12493. this.MXC = matrix[6];
  12494. this.MYC = matrix[7];
  12495. this.MZC = matrix[8];
  12496. // Validate variables as per spec.
  12497. if (XW < 0 || ZW < 0 || YW !== 1) {
  12498. error('Invalid WhitePoint components for ' + this.name +
  12499. ', no fallback available');
  12500. }
  12501. if (XB < 0 || YB < 0 || ZB < 0) {
  12502. info('Invalid BlackPoint for ' + this.name + ' [' + XB + ', ' + YB +
  12503. ', ' + ZB + '], falling back to default');
  12504. this.blackPoint = new Float32Array(3);
  12505. }
  12506. if (this.GR < 0 || this.GG < 0 || this.GB < 0) {
  12507. info('Invalid Gamma [' + this.GR + ', ' + this.GG + ', ' + this.GB +
  12508. '] for ' + this.name + ', falling back to default');
  12509. this.GR = this.GG = this.GB = 1;
  12510. }
  12511. if (this.MXA < 0 || this.MYA < 0 || this.MZA < 0 ||
  12512. this.MXB < 0 || this.MYB < 0 || this.MZB < 0 ||
  12513. this.MXC < 0 || this.MYC < 0 || this.MZC < 0) {
  12514. info('Invalid Matrix for ' + this.name + ' [' +
  12515. this.MXA + ', ' + this.MYA + ', ' + this.MZA +
  12516. this.MXB + ', ' + this.MYB + ', ' + this.MZB +
  12517. this.MXC + ', ' + this.MYC + ', ' + this.MZC +
  12518. '], falling back to default');
  12519. this.MXA = this.MYB = this.MZC = 1;
  12520. this.MXB = this.MYA = this.MZA = this.MXC = this.MYC = this.MZB = 0;
  12521. }
  12522. }
  12523. function matrixProduct(a, b, result) {
  12524. result[0] = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  12525. result[1] = a[3] * b[0] + a[4] * b[1] + a[5] * b[2];
  12526. result[2] = a[6] * b[0] + a[7] * b[1] + a[8] * b[2];
  12527. }
  12528. function convertToFlat(sourceWhitePoint, LMS, result) {
  12529. result[0] = LMS[0] * 1 / sourceWhitePoint[0];
  12530. result[1] = LMS[1] * 1 / sourceWhitePoint[1];
  12531. result[2] = LMS[2] * 1 / sourceWhitePoint[2];
  12532. }
  12533. function convertToD65(sourceWhitePoint, LMS, result) {
  12534. var D65X = 0.95047;
  12535. var D65Y = 1;
  12536. var D65Z = 1.08883;
  12537. result[0] = LMS[0] * D65X / sourceWhitePoint[0];
  12538. result[1] = LMS[1] * D65Y / sourceWhitePoint[1];
  12539. result[2] = LMS[2] * D65Z / sourceWhitePoint[2];
  12540. }
  12541. function sRGBTransferFunction(color) {
  12542. // See http://en.wikipedia.org/wiki/SRGB.
  12543. if (color <= 0.0031308){
  12544. return adjustToRange(0, 1, 12.92 * color);
  12545. }
  12546. return adjustToRange(0, 1, (1 + 0.055) * Math.pow(color, 1 / 2.4) - 0.055);
  12547. }
  12548. function adjustToRange(min, max, value) {
  12549. return Math.max(min, Math.min(max, value));
  12550. }
  12551. function decodeL(L) {
  12552. if (L < 0) {
  12553. return -decodeL(-L);
  12554. }
  12555. if (L > 8.0) {
  12556. return Math.pow(((L + 16) / 116), 3);
  12557. }
  12558. return L * DECODE_L_CONSTANT;
  12559. }
  12560. function compensateBlackPoint(sourceBlackPoint, XYZ_Flat, result) {
  12561. // In case the blackPoint is already the default blackPoint then there is
  12562. // no need to do compensation.
  12563. if (sourceBlackPoint[0] === 0 &&
  12564. sourceBlackPoint[1] === 0 &&
  12565. sourceBlackPoint[2] === 0) {
  12566. result[0] = XYZ_Flat[0];
  12567. result[1] = XYZ_Flat[1];
  12568. result[2] = XYZ_Flat[2];
  12569. return;
  12570. }
  12571. // For the blackPoint calculation details, please see
  12572. // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
  12573. // AdobeBPC.pdf.
  12574. // The destination blackPoint is the default blackPoint [0, 0, 0].
  12575. var zeroDecodeL = decodeL(0);
  12576. var X_DST = zeroDecodeL;
  12577. var X_SRC = decodeL(sourceBlackPoint[0]);
  12578. var Y_DST = zeroDecodeL;
  12579. var Y_SRC = decodeL(sourceBlackPoint[1]);
  12580. var Z_DST = zeroDecodeL;
  12581. var Z_SRC = decodeL(sourceBlackPoint[2]);
  12582. var X_Scale = (1 - X_DST) / (1 - X_SRC);
  12583. var X_Offset = 1 - X_Scale;
  12584. var Y_Scale = (1 - Y_DST) / (1 - Y_SRC);
  12585. var Y_Offset = 1 - Y_Scale;
  12586. var Z_Scale = (1 - Z_DST) / (1 - Z_SRC);
  12587. var Z_Offset = 1 - Z_Scale;
  12588. result[0] = XYZ_Flat[0] * X_Scale + X_Offset;
  12589. result[1] = XYZ_Flat[1] * Y_Scale + Y_Offset;
  12590. result[2] = XYZ_Flat[2] * Z_Scale + Z_Offset;
  12591. }
  12592. function normalizeWhitePointToFlat(sourceWhitePoint, XYZ_In, result) {
  12593. // In case the whitePoint is already flat then there is no need to do
  12594. // normalization.
  12595. if (sourceWhitePoint[0] === 1 && sourceWhitePoint[2] === 1) {
  12596. result[0] = XYZ_In[0];
  12597. result[1] = XYZ_In[1];
  12598. result[2] = XYZ_In[2];
  12599. return;
  12600. }
  12601. var LMS = result;
  12602. matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
  12603. var LMS_Flat = tempNormalizeMatrix;
  12604. convertToFlat(sourceWhitePoint, LMS, LMS_Flat);
  12605. matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_Flat, result);
  12606. }
  12607. function normalizeWhitePointToD65(sourceWhitePoint, XYZ_In, result) {
  12608. var LMS = result;
  12609. matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
  12610. var LMS_D65 = tempNormalizeMatrix;
  12611. convertToD65(sourceWhitePoint, LMS, LMS_D65);
  12612. matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_D65, result);
  12613. }
  12614. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  12615. // A, B and C represent a red, green and blue components of a calibrated
  12616. // rgb space.
  12617. var A = adjustToRange(0, 1, src[srcOffset] * scale);
  12618. var B = adjustToRange(0, 1, src[srcOffset + 1] * scale);
  12619. var C = adjustToRange(0, 1, src[srcOffset + 2] * scale);
  12620. // A <---> AGR in the spec
  12621. // B <---> BGG in the spec
  12622. // C <---> CGB in the spec
  12623. var AGR = Math.pow(A, cs.GR);
  12624. var BGG = Math.pow(B, cs.GG);
  12625. var CGB = Math.pow(C, cs.GB);
  12626. // Computes intermediate variables L, M, N as per spec.
  12627. // To decode X, Y, Z values map L, M, N directly to them.
  12628. var X = cs.MXA * AGR + cs.MXB * BGG + cs.MXC * CGB;
  12629. var Y = cs.MYA * AGR + cs.MYB * BGG + cs.MYC * CGB;
  12630. var Z = cs.MZA * AGR + cs.MZB * BGG + cs.MZC * CGB;
  12631. // The following calculations are based on this document:
  12632. // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
  12633. // AdobeBPC.pdf.
  12634. var XYZ = tempConvertMatrix1;
  12635. XYZ[0] = X;
  12636. XYZ[1] = Y;
  12637. XYZ[2] = Z;
  12638. var XYZ_Flat = tempConvertMatrix2;
  12639. normalizeWhitePointToFlat(cs.whitePoint, XYZ, XYZ_Flat);
  12640. var XYZ_Black = tempConvertMatrix1;
  12641. compensateBlackPoint(cs.blackPoint, XYZ_Flat, XYZ_Black);
  12642. var XYZ_D65 = tempConvertMatrix2;
  12643. normalizeWhitePointToD65(FLAT_WHITEPOINT_MATRIX, XYZ_Black, XYZ_D65);
  12644. var SRGB = tempConvertMatrix1;
  12645. matrixProduct(SRGB_D65_XYZ_TO_RGB_MATRIX, XYZ_D65, SRGB);
  12646. var sR = sRGBTransferFunction(SRGB[0]);
  12647. var sG = sRGBTransferFunction(SRGB[1]);
  12648. var sB = sRGBTransferFunction(SRGB[2]);
  12649. // Convert the values to rgb range [0, 255].
  12650. dest[destOffset] = Math.round(sR * 255);
  12651. dest[destOffset + 1] = Math.round(sG * 255);
  12652. dest[destOffset + 2] = Math.round(sB * 255);
  12653. }
  12654. CalRGBCS.prototype = {
  12655. getRgb: function CalRGBCS_getRgb(src, srcOffset) {
  12656. var rgb = new Uint8Array(3);
  12657. this.getRgbItem(src, srcOffset, rgb, 0);
  12658. return rgb;
  12659. },
  12660. getRgbItem: function CalRGBCS_getRgbItem(src, srcOffset,
  12661. dest, destOffset) {
  12662. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  12663. },
  12664. getRgbBuffer: function CalRGBCS_getRgbBuffer(src, srcOffset, count,
  12665. dest, destOffset, bits,
  12666. alpha01) {
  12667. var scale = 1 / ((1 << bits) - 1);
  12668. for (var i = 0; i < count; ++i) {
  12669. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  12670. srcOffset += 3;
  12671. destOffset += 3 + alpha01;
  12672. }
  12673. },
  12674. getOutputLength: function CalRGBCS_getOutputLength(inputLength, alpha01) {
  12675. return (inputLength * (3 + alpha01) / 3) | 0;
  12676. },
  12677. isPassthrough: ColorSpace.prototype.isPassthrough,
  12678. fillRgb: ColorSpace.prototype.fillRgb,
  12679. isDefaultDecode: function CalRGBCS_isDefaultDecode(decodeMap) {
  12680. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12681. },
  12682. usesZeroToOneRange: true
  12683. };
  12684. return CalRGBCS;
  12685. })();
  12686. //
  12687. // LabCS: Based on "PDF Reference, Sixth Ed", p.250
  12688. //
  12689. var LabCS = (function LabCSClosure() {
  12690. function LabCS(whitePoint, blackPoint, range) {
  12691. this.name = 'Lab';
  12692. this.numComps = 3;
  12693. this.defaultColor = new Float32Array([0, 0, 0]);
  12694. if (!whitePoint) {
  12695. error('WhitePoint missing - required for color space Lab');
  12696. }
  12697. blackPoint = blackPoint || [0, 0, 0];
  12698. range = range || [-100, 100, -100, 100];
  12699. // Translate args to spec variables
  12700. this.XW = whitePoint[0];
  12701. this.YW = whitePoint[1];
  12702. this.ZW = whitePoint[2];
  12703. this.amin = range[0];
  12704. this.amax = range[1];
  12705. this.bmin = range[2];
  12706. this.bmax = range[3];
  12707. // These are here just for completeness - the spec doesn't offer any
  12708. // formulas that use BlackPoint in Lab
  12709. this.XB = blackPoint[0];
  12710. this.YB = blackPoint[1];
  12711. this.ZB = blackPoint[2];
  12712. // Validate vars as per spec
  12713. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  12714. error('Invalid WhitePoint components, no fallback available');
  12715. }
  12716. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  12717. info('Invalid BlackPoint, falling back to default');
  12718. this.XB = this.YB = this.ZB = 0;
  12719. }
  12720. if (this.amin > this.amax || this.bmin > this.bmax) {
  12721. info('Invalid Range, falling back to defaults');
  12722. this.amin = -100;
  12723. this.amax = 100;
  12724. this.bmin = -100;
  12725. this.bmax = 100;
  12726. }
  12727. }
  12728. // Function g(x) from spec
  12729. function fn_g(x) {
  12730. if (x >= 6 / 29) {
  12731. return x * x * x;
  12732. } else {
  12733. return (108 / 841) * (x - 4 / 29);
  12734. }
  12735. }
  12736. function decode(value, high1, low2, high2) {
  12737. return low2 + (value) * (high2 - low2) / (high1);
  12738. }
  12739. // If decoding is needed maxVal should be 2^bits per component - 1.
  12740. function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
  12741. // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]
  12742. // not the usual [0, 1]. If a command like setFillColor is used the src
  12743. // values will already be within the correct range. However, if we are
  12744. // converting an image we have to map the values to the correct range given
  12745. // above.
  12746. // Ls,as,bs <---> L*,a*,b* in the spec
  12747. var Ls = src[srcOffset];
  12748. var as = src[srcOffset + 1];
  12749. var bs = src[srcOffset + 2];
  12750. if (maxVal !== false) {
  12751. Ls = decode(Ls, maxVal, 0, 100);
  12752. as = decode(as, maxVal, cs.amin, cs.amax);
  12753. bs = decode(bs, maxVal, cs.bmin, cs.bmax);
  12754. }
  12755. // Adjust limits of 'as' and 'bs'
  12756. as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;
  12757. bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;
  12758. // Computes intermediate variables X,Y,Z as per spec
  12759. var M = (Ls + 16) / 116;
  12760. var L = M + (as / 500);
  12761. var N = M - (bs / 200);
  12762. var X = cs.XW * fn_g(L);
  12763. var Y = cs.YW * fn_g(M);
  12764. var Z = cs.ZW * fn_g(N);
  12765. var r, g, b;
  12766. // Using different conversions for D50 and D65 white points,
  12767. // per http://www.color.org/srgb.pdf
  12768. if (cs.ZW < 1) {
  12769. // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)
  12770. r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;
  12771. g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;
  12772. b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;
  12773. } else {
  12774. // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)
  12775. r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
  12776. g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
  12777. b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;
  12778. }
  12779. // clamp color values to [0,1] range then convert to [0,255] range.
  12780. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0;
  12781. dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0;
  12782. dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0;
  12783. }
  12784. LabCS.prototype = {
  12785. getRgb: ColorSpace.prototype.getRgb,
  12786. getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) {
  12787. convertToRgb(this, src, srcOffset, false, dest, destOffset);
  12788. },
  12789. getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count,
  12790. dest, destOffset, bits,
  12791. alpha01) {
  12792. var maxVal = (1 << bits) - 1;
  12793. for (var i = 0; i < count; i++) {
  12794. convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);
  12795. srcOffset += 3;
  12796. destOffset += 3 + alpha01;
  12797. }
  12798. },
  12799. getOutputLength: function LabCS_getOutputLength(inputLength, alpha01) {
  12800. return (inputLength * (3 + alpha01) / 3) | 0;
  12801. },
  12802. isPassthrough: ColorSpace.prototype.isPassthrough,
  12803. fillRgb: ColorSpace.prototype.fillRgb,
  12804. isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {
  12805. // XXX: Decoding is handled with the lab conversion because of the strange
  12806. // ranges that are used.
  12807. return true;
  12808. },
  12809. usesZeroToOneRange: false
  12810. };
  12811. return LabCS;
  12812. })();
  12813. var ARCFourCipher = (function ARCFourCipherClosure() {
  12814. function ARCFourCipher(key) {
  12815. this.a = 0;
  12816. this.b = 0;
  12817. var s = new Uint8Array(256);
  12818. var i, j = 0, tmp, keyLength = key.length;
  12819. for (i = 0; i < 256; ++i) {
  12820. s[i] = i;
  12821. }
  12822. for (i = 0; i < 256; ++i) {
  12823. tmp = s[i];
  12824. j = (j + tmp + key[i % keyLength]) & 0xFF;
  12825. s[i] = s[j];
  12826. s[j] = tmp;
  12827. }
  12828. this.s = s;
  12829. }
  12830. ARCFourCipher.prototype = {
  12831. encryptBlock: function ARCFourCipher_encryptBlock(data) {
  12832. var i, n = data.length, tmp, tmp2;
  12833. var a = this.a, b = this.b, s = this.s;
  12834. var output = new Uint8Array(n);
  12835. for (i = 0; i < n; ++i) {
  12836. a = (a + 1) & 0xFF;
  12837. tmp = s[a];
  12838. b = (b + tmp) & 0xFF;
  12839. tmp2 = s[b];
  12840. s[a] = tmp2;
  12841. s[b] = tmp;
  12842. output[i] = data[i] ^ s[(tmp + tmp2) & 0xFF];
  12843. }
  12844. this.a = a;
  12845. this.b = b;
  12846. return output;
  12847. }
  12848. };
  12849. ARCFourCipher.prototype.decryptBlock = ARCFourCipher.prototype.encryptBlock;
  12850. return ARCFourCipher;
  12851. })();
  12852. var calculateMD5 = (function calculateMD5Closure() {
  12853. var r = new Uint8Array([
  12854. 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  12855. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  12856. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  12857. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
  12858. var k = new Int32Array([
  12859. -680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426,
  12860. -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162,
  12861. 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632,
  12862. 643717713, -373897302, -701558691, 38016083, -660478335, -405537848,
  12863. 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784,
  12864. 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556,
  12865. -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222,
  12866. -722521979, 76029189, -640364487, -421815835, 530742520, -995338651,
  12867. -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606,
  12868. -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649,
  12869. -145523070, -1120210379, 718787259, -343485551]);
  12870. function hash(data, offset, length) {
  12871. var h0 = 1732584193, h1 = -271733879, h2 = -1732584194, h3 = 271733878;
  12872. // pre-processing
  12873. var paddedLength = (length + 72) & ~63; // data + 9 extra bytes
  12874. var padded = new Uint8Array(paddedLength);
  12875. var i, j, n;
  12876. for (i = 0; i < length; ++i) {
  12877. padded[i] = data[offset++];
  12878. }
  12879. padded[i++] = 0x80;
  12880. n = paddedLength - 8;
  12881. while (i < n) {
  12882. padded[i++] = 0;
  12883. }
  12884. padded[i++] = (length << 3) & 0xFF;
  12885. padded[i++] = (length >> 5) & 0xFF;
  12886. padded[i++] = (length >> 13) & 0xFF;
  12887. padded[i++] = (length >> 21) & 0xFF;
  12888. padded[i++] = (length >>> 29) & 0xFF;
  12889. padded[i++] = 0;
  12890. padded[i++] = 0;
  12891. padded[i++] = 0;
  12892. var w = new Int32Array(16);
  12893. for (i = 0; i < paddedLength;) {
  12894. for (j = 0; j < 16; ++j, i += 4) {
  12895. w[j] = (padded[i] | (padded[i + 1] << 8) |
  12896. (padded[i + 2] << 16) | (padded[i + 3] << 24));
  12897. }
  12898. var a = h0, b = h1, c = h2, d = h3, f, g;
  12899. for (j = 0; j < 64; ++j) {
  12900. if (j < 16) {
  12901. f = (b & c) | ((~b) & d);
  12902. g = j;
  12903. } else if (j < 32) {
  12904. f = (d & b) | ((~d) & c);
  12905. g = (5 * j + 1) & 15;
  12906. } else if (j < 48) {
  12907. f = b ^ c ^ d;
  12908. g = (3 * j + 5) & 15;
  12909. } else {
  12910. f = c ^ (b | (~d));
  12911. g = (7 * j) & 15;
  12912. }
  12913. var tmp = d, rotateArg = (a + f + k[j] + w[g]) | 0, rotate = r[j];
  12914. d = c;
  12915. c = b;
  12916. b = (b + ((rotateArg << rotate) | (rotateArg >>> (32 - rotate)))) | 0;
  12917. a = tmp;
  12918. }
  12919. h0 = (h0 + a) | 0;
  12920. h1 = (h1 + b) | 0;
  12921. h2 = (h2 + c) | 0;
  12922. h3 = (h3 + d) | 0;
  12923. }
  12924. return new Uint8Array([
  12925. h0 & 0xFF, (h0 >> 8) & 0xFF, (h0 >> 16) & 0xFF, (h0 >>> 24) & 0xFF,
  12926. h1 & 0xFF, (h1 >> 8) & 0xFF, (h1 >> 16) & 0xFF, (h1 >>> 24) & 0xFF,
  12927. h2 & 0xFF, (h2 >> 8) & 0xFF, (h2 >> 16) & 0xFF, (h2 >>> 24) & 0xFF,
  12928. h3 & 0xFF, (h3 >> 8) & 0xFF, (h3 >> 16) & 0xFF, (h3 >>> 24) & 0xFF
  12929. ]);
  12930. }
  12931. return hash;
  12932. })();
  12933. var Word64 = (function Word64Closure() {
  12934. function Word64(highInteger, lowInteger) {
  12935. this.high = highInteger | 0;
  12936. this.low = lowInteger | 0;
  12937. }
  12938. Word64.prototype = {
  12939. and: function Word64_and(word) {
  12940. this.high &= word.high;
  12941. this.low &= word.low;
  12942. },
  12943. xor: function Word64_xor(word) {
  12944. this.high ^= word.high;
  12945. this.low ^= word.low;
  12946. },
  12947. or: function Word64_or(word) {
  12948. this.high |= word.high;
  12949. this.low |= word.low;
  12950. },
  12951. shiftRight: function Word64_shiftRight(places) {
  12952. if (places >= 32) {
  12953. this.low = (this.high >>> (places - 32)) | 0;
  12954. this.high = 0;
  12955. } else {
  12956. this.low = (this.low >>> places) | (this.high << (32 - places));
  12957. this.high = (this.high >>> places) | 0;
  12958. }
  12959. },
  12960. shiftLeft: function Word64_shiftLeft(places) {
  12961. if (places >= 32) {
  12962. this.high = this.low << (places - 32);
  12963. this.low = 0;
  12964. } else {
  12965. this.high = (this.high << places) | (this.low >>> (32 - places));
  12966. this.low = this.low << places;
  12967. }
  12968. },
  12969. rotateRight: function Word64_rotateRight(places) {
  12970. var low, high;
  12971. if (places & 32) {
  12972. high = this.low;
  12973. low = this.high;
  12974. } else {
  12975. low = this.low;
  12976. high = this.high;
  12977. }
  12978. places &= 31;
  12979. this.low = (low >>> places) | (high << (32 - places));
  12980. this.high = (high >>> places) | (low << (32 - places));
  12981. },
  12982. not: function Word64_not() {
  12983. this.high = ~this.high;
  12984. this.low = ~this.low;
  12985. },
  12986. add: function Word64_add(word) {
  12987. var lowAdd = (this.low >>> 0) + (word.low >>> 0);
  12988. var highAdd = (this.high >>> 0) + (word.high >>> 0);
  12989. if (lowAdd > 0xFFFFFFFF) {
  12990. highAdd += 1;
  12991. }
  12992. this.low = lowAdd | 0;
  12993. this.high = highAdd | 0;
  12994. },
  12995. copyTo: function Word64_copyTo(bytes, offset) {
  12996. bytes[offset] = (this.high >>> 24) & 0xFF;
  12997. bytes[offset + 1] = (this.high >> 16) & 0xFF;
  12998. bytes[offset + 2] = (this.high >> 8) & 0xFF;
  12999. bytes[offset + 3] = this.high & 0xFF;
  13000. bytes[offset + 4] = (this.low >>> 24) & 0xFF;
  13001. bytes[offset + 5] = (this.low >> 16) & 0xFF;
  13002. bytes[offset + 6] = (this.low >> 8) & 0xFF;
  13003. bytes[offset + 7] = this.low & 0xFF;
  13004. },
  13005. assign: function Word64_assign(word) {
  13006. this.high = word.high;
  13007. this.low = word.low;
  13008. }
  13009. };
  13010. return Word64;
  13011. })();
  13012. var calculateSHA256 = (function calculateSHA256Closure() {
  13013. function rotr(x, n) {
  13014. return (x >>> n) | (x << 32 - n);
  13015. }
  13016. function ch(x, y, z) {
  13017. return (x & y) ^ (~x & z);
  13018. }
  13019. function maj(x, y, z) {
  13020. return (x & y) ^ (x & z) ^ (y & z);
  13021. }
  13022. function sigma(x) {
  13023. return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
  13024. }
  13025. function sigmaPrime(x) {
  13026. return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
  13027. }
  13028. function littleSigma(x) {
  13029. return rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3;
  13030. }
  13031. function littleSigmaPrime(x) {
  13032. return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10;
  13033. }
  13034. var k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  13035. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  13036. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  13037. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  13038. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  13039. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  13040. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  13041. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  13042. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  13043. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  13044. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  13045. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  13046. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  13047. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  13048. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  13049. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
  13050. function hash(data, offset, length) {
  13051. // initial hash values
  13052. var h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372,
  13053. h3 = 0xa54ff53a, h4 = 0x510e527f, h5 = 0x9b05688c,
  13054. h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
  13055. // pre-processing
  13056. var paddedLength = Math.ceil((length + 9) / 64) * 64;
  13057. var padded = new Uint8Array(paddedLength);
  13058. var i, j, n;
  13059. for (i = 0; i < length; ++i) {
  13060. padded[i] = data[offset++];
  13061. }
  13062. padded[i++] = 0x80;
  13063. n = paddedLength - 8;
  13064. while (i < n) {
  13065. padded[i++] = 0;
  13066. }
  13067. padded[i++] = 0;
  13068. padded[i++] = 0;
  13069. padded[i++] = 0;
  13070. padded[i++] = (length >>> 29) & 0xFF;
  13071. padded[i++] = (length >> 21) & 0xFF;
  13072. padded[i++] = (length >> 13) & 0xFF;
  13073. padded[i++] = (length >> 5) & 0xFF;
  13074. padded[i++] = (length << 3) & 0xFF;
  13075. var w = new Uint32Array(64);
  13076. // for each 512 bit block
  13077. for (i = 0; i < paddedLength;) {
  13078. for (j = 0; j < 16; ++j) {
  13079. w[j] = (padded[i] << 24 | (padded[i + 1] << 16) |
  13080. (padded[i + 2] << 8) | (padded[i + 3]));
  13081. i += 4;
  13082. }
  13083. for (j = 16; j < 64; ++j) {
  13084. w[j] = littleSigmaPrime(w[j - 2]) + w[j - 7] +
  13085. littleSigma(w[j - 15]) + w[j - 16] | 0;
  13086. }
  13087. var a = h0, b = h1, c = h2, d = h3, e = h4,
  13088. f = h5, g = h6, h = h7, t1, t2;
  13089. for (j = 0; j < 64; ++j) {
  13090. t1 = h + sigmaPrime(e) + ch(e, f, g) + k[j] + w[j];
  13091. t2 = sigma(a) + maj(a, b, c);
  13092. h = g;
  13093. g = f;
  13094. f = e;
  13095. e = (d + t1) | 0;
  13096. d = c;
  13097. c = b;
  13098. b = a;
  13099. a = (t1 + t2) | 0;
  13100. }
  13101. h0 = (h0 + a) | 0;
  13102. h1 = (h1 + b) | 0;
  13103. h2 = (h2 + c) | 0;
  13104. h3 = (h3 + d) | 0;
  13105. h4 = (h4 + e) | 0;
  13106. h5 = (h5 + f) | 0;
  13107. h6 = (h6 + g) | 0;
  13108. h7 = (h7 + h) | 0;
  13109. }
  13110. return new Uint8Array([
  13111. (h0 >> 24) & 0xFF, (h0 >> 16) & 0xFF, (h0 >> 8) & 0xFF, (h0) & 0xFF,
  13112. (h1 >> 24) & 0xFF, (h1 >> 16) & 0xFF, (h1 >> 8) & 0xFF, (h1) & 0xFF,
  13113. (h2 >> 24) & 0xFF, (h2 >> 16) & 0xFF, (h2 >> 8) & 0xFF, (h2) & 0xFF,
  13114. (h3 >> 24) & 0xFF, (h3 >> 16) & 0xFF, (h3 >> 8) & 0xFF, (h3) & 0xFF,
  13115. (h4 >> 24) & 0xFF, (h4 >> 16) & 0xFF, (h4 >> 8) & 0xFF, (h4) & 0xFF,
  13116. (h5 >> 24) & 0xFF, (h5 >> 16) & 0xFF, (h5 >> 8) & 0xFF, (h5) & 0xFF,
  13117. (h6 >> 24) & 0xFF, (h6 >> 16) & 0xFF, (h6 >> 8) & 0xFF, (h6) & 0xFF,
  13118. (h7 >> 24) & 0xFF, (h7 >> 16) & 0xFF, (h7 >> 8) & 0xFF, (h7) & 0xFF
  13119. ]);
  13120. }
  13121. return hash;
  13122. })();
  13123. var calculateSHA512 = (function calculateSHA512Closure() {
  13124. function ch(result, x, y, z, tmp) {
  13125. result.assign(x);
  13126. result.and(y);
  13127. tmp.assign(x);
  13128. tmp.not();
  13129. tmp.and(z);
  13130. result.xor(tmp);
  13131. }
  13132. function maj(result, x, y, z, tmp) {
  13133. result.assign(x);
  13134. result.and(y);
  13135. tmp.assign(x);
  13136. tmp.and(z);
  13137. result.xor(tmp);
  13138. tmp.assign(y);
  13139. tmp.and(z);
  13140. result.xor(tmp);
  13141. }
  13142. function sigma(result, x, tmp) {
  13143. result.assign(x);
  13144. result.rotateRight(28);
  13145. tmp.assign(x);
  13146. tmp.rotateRight(34);
  13147. result.xor(tmp);
  13148. tmp.assign(x);
  13149. tmp.rotateRight(39);
  13150. result.xor(tmp);
  13151. }
  13152. function sigmaPrime(result, x, tmp) {
  13153. result.assign(x);
  13154. result.rotateRight(14);
  13155. tmp.assign(x);
  13156. tmp.rotateRight(18);
  13157. result.xor(tmp);
  13158. tmp.assign(x);
  13159. tmp.rotateRight(41);
  13160. result.xor(tmp);
  13161. }
  13162. function littleSigma(result, x, tmp) {
  13163. result.assign(x);
  13164. result.rotateRight(1);
  13165. tmp.assign(x);
  13166. tmp.rotateRight(8);
  13167. result.xor(tmp);
  13168. tmp.assign(x);
  13169. tmp.shiftRight(7);
  13170. result.xor(tmp);
  13171. }
  13172. function littleSigmaPrime(result, x, tmp) {
  13173. result.assign(x);
  13174. result.rotateRight(19);
  13175. tmp.assign(x);
  13176. tmp.rotateRight(61);
  13177. result.xor(tmp);
  13178. tmp.assign(x);
  13179. tmp.shiftRight(6);
  13180. result.xor(tmp);
  13181. }
  13182. var k = [
  13183. new Word64(0x428a2f98, 0xd728ae22), new Word64(0x71374491, 0x23ef65cd),
  13184. new Word64(0xb5c0fbcf, 0xec4d3b2f), new Word64(0xe9b5dba5, 0x8189dbbc),
  13185. new Word64(0x3956c25b, 0xf348b538), new Word64(0x59f111f1, 0xb605d019),
  13186. new Word64(0x923f82a4, 0xaf194f9b), new Word64(0xab1c5ed5, 0xda6d8118),
  13187. new Word64(0xd807aa98, 0xa3030242), new Word64(0x12835b01, 0x45706fbe),
  13188. new Word64(0x243185be, 0x4ee4b28c), new Word64(0x550c7dc3, 0xd5ffb4e2),
  13189. new Word64(0x72be5d74, 0xf27b896f), new Word64(0x80deb1fe, 0x3b1696b1),
  13190. new Word64(0x9bdc06a7, 0x25c71235), new Word64(0xc19bf174, 0xcf692694),
  13191. new Word64(0xe49b69c1, 0x9ef14ad2), new Word64(0xefbe4786, 0x384f25e3),
  13192. new Word64(0x0fc19dc6, 0x8b8cd5b5), new Word64(0x240ca1cc, 0x77ac9c65),
  13193. new Word64(0x2de92c6f, 0x592b0275), new Word64(0x4a7484aa, 0x6ea6e483),
  13194. new Word64(0x5cb0a9dc, 0xbd41fbd4), new Word64(0x76f988da, 0x831153b5),
  13195. new Word64(0x983e5152, 0xee66dfab), new Word64(0xa831c66d, 0x2db43210),
  13196. new Word64(0xb00327c8, 0x98fb213f), new Word64(0xbf597fc7, 0xbeef0ee4),
  13197. new Word64(0xc6e00bf3, 0x3da88fc2), new Word64(0xd5a79147, 0x930aa725),
  13198. new Word64(0x06ca6351, 0xe003826f), new Word64(0x14292967, 0x0a0e6e70),
  13199. new Word64(0x27b70a85, 0x46d22ffc), new Word64(0x2e1b2138, 0x5c26c926),
  13200. new Word64(0x4d2c6dfc, 0x5ac42aed), new Word64(0x53380d13, 0x9d95b3df),
  13201. new Word64(0x650a7354, 0x8baf63de), new Word64(0x766a0abb, 0x3c77b2a8),
  13202. new Word64(0x81c2c92e, 0x47edaee6), new Word64(0x92722c85, 0x1482353b),
  13203. new Word64(0xa2bfe8a1, 0x4cf10364), new Word64(0xa81a664b, 0xbc423001),
  13204. new Word64(0xc24b8b70, 0xd0f89791), new Word64(0xc76c51a3, 0x0654be30),
  13205. new Word64(0xd192e819, 0xd6ef5218), new Word64(0xd6990624, 0x5565a910),
  13206. new Word64(0xf40e3585, 0x5771202a), new Word64(0x106aa070, 0x32bbd1b8),
  13207. new Word64(0x19a4c116, 0xb8d2d0c8), new Word64(0x1e376c08, 0x5141ab53),
  13208. new Word64(0x2748774c, 0xdf8eeb99), new Word64(0x34b0bcb5, 0xe19b48a8),
  13209. new Word64(0x391c0cb3, 0xc5c95a63), new Word64(0x4ed8aa4a, 0xe3418acb),
  13210. new Word64(0x5b9cca4f, 0x7763e373), new Word64(0x682e6ff3, 0xd6b2b8a3),
  13211. new Word64(0x748f82ee, 0x5defb2fc), new Word64(0x78a5636f, 0x43172f60),
  13212. new Word64(0x84c87814, 0xa1f0ab72), new Word64(0x8cc70208, 0x1a6439ec),
  13213. new Word64(0x90befffa, 0x23631e28), new Word64(0xa4506ceb, 0xde82bde9),
  13214. new Word64(0xbef9a3f7, 0xb2c67915), new Word64(0xc67178f2, 0xe372532b),
  13215. new Word64(0xca273ece, 0xea26619c), new Word64(0xd186b8c7, 0x21c0c207),
  13216. new Word64(0xeada7dd6, 0xcde0eb1e), new Word64(0xf57d4f7f, 0xee6ed178),
  13217. new Word64(0x06f067aa, 0x72176fba), new Word64(0x0a637dc5, 0xa2c898a6),
  13218. new Word64(0x113f9804, 0xbef90dae), new Word64(0x1b710b35, 0x131c471b),
  13219. new Word64(0x28db77f5, 0x23047d84), new Word64(0x32caab7b, 0x40c72493),
  13220. new Word64(0x3c9ebe0a, 0x15c9bebc), new Word64(0x431d67c4, 0x9c100d4c),
  13221. new Word64(0x4cc5d4be, 0xcb3e42b6), new Word64(0x597f299c, 0xfc657e2a),
  13222. new Word64(0x5fcb6fab, 0x3ad6faec), new Word64(0x6c44198c, 0x4a475817)];
  13223. function hash(data, offset, length, mode384) {
  13224. mode384 = !!mode384;
  13225. // initial hash values
  13226. var h0, h1, h2, h3, h4, h5, h6, h7;
  13227. if (!mode384) {
  13228. h0 = new Word64(0x6a09e667, 0xf3bcc908);
  13229. h1 = new Word64(0xbb67ae85, 0x84caa73b);
  13230. h2 = new Word64(0x3c6ef372, 0xfe94f82b);
  13231. h3 = new Word64(0xa54ff53a, 0x5f1d36f1);
  13232. h4 = new Word64(0x510e527f, 0xade682d1);
  13233. h5 = new Word64(0x9b05688c, 0x2b3e6c1f);
  13234. h6 = new Word64(0x1f83d9ab, 0xfb41bd6b);
  13235. h7 = new Word64(0x5be0cd19, 0x137e2179);
  13236. }
  13237. else {
  13238. // SHA384 is exactly the same
  13239. // except with different starting values and a trimmed result
  13240. h0 = new Word64(0xcbbb9d5d, 0xc1059ed8);
  13241. h1 = new Word64(0x629a292a, 0x367cd507);
  13242. h2 = new Word64(0x9159015a, 0x3070dd17);
  13243. h3 = new Word64(0x152fecd8, 0xf70e5939);
  13244. h4 = new Word64(0x67332667, 0xffc00b31);
  13245. h5 = new Word64(0x8eb44a87, 0x68581511);
  13246. h6 = new Word64(0xdb0c2e0d, 0x64f98fa7);
  13247. h7 = new Word64(0x47b5481d, 0xbefa4fa4);
  13248. }
  13249. // pre-processing
  13250. var paddedLength = Math.ceil((length + 17) / 128) * 128;
  13251. var padded = new Uint8Array(paddedLength);
  13252. var i, j, n;
  13253. for (i = 0; i < length; ++i) {
  13254. padded[i] = data[offset++];
  13255. }
  13256. padded[i++] = 0x80;
  13257. n = paddedLength - 16;
  13258. while (i < n) {
  13259. padded[i++] = 0;
  13260. }
  13261. padded[i++] = 0;
  13262. padded[i++] = 0;
  13263. padded[i++] = 0;
  13264. padded[i++] = 0;
  13265. padded[i++] = 0;
  13266. padded[i++] = 0;
  13267. padded[i++] = 0;
  13268. padded[i++] = 0;
  13269. padded[i++] = 0;
  13270. padded[i++] = 0;
  13271. padded[i++] = 0;
  13272. padded[i++] = (length >>> 29) & 0xFF;
  13273. padded[i++] = (length >> 21) & 0xFF;
  13274. padded[i++] = (length >> 13) & 0xFF;
  13275. padded[i++] = (length >> 5) & 0xFF;
  13276. padded[i++] = (length << 3) & 0xFF;
  13277. var w = new Array(80);
  13278. for (i = 0; i < 80; i++) {
  13279. w[i] = new Word64(0, 0);
  13280. }
  13281. var a = new Word64(0, 0), b = new Word64(0, 0), c = new Word64(0, 0);
  13282. var d = new Word64(0, 0), e = new Word64(0, 0), f = new Word64(0, 0);
  13283. var g = new Word64(0, 0), h = new Word64(0, 0);
  13284. var t1 = new Word64(0, 0), t2 = new Word64(0, 0);
  13285. var tmp1 = new Word64(0, 0), tmp2 = new Word64(0, 0), tmp3;
  13286. // for each 1024 bit block
  13287. for (i = 0; i < paddedLength;) {
  13288. for (j = 0; j < 16; ++j) {
  13289. w[j].high = (padded[i] << 24) | (padded[i + 1] << 16) |
  13290. (padded[i + 2] << 8) | (padded[i + 3]);
  13291. w[j].low = (padded[i + 4]) << 24 | (padded[i + 5]) << 16 |
  13292. (padded[i + 6]) << 8 | (padded[i + 7]);
  13293. i += 8;
  13294. }
  13295. for (j = 16; j < 80; ++j) {
  13296. tmp3 = w[j];
  13297. littleSigmaPrime(tmp3, w[j - 2], tmp2);
  13298. tmp3.add(w[j - 7]);
  13299. littleSigma(tmp1, w[j - 15], tmp2);
  13300. tmp3.add(tmp1);
  13301. tmp3.add(w[j - 16]);
  13302. }
  13303. a.assign(h0); b.assign(h1); c.assign(h2); d.assign(h3);
  13304. e.assign(h4); f.assign(h5); g.assign(h6); h.assign(h7);
  13305. for (j = 0; j < 80; ++j) {
  13306. t1.assign(h);
  13307. sigmaPrime(tmp1, e, tmp2);
  13308. t1.add(tmp1);
  13309. ch(tmp1, e, f, g, tmp2);
  13310. t1.add(tmp1);
  13311. t1.add(k[j]);
  13312. t1.add(w[j]);
  13313. sigma(t2, a, tmp2);
  13314. maj(tmp1, a, b, c, tmp2);
  13315. t2.add(tmp1);
  13316. tmp3 = h;
  13317. h = g;
  13318. g = f;
  13319. f = e;
  13320. d.add(t1);
  13321. e = d;
  13322. d = c;
  13323. c = b;
  13324. b = a;
  13325. tmp3.assign(t1);
  13326. tmp3.add(t2);
  13327. a = tmp3;
  13328. }
  13329. h0.add(a);
  13330. h1.add(b);
  13331. h2.add(c);
  13332. h3.add(d);
  13333. h4.add(e);
  13334. h5.add(f);
  13335. h6.add(g);
  13336. h7.add(h);
  13337. }
  13338. var result;
  13339. if (!mode384) {
  13340. result = new Uint8Array(64);
  13341. h0.copyTo(result,0);
  13342. h1.copyTo(result,8);
  13343. h2.copyTo(result,16);
  13344. h3.copyTo(result,24);
  13345. h4.copyTo(result,32);
  13346. h5.copyTo(result,40);
  13347. h6.copyTo(result,48);
  13348. h7.copyTo(result,56);
  13349. }
  13350. else {
  13351. result = new Uint8Array(48);
  13352. h0.copyTo(result,0);
  13353. h1.copyTo(result,8);
  13354. h2.copyTo(result,16);
  13355. h3.copyTo(result,24);
  13356. h4.copyTo(result,32);
  13357. h5.copyTo(result,40);
  13358. }
  13359. return result;
  13360. }
  13361. return hash;
  13362. })();
  13363. var calculateSHA384 = (function calculateSHA384Closure() {
  13364. function hash(data, offset, length) {
  13365. return calculateSHA512(data, offset, length, true);
  13366. }
  13367. return hash;
  13368. })();
  13369. var NullCipher = (function NullCipherClosure() {
  13370. function NullCipher() {
  13371. }
  13372. NullCipher.prototype = {
  13373. decryptBlock: function NullCipher_decryptBlock(data) {
  13374. return data;
  13375. }
  13376. };
  13377. return NullCipher;
  13378. })();
  13379. var AES128Cipher = (function AES128CipherClosure() {
  13380. var rcon = new Uint8Array([
  13381. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13382. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13383. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13384. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13385. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
  13386. 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,
  13387. 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  13388. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  13389. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10,
  13390. 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e,
  13391. 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  13392. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
  13393. 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
  13394. 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  13395. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  13396. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
  13397. 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb,
  13398. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13399. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13400. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13401. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13402. 0x74, 0xe8, 0xcb, 0x8d]);
  13403. var s = new Uint8Array([
  13404. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
  13405. 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
  13406. 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
  13407. 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  13408. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
  13409. 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
  13410. 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
  13411. 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  13412. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
  13413. 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
  13414. 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  13415. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  13416. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
  13417. 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
  13418. 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
  13419. 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  13420. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
  13421. 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
  13422. 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
  13423. 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  13424. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
  13425. 0xb0, 0x54, 0xbb, 0x16]);
  13426. var inv_s = new Uint8Array([
  13427. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
  13428. 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
  13429. 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
  13430. 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  13431. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
  13432. 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
  13433. 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
  13434. 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  13435. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
  13436. 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
  13437. 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  13438. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  13439. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
  13440. 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
  13441. 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
  13442. 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  13443. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
  13444. 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
  13445. 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
  13446. 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  13447. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
  13448. 0x55, 0x21, 0x0c, 0x7d]);
  13449. var mixCol = new Uint8Array(256);
  13450. for (var i = 0; i < 256; i++) {
  13451. if (i < 128) {
  13452. mixCol[i] = i << 1;
  13453. } else {
  13454. mixCol[i] = (i << 1) ^ 0x1b;
  13455. }
  13456. }
  13457. var mix = new Uint32Array([
  13458. 0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927,
  13459. 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
  13460. 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb,
  13461. 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
  13462. 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf,
  13463. 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
  13464. 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28,
  13465. 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
  13466. 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec,
  13467. 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
  13468. 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd,
  13469. 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
  13470. 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89,
  13471. 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
  13472. 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815,
  13473. 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f,
  13474. 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa,
  13475. 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8,
  13476. 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36,
  13477. 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
  13478. 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742,
  13479. 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
  13480. 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4,
  13481. 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e,
  13482. 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360,
  13483. 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
  13484. 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87,
  13485. 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
  13486. 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3,
  13487. 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
  13488. 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f,
  13489. 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
  13490. 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26,
  13491. 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
  13492. 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba,
  13493. 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
  13494. 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce,
  13495. 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
  13496. 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929,
  13497. 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
  13498. 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed,
  13499. 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
  13500. 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
  13501. function expandKey128(cipherKey) {
  13502. var b = 176, result = new Uint8Array(b);
  13503. result.set(cipherKey);
  13504. for (var j = 16, i = 1; j < b; ++i) {
  13505. // RotWord
  13506. var t1 = result[j - 3], t2 = result[j - 2],
  13507. t3 = result[j - 1], t4 = result[j - 4];
  13508. // SubWord
  13509. t1 = s[t1];
  13510. t2 = s[t2];
  13511. t3 = s[t3];
  13512. t4 = s[t4];
  13513. // Rcon
  13514. t1 = t1 ^ rcon[i];
  13515. for (var n = 0; n < 4; ++n) {
  13516. result[j] = (t1 ^= result[j - 16]);
  13517. j++;
  13518. result[j] = (t2 ^= result[j - 16]);
  13519. j++;
  13520. result[j] = (t3 ^= result[j - 16]);
  13521. j++;
  13522. result[j] = (t4 ^= result[j - 16]);
  13523. j++;
  13524. }
  13525. }
  13526. return result;
  13527. }
  13528. function decrypt128(input, key) {
  13529. var state = new Uint8Array(16);
  13530. state.set(input);
  13531. var i, j, k;
  13532. var t, u, v;
  13533. // AddRoundKey
  13534. for (j = 0, k = 160; j < 16; ++j, ++k) {
  13535. state[j] ^= key[k];
  13536. }
  13537. for (i = 9; i >= 1; --i) {
  13538. // InvShiftRows
  13539. t = state[13];
  13540. state[13] = state[9];
  13541. state[9] = state[5];
  13542. state[5] = state[1];
  13543. state[1] = t;
  13544. t = state[14];
  13545. u = state[10];
  13546. state[14] = state[6];
  13547. state[10] = state[2];
  13548. state[6] = t;
  13549. state[2] = u;
  13550. t = state[15];
  13551. u = state[11];
  13552. v = state[7];
  13553. state[15] = state[3];
  13554. state[11] = t;
  13555. state[7] = u;
  13556. state[3] = v;
  13557. // InvSubBytes
  13558. for (j = 0; j < 16; ++j) {
  13559. state[j] = inv_s[state[j]];
  13560. }
  13561. // AddRoundKey
  13562. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13563. state[j] ^= key[k];
  13564. }
  13565. // InvMixColumns
  13566. for (j = 0; j < 16; j += 4) {
  13567. var s0 = mix[state[j]], s1 = mix[state[j + 1]],
  13568. s2 = mix[state[j + 2]], s3 = mix[state[j + 3]];
  13569. t = (s0 ^ (s1 >>> 8) ^ (s1 << 24) ^ (s2 >>> 16) ^ (s2 << 16) ^
  13570. (s3 >>> 24) ^ (s3 << 8));
  13571. state[j] = (t >>> 24) & 0xFF;
  13572. state[j + 1] = (t >> 16) & 0xFF;
  13573. state[j + 2] = (t >> 8) & 0xFF;
  13574. state[j + 3] = t & 0xFF;
  13575. }
  13576. }
  13577. // InvShiftRows
  13578. t = state[13];
  13579. state[13] = state[9];
  13580. state[9] = state[5];
  13581. state[5] = state[1];
  13582. state[1] = t;
  13583. t = state[14];
  13584. u = state[10];
  13585. state[14] = state[6];
  13586. state[10] = state[2];
  13587. state[6] = t;
  13588. state[2] = u;
  13589. t = state[15];
  13590. u = state[11];
  13591. v = state[7];
  13592. state[15] = state[3];
  13593. state[11] = t;
  13594. state[7] = u;
  13595. state[3] = v;
  13596. for (j = 0; j < 16; ++j) {
  13597. // InvSubBytes
  13598. state[j] = inv_s[state[j]];
  13599. // AddRoundKey
  13600. state[j] ^= key[j];
  13601. }
  13602. return state;
  13603. }
  13604. function encrypt128(input, key) {
  13605. var t, u, v, k;
  13606. var state = new Uint8Array(16);
  13607. state.set(input);
  13608. for (j = 0; j < 16; ++j) {
  13609. // AddRoundKey
  13610. state[j] ^= key[j];
  13611. }
  13612. for (i = 1; i < 10; i++) {
  13613. //SubBytes
  13614. for (j = 0; j < 16; ++j) {
  13615. state[j] = s[state[j]];
  13616. }
  13617. //ShiftRows
  13618. v = state[1];
  13619. state[1] = state[5];
  13620. state[5] = state[9];
  13621. state[9] = state[13];
  13622. state[13] = v;
  13623. v = state[2];
  13624. u = state[6];
  13625. state[2] = state[10];
  13626. state[6] = state[14];
  13627. state[10] = v;
  13628. state[14] = u;
  13629. v = state[3];
  13630. u = state[7];
  13631. t = state[11];
  13632. state[3] = state[15];
  13633. state[7] = v;
  13634. state[11] = u;
  13635. state[15] = t;
  13636. //MixColumns
  13637. for (var j = 0; j < 16; j += 4) {
  13638. var s0 = state[j + 0], s1 = state[j + 1];
  13639. var s2 = state[j + 2], s3 = state[j + 3];
  13640. t = s0 ^ s1 ^ s2 ^ s3;
  13641. state[j + 0] ^= t ^ mixCol[s0 ^ s1];
  13642. state[j + 1] ^= t ^ mixCol[s1 ^ s2];
  13643. state[j + 2] ^= t ^ mixCol[s2 ^ s3];
  13644. state[j + 3] ^= t ^ mixCol[s3 ^ s0];
  13645. }
  13646. //AddRoundKey
  13647. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13648. state[j] ^= key[k];
  13649. }
  13650. }
  13651. //SubBytes
  13652. for (j = 0; j < 16; ++j) {
  13653. state[j] = s[state[j]];
  13654. }
  13655. //ShiftRows
  13656. v = state[1];
  13657. state[1] = state[5];
  13658. state[5] = state[9];
  13659. state[9] = state[13];
  13660. state[13] = v;
  13661. v = state[2];
  13662. u = state[6];
  13663. state[2] = state[10];
  13664. state[6] = state[14];
  13665. state[10] = v;
  13666. state[14] = u;
  13667. v = state[3];
  13668. u = state[7];
  13669. t = state[11];
  13670. state[3] = state[15];
  13671. state[7] = v;
  13672. state[11] = u;
  13673. state[15] = t;
  13674. //AddRoundKey
  13675. for (j = 0, k = 160; j < 16; ++j, ++k) {
  13676. state[j] ^= key[k];
  13677. }
  13678. return state;
  13679. }
  13680. function AES128Cipher(key) {
  13681. this.key = expandKey128(key);
  13682. this.buffer = new Uint8Array(16);
  13683. this.bufferPosition = 0;
  13684. }
  13685. function decryptBlock2(data, finalize) {
  13686. var i, j, ii, sourceLength = data.length,
  13687. buffer = this.buffer, bufferLength = this.bufferPosition,
  13688. result = [], iv = this.iv;
  13689. for (i = 0; i < sourceLength; ++i) {
  13690. buffer[bufferLength] = data[i];
  13691. ++bufferLength;
  13692. if (bufferLength < 16) {
  13693. continue;
  13694. }
  13695. // buffer is full, decrypting
  13696. var plain = decrypt128(buffer, this.key);
  13697. // xor-ing the IV vector to get plain text
  13698. for (j = 0; j < 16; ++j) {
  13699. plain[j] ^= iv[j];
  13700. }
  13701. iv = buffer;
  13702. result.push(plain);
  13703. buffer = new Uint8Array(16);
  13704. bufferLength = 0;
  13705. }
  13706. // saving incomplete buffer
  13707. this.buffer = buffer;
  13708. this.bufferLength = bufferLength;
  13709. this.iv = iv;
  13710. if (result.length === 0) {
  13711. return new Uint8Array([]);
  13712. }
  13713. // combining plain text blocks into one
  13714. var outputLength = 16 * result.length;
  13715. if (finalize) {
  13716. // undo a padding that is described in RFC 2898
  13717. var lastBlock = result[result.length - 1];
  13718. var psLen = lastBlock[15];
  13719. if (psLen <= 16) {
  13720. for (i = 15, ii = 16 - psLen; i >= ii; --i) {
  13721. if (lastBlock[i] !== psLen) {
  13722. // Invalid padding, assume that the block has no padding.
  13723. psLen = 0;
  13724. break;
  13725. }
  13726. }
  13727. outputLength -= psLen;
  13728. result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
  13729. }
  13730. }
  13731. var output = new Uint8Array(outputLength);
  13732. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13733. output.set(result[i], j);
  13734. }
  13735. return output;
  13736. }
  13737. AES128Cipher.prototype = {
  13738. decryptBlock: function AES128Cipher_decryptBlock(data, finalize) {
  13739. var i, sourceLength = data.length;
  13740. var buffer = this.buffer, bufferLength = this.bufferPosition;
  13741. // waiting for IV values -- they are at the start of the stream
  13742. for (i = 0; bufferLength < 16 && i < sourceLength; ++i, ++bufferLength) {
  13743. buffer[bufferLength] = data[i];
  13744. }
  13745. if (bufferLength < 16) {
  13746. // need more data
  13747. this.bufferLength = bufferLength;
  13748. return new Uint8Array([]);
  13749. }
  13750. this.iv = buffer;
  13751. this.buffer = new Uint8Array(16);
  13752. this.bufferLength = 0;
  13753. // starting decryption
  13754. this.decryptBlock = decryptBlock2;
  13755. return this.decryptBlock(data.subarray(16), finalize);
  13756. },
  13757. encrypt: function AES128Cipher_encrypt(data, iv) {
  13758. var i, j, ii, sourceLength = data.length,
  13759. buffer = this.buffer, bufferLength = this.bufferPosition,
  13760. result = [];
  13761. if (!iv) {
  13762. iv = new Uint8Array(16);
  13763. }
  13764. for (i = 0; i < sourceLength; ++i) {
  13765. buffer[bufferLength] = data[i];
  13766. ++bufferLength;
  13767. if (bufferLength < 16) {
  13768. continue;
  13769. }
  13770. for (j = 0; j < 16; ++j) {
  13771. buffer[j] ^= iv[j];
  13772. }
  13773. // buffer is full, encrypting
  13774. var cipher = encrypt128(buffer, this.key);
  13775. iv = cipher;
  13776. result.push(cipher);
  13777. buffer = new Uint8Array(16);
  13778. bufferLength = 0;
  13779. }
  13780. // saving incomplete buffer
  13781. this.buffer = buffer;
  13782. this.bufferLength = bufferLength;
  13783. this.iv = iv;
  13784. if (result.length === 0) {
  13785. return new Uint8Array([]);
  13786. }
  13787. // combining plain text blocks into one
  13788. var outputLength = 16 * result.length;
  13789. var output = new Uint8Array(outputLength);
  13790. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13791. output.set(result[i], j);
  13792. }
  13793. return output;
  13794. }
  13795. };
  13796. return AES128Cipher;
  13797. })();
  13798. var AES256Cipher = (function AES256CipherClosure() {
  13799. var rcon = new Uint8Array([
  13800. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13801. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13802. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13803. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13804. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
  13805. 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,
  13806. 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  13807. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  13808. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10,
  13809. 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e,
  13810. 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  13811. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
  13812. 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
  13813. 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  13814. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  13815. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
  13816. 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb,
  13817. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13818. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13819. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13820. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13821. 0x74, 0xe8, 0xcb, 0x8d]);
  13822. var s = new Uint8Array([
  13823. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
  13824. 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
  13825. 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
  13826. 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  13827. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
  13828. 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
  13829. 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
  13830. 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  13831. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
  13832. 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
  13833. 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  13834. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  13835. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
  13836. 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
  13837. 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
  13838. 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  13839. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
  13840. 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
  13841. 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
  13842. 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  13843. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
  13844. 0xb0, 0x54, 0xbb, 0x16]);
  13845. var inv_s = new Uint8Array([
  13846. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
  13847. 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
  13848. 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
  13849. 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  13850. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
  13851. 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
  13852. 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
  13853. 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  13854. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
  13855. 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
  13856. 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  13857. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  13858. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
  13859. 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
  13860. 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
  13861. 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  13862. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
  13863. 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
  13864. 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
  13865. 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  13866. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
  13867. 0x55, 0x21, 0x0c, 0x7d]);
  13868. var mixCol = new Uint8Array(256);
  13869. for (var i = 0; i < 256; i++) {
  13870. if (i < 128) {
  13871. mixCol[i] = i << 1;
  13872. } else {
  13873. mixCol[i] = (i << 1) ^ 0x1b;
  13874. }
  13875. }
  13876. var mix = new Uint32Array([
  13877. 0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927,
  13878. 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
  13879. 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb,
  13880. 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
  13881. 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf,
  13882. 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
  13883. 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28,
  13884. 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
  13885. 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec,
  13886. 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
  13887. 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd,
  13888. 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
  13889. 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89,
  13890. 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
  13891. 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815,
  13892. 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f,
  13893. 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa,
  13894. 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8,
  13895. 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36,
  13896. 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
  13897. 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742,
  13898. 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
  13899. 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4,
  13900. 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e,
  13901. 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360,
  13902. 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
  13903. 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87,
  13904. 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
  13905. 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3,
  13906. 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
  13907. 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f,
  13908. 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
  13909. 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26,
  13910. 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
  13911. 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba,
  13912. 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
  13913. 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce,
  13914. 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
  13915. 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929,
  13916. 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
  13917. 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed,
  13918. 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
  13919. 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
  13920. function expandKey256(cipherKey) {
  13921. var b = 240, result = new Uint8Array(b);
  13922. var r = 1;
  13923. result.set(cipherKey);
  13924. for (var j = 32, i = 1; j < b; ++i) {
  13925. if (j % 32 === 16) {
  13926. t1 = s[t1];
  13927. t2 = s[t2];
  13928. t3 = s[t3];
  13929. t4 = s[t4];
  13930. } else if (j % 32 === 0) {
  13931. // RotWord
  13932. var t1 = result[j - 3], t2 = result[j - 2],
  13933. t3 = result[j - 1], t4 = result[j - 4];
  13934. // SubWord
  13935. t1 = s[t1];
  13936. t2 = s[t2];
  13937. t3 = s[t3];
  13938. t4 = s[t4];
  13939. // Rcon
  13940. t1 = t1 ^ r;
  13941. if ((r <<= 1) >= 256) {
  13942. r = (r ^ 0x1b) & 0xFF;
  13943. }
  13944. }
  13945. for (var n = 0; n < 4; ++n) {
  13946. result[j] = (t1 ^= result[j - 32]);
  13947. j++;
  13948. result[j] = (t2 ^= result[j - 32]);
  13949. j++;
  13950. result[j] = (t3 ^= result[j - 32]);
  13951. j++;
  13952. result[j] = (t4 ^= result[j - 32]);
  13953. j++;
  13954. }
  13955. }
  13956. return result;
  13957. }
  13958. function decrypt256(input, key) {
  13959. var state = new Uint8Array(16);
  13960. state.set(input);
  13961. var i, j, k;
  13962. var t, u, v;
  13963. // AddRoundKey
  13964. for (j = 0, k = 224; j < 16; ++j, ++k) {
  13965. state[j] ^= key[k];
  13966. }
  13967. for (i = 13; i >= 1; --i) {
  13968. // InvShiftRows
  13969. t = state[13];
  13970. state[13] = state[9];
  13971. state[9] = state[5];
  13972. state[5] = state[1];
  13973. state[1] = t;
  13974. t = state[14];
  13975. u = state[10];
  13976. state[14] = state[6];
  13977. state[10] = state[2];
  13978. state[6] = t;
  13979. state[2] = u;
  13980. t = state[15];
  13981. u = state[11];
  13982. v = state[7];
  13983. state[15] = state[3];
  13984. state[11] = t;
  13985. state[7] = u;
  13986. state[3] = v;
  13987. // InvSubBytes
  13988. for (j = 0; j < 16; ++j) {
  13989. state[j] = inv_s[state[j]];
  13990. }
  13991. // AddRoundKey
  13992. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13993. state[j] ^= key[k];
  13994. }
  13995. // InvMixColumns
  13996. for (j = 0; j < 16; j += 4) {
  13997. var s0 = mix[state[j]], s1 = mix[state[j + 1]],
  13998. s2 = mix[state[j + 2]], s3 = mix[state[j + 3]];
  13999. t = (s0 ^ (s1 >>> 8) ^ (s1 << 24) ^ (s2 >>> 16) ^ (s2 << 16) ^
  14000. (s3 >>> 24) ^ (s3 << 8));
  14001. state[j] = (t >>> 24) & 0xFF;
  14002. state[j + 1] = (t >> 16) & 0xFF;
  14003. state[j + 2] = (t >> 8) & 0xFF;
  14004. state[j + 3] = t & 0xFF;
  14005. }
  14006. }
  14007. // InvShiftRows
  14008. t = state[13];
  14009. state[13] = state[9];
  14010. state[9] = state[5];
  14011. state[5] = state[1];
  14012. state[1] = t;
  14013. t = state[14];
  14014. u = state[10];
  14015. state[14] = state[6];
  14016. state[10] = state[2];
  14017. state[6] = t;
  14018. state[2] = u;
  14019. t = state[15];
  14020. u = state[11];
  14021. v = state[7];
  14022. state[15] = state[3];
  14023. state[11] = t;
  14024. state[7] = u;
  14025. state[3] = v;
  14026. for (j = 0; j < 16; ++j) {
  14027. // InvSubBytes
  14028. state[j] = inv_s[state[j]];
  14029. // AddRoundKey
  14030. state[j] ^= key[j];
  14031. }
  14032. return state;
  14033. }
  14034. function encrypt256(input, key) {
  14035. var t, u, v, k;
  14036. var state = new Uint8Array(16);
  14037. state.set(input);
  14038. for (j = 0; j < 16; ++j) {
  14039. // AddRoundKey
  14040. state[j] ^= key[j];
  14041. }
  14042. for (i = 1; i < 14; i++) {
  14043. //SubBytes
  14044. for (j = 0; j < 16; ++j) {
  14045. state[j] = s[state[j]];
  14046. }
  14047. //ShiftRows
  14048. v = state[1];
  14049. state[1] = state[5];
  14050. state[5] = state[9];
  14051. state[9] = state[13];
  14052. state[13] = v;
  14053. v = state[2];
  14054. u = state[6];
  14055. state[2] = state[10];
  14056. state[6] = state[14];
  14057. state[10] = v;
  14058. state[14] = u;
  14059. v = state[3];
  14060. u = state[7];
  14061. t = state[11];
  14062. state[3] = state[15];
  14063. state[7] = v;
  14064. state[11] = u;
  14065. state[15] = t;
  14066. //MixColumns
  14067. for (var j = 0; j < 16; j += 4) {
  14068. var s0 = state[j + 0], s1 = state[j + 1];
  14069. var s2 = state[j + 2], s3 = state[j + 3];
  14070. t = s0 ^ s1 ^ s2 ^ s3;
  14071. state[j + 0] ^= t ^ mixCol[s0 ^ s1];
  14072. state[j + 1] ^= t ^ mixCol[s1 ^ s2];
  14073. state[j + 2] ^= t ^ mixCol[s2 ^ s3];
  14074. state[j + 3] ^= t ^ mixCol[s3 ^ s0];
  14075. }
  14076. //AddRoundKey
  14077. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  14078. state[j] ^= key[k];
  14079. }
  14080. }
  14081. //SubBytes
  14082. for (j = 0; j < 16; ++j) {
  14083. state[j] = s[state[j]];
  14084. }
  14085. //ShiftRows
  14086. v = state[1];
  14087. state[1] = state[5];
  14088. state[5] = state[9];
  14089. state[9] = state[13];
  14090. state[13] = v;
  14091. v = state[2];
  14092. u = state[6];
  14093. state[2] = state[10];
  14094. state[6] = state[14];
  14095. state[10] = v;
  14096. state[14] = u;
  14097. v = state[3];
  14098. u = state[7];
  14099. t = state[11];
  14100. state[3] = state[15];
  14101. state[7] = v;
  14102. state[11] = u;
  14103. state[15] = t;
  14104. //AddRoundKey
  14105. for (j = 0, k = 224; j < 16; ++j, ++k) {
  14106. state[j] ^= key[k];
  14107. }
  14108. return state;
  14109. }
  14110. function AES256Cipher(key) {
  14111. this.key = expandKey256(key);
  14112. this.buffer = new Uint8Array(16);
  14113. this.bufferPosition = 0;
  14114. }
  14115. function decryptBlock2(data, finalize) {
  14116. var i, j, ii, sourceLength = data.length,
  14117. buffer = this.buffer, bufferLength = this.bufferPosition,
  14118. result = [], iv = this.iv;
  14119. for (i = 0; i < sourceLength; ++i) {
  14120. buffer[bufferLength] = data[i];
  14121. ++bufferLength;
  14122. if (bufferLength < 16) {
  14123. continue;
  14124. }
  14125. // buffer is full, decrypting
  14126. var plain = decrypt256(buffer, this.key);
  14127. // xor-ing the IV vector to get plain text
  14128. for (j = 0; j < 16; ++j) {
  14129. plain[j] ^= iv[j];
  14130. }
  14131. iv = buffer;
  14132. result.push(plain);
  14133. buffer = new Uint8Array(16);
  14134. bufferLength = 0;
  14135. }
  14136. // saving incomplete buffer
  14137. this.buffer = buffer;
  14138. this.bufferLength = bufferLength;
  14139. this.iv = iv;
  14140. if (result.length === 0) {
  14141. return new Uint8Array([]);
  14142. }
  14143. // combining plain text blocks into one
  14144. var outputLength = 16 * result.length;
  14145. if (finalize) {
  14146. // undo a padding that is described in RFC 2898
  14147. var lastBlock = result[result.length - 1];
  14148. var psLen = lastBlock[15];
  14149. if (psLen <= 16) {
  14150. for (i = 15, ii = 16 - psLen; i >= ii; --i) {
  14151. if (lastBlock[i] !== psLen) {
  14152. // Invalid padding, assume that the block has no padding.
  14153. psLen = 0;
  14154. break;
  14155. }
  14156. }
  14157. outputLength -= psLen;
  14158. result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
  14159. }
  14160. }
  14161. var output = new Uint8Array(outputLength);
  14162. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  14163. output.set(result[i], j);
  14164. }
  14165. return output;
  14166. }
  14167. AES256Cipher.prototype = {
  14168. decryptBlock: function AES256Cipher_decryptBlock(data, finalize, iv) {
  14169. var i, sourceLength = data.length;
  14170. var buffer = this.buffer, bufferLength = this.bufferPosition;
  14171. // if not supplied an IV wait for IV values
  14172. // they are at the start of the stream
  14173. if (iv) {
  14174. this.iv = iv;
  14175. } else {
  14176. for (i = 0; bufferLength < 16 &&
  14177. i < sourceLength; ++i, ++bufferLength) {
  14178. buffer[bufferLength] = data[i];
  14179. }
  14180. if (bufferLength < 16) {
  14181. //need more data
  14182. this.bufferLength = bufferLength;
  14183. return new Uint8Array([]);
  14184. }
  14185. this.iv = buffer;
  14186. data = data.subarray(16);
  14187. }
  14188. this.buffer = new Uint8Array(16);
  14189. this.bufferLength = 0;
  14190. // starting decryption
  14191. this.decryptBlock = decryptBlock2;
  14192. return this.decryptBlock(data, finalize);
  14193. },
  14194. encrypt: function AES256Cipher_encrypt(data, iv) {
  14195. var i, j, ii, sourceLength = data.length,
  14196. buffer = this.buffer, bufferLength = this.bufferPosition,
  14197. result = [];
  14198. if (!iv) {
  14199. iv = new Uint8Array(16);
  14200. }
  14201. for (i = 0; i < sourceLength; ++i) {
  14202. buffer[bufferLength] = data[i];
  14203. ++bufferLength;
  14204. if (bufferLength < 16) {
  14205. continue;
  14206. }
  14207. for (j = 0; j < 16; ++j) {
  14208. buffer[j] ^= iv[j];
  14209. }
  14210. // buffer is full, encrypting
  14211. var cipher = encrypt256(buffer, this.key);
  14212. this.iv = cipher;
  14213. result.push(cipher);
  14214. buffer = new Uint8Array(16);
  14215. bufferLength = 0;
  14216. }
  14217. // saving incomplete buffer
  14218. this.buffer = buffer;
  14219. this.bufferLength = bufferLength;
  14220. this.iv = iv;
  14221. if (result.length === 0) {
  14222. return new Uint8Array([]);
  14223. }
  14224. // combining plain text blocks into one
  14225. var outputLength = 16 * result.length;
  14226. var output = new Uint8Array(outputLength);
  14227. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  14228. output.set(result[i], j);
  14229. }
  14230. return output;
  14231. }
  14232. };
  14233. return AES256Cipher;
  14234. })();
  14235. var PDF17 = (function PDF17Closure() {
  14236. function compareByteArrays(array1, array2) {
  14237. if (array1.length !== array2.length) {
  14238. return false;
  14239. }
  14240. for (var i = 0; i < array1.length; i++) {
  14241. if (array1[i] !== array2[i]) {
  14242. return false;
  14243. }
  14244. }
  14245. return true;
  14246. }
  14247. function PDF17() {
  14248. }
  14249. PDF17.prototype = {
  14250. checkOwnerPassword: function PDF17_checkOwnerPassword(password,
  14251. ownerValidationSalt,
  14252. userBytes,
  14253. ownerPassword) {
  14254. var hashData = new Uint8Array(password.length + 56);
  14255. hashData.set(password, 0);
  14256. hashData.set(ownerValidationSalt, password.length);
  14257. hashData.set(userBytes, password.length + ownerValidationSalt.length);
  14258. var result = calculateSHA256(hashData, 0, hashData.length);
  14259. return compareByteArrays(result, ownerPassword);
  14260. },
  14261. checkUserPassword: function PDF17_checkUserPassword(password,
  14262. userValidationSalt,
  14263. userPassword) {
  14264. var hashData = new Uint8Array(password.length + 8);
  14265. hashData.set(password, 0);
  14266. hashData.set(userValidationSalt, password.length);
  14267. var result = calculateSHA256(hashData, 0, hashData.length);
  14268. return compareByteArrays(result, userPassword);
  14269. },
  14270. getOwnerKey: function PDF17_getOwnerKey(password, ownerKeySalt, userBytes,
  14271. ownerEncryption) {
  14272. var hashData = new Uint8Array(password.length + 56);
  14273. hashData.set(password, 0);
  14274. hashData.set(ownerKeySalt, password.length);
  14275. hashData.set(userBytes, password.length + ownerKeySalt.length);
  14276. var key = calculateSHA256(hashData, 0, hashData.length);
  14277. var cipher = new AES256Cipher(key);
  14278. return cipher.decryptBlock(ownerEncryption,
  14279. false,
  14280. new Uint8Array(16));
  14281. },
  14282. getUserKey: function PDF17_getUserKey(password, userKeySalt,
  14283. userEncryption) {
  14284. var hashData = new Uint8Array(password.length + 8);
  14285. hashData.set(password, 0);
  14286. hashData.set(userKeySalt, password.length);
  14287. //key is the decryption key for the UE string
  14288. var key = calculateSHA256(hashData, 0, hashData.length);
  14289. var cipher = new AES256Cipher(key);
  14290. return cipher.decryptBlock(userEncryption,
  14291. false,
  14292. new Uint8Array(16));
  14293. }
  14294. };
  14295. return PDF17;
  14296. })();
  14297. var PDF20 = (function PDF20Closure() {
  14298. function concatArrays(array1, array2) {
  14299. var t = new Uint8Array(array1.length + array2.length);
  14300. t.set(array1, 0);
  14301. t.set(array2, array1.length);
  14302. return t;
  14303. }
  14304. function calculatePDF20Hash(password, input, userBytes) {
  14305. //This refers to Algorithm 2.B as defined in ISO 32000-2
  14306. var k = calculateSHA256(input, 0, input.length).subarray(0, 32);
  14307. var e = [0];
  14308. var i = 0;
  14309. while (i < 64 || e[e.length - 1] > i - 32) {
  14310. var arrayLength = password.length + k.length + userBytes.length;
  14311. var k1 = new Uint8Array(arrayLength * 64);
  14312. var array = concatArrays(password, k);
  14313. array = concatArrays(array, userBytes);
  14314. for (var j = 0, pos = 0; j < 64; j++, pos += arrayLength) {
  14315. k1.set(array, pos);
  14316. }
  14317. //AES128 CBC NO PADDING with
  14318. //first 16 bytes of k as the key and the second 16 as the iv.
  14319. var cipher = new AES128Cipher(k.subarray(0, 16));
  14320. e = cipher.encrypt(k1, k.subarray(16, 32));
  14321. //Now we have to take the first 16 bytes of an unsigned
  14322. //big endian integer... and compute the remainder
  14323. //modulo 3.... That is a fairly large number and
  14324. //JavaScript isn't going to handle that well...
  14325. //So we're using a trick that allows us to perform
  14326. //modulo math byte by byte
  14327. var remainder = 0;
  14328. for (var z = 0; z < 16; z++) {
  14329. remainder *= (256 % 3);
  14330. remainder %= 3;
  14331. remainder += ((e[z] >>> 0) % 3);
  14332. remainder %= 3;
  14333. }
  14334. if (remainder === 0) {
  14335. k = calculateSHA256(e, 0, e.length);
  14336. }
  14337. else if (remainder === 1) {
  14338. k = calculateSHA384(e, 0, e.length);
  14339. }
  14340. else if (remainder === 2) {
  14341. k = calculateSHA512(e, 0, e.length);
  14342. }
  14343. i++;
  14344. }
  14345. return k.subarray(0, 32);
  14346. }
  14347. function PDF20() {
  14348. }
  14349. function compareByteArrays(array1, array2) {
  14350. if (array1.length !== array2.length) {
  14351. return false;
  14352. }
  14353. for (var i = 0; i < array1.length; i++) {
  14354. if (array1[i] !== array2[i]) {
  14355. return false;
  14356. }
  14357. }
  14358. return true;
  14359. }
  14360. PDF20.prototype = {
  14361. hash: function PDF20_hash(password, concatBytes, userBytes) {
  14362. return calculatePDF20Hash(password, concatBytes, userBytes);
  14363. },
  14364. checkOwnerPassword: function PDF20_checkOwnerPassword(password,
  14365. ownerValidationSalt,
  14366. userBytes,
  14367. ownerPassword) {
  14368. var hashData = new Uint8Array(password.length + 56);
  14369. hashData.set(password, 0);
  14370. hashData.set(ownerValidationSalt, password.length);
  14371. hashData.set(userBytes, password.length + ownerValidationSalt.length);
  14372. var result = calculatePDF20Hash(password, hashData, userBytes);
  14373. return compareByteArrays(result, ownerPassword);
  14374. },
  14375. checkUserPassword: function PDF20_checkUserPassword(password,
  14376. userValidationSalt,
  14377. userPassword) {
  14378. var hashData = new Uint8Array(password.length + 8);
  14379. hashData.set(password, 0);
  14380. hashData.set(userValidationSalt, password.length);
  14381. var result = calculatePDF20Hash(password, hashData, []);
  14382. return compareByteArrays(result, userPassword);
  14383. },
  14384. getOwnerKey: function PDF20_getOwnerKey(password, ownerKeySalt, userBytes,
  14385. ownerEncryption) {
  14386. var hashData = new Uint8Array(password.length + 56);
  14387. hashData.set(password, 0);
  14388. hashData.set(ownerKeySalt, password.length);
  14389. hashData.set(userBytes, password.length + ownerKeySalt.length);
  14390. var key = calculatePDF20Hash(password, hashData, userBytes);
  14391. var cipher = new AES256Cipher(key);
  14392. return cipher.decryptBlock(ownerEncryption,
  14393. false,
  14394. new Uint8Array(16));
  14395. },
  14396. getUserKey: function PDF20_getUserKey(password, userKeySalt,
  14397. userEncryption) {
  14398. var hashData = new Uint8Array(password.length + 8);
  14399. hashData.set(password, 0);
  14400. hashData.set(userKeySalt, password.length);
  14401. //key is the decryption key for the UE string
  14402. var key = calculatePDF20Hash(password, hashData, []);
  14403. var cipher = new AES256Cipher(key);
  14404. return cipher.decryptBlock(userEncryption,
  14405. false,
  14406. new Uint8Array(16));
  14407. }
  14408. };
  14409. return PDF20;
  14410. })();
  14411. var CipherTransform = (function CipherTransformClosure() {
  14412. function CipherTransform(stringCipherConstructor, streamCipherConstructor) {
  14413. this.stringCipherConstructor = stringCipherConstructor;
  14414. this.streamCipherConstructor = streamCipherConstructor;
  14415. }
  14416. CipherTransform.prototype = {
  14417. createStream: function CipherTransform_createStream(stream, length) {
  14418. var cipher = new this.streamCipherConstructor();
  14419. return new DecryptStream(stream, length,
  14420. function cipherTransformDecryptStream(data, finalize) {
  14421. return cipher.decryptBlock(data, finalize);
  14422. }
  14423. );
  14424. },
  14425. decryptString: function CipherTransform_decryptString(s) {
  14426. var cipher = new this.stringCipherConstructor();
  14427. var data = stringToBytes(s);
  14428. data = cipher.decryptBlock(data, true);
  14429. return bytesToString(data);
  14430. }
  14431. };
  14432. return CipherTransform;
  14433. })();
  14434. var CipherTransformFactory = (function CipherTransformFactoryClosure() {
  14435. var defaultPasswordBytes = new Uint8Array([
  14436. 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41,
  14437. 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
  14438. 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80,
  14439. 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A]);
  14440. function createEncryptionKey20(revision, password, ownerPassword,
  14441. ownerValidationSalt, ownerKeySalt, uBytes,
  14442. userPassword, userValidationSalt, userKeySalt,
  14443. ownerEncryption, userEncryption, perms) {
  14444. if (password) {
  14445. var passwordLength = Math.min(127, password.length);
  14446. password = password.subarray(0, passwordLength);
  14447. } else {
  14448. password = [];
  14449. }
  14450. var pdfAlgorithm;
  14451. if (revision === 6) {
  14452. pdfAlgorithm = new PDF20();
  14453. } else {
  14454. pdfAlgorithm = new PDF17();
  14455. }
  14456. if (pdfAlgorithm) {
  14457. if (pdfAlgorithm.checkUserPassword(password, userValidationSalt,
  14458. userPassword)) {
  14459. return pdfAlgorithm.getUserKey(password, userKeySalt, userEncryption);
  14460. } else if (pdfAlgorithm.checkOwnerPassword(password, ownerValidationSalt,
  14461. uBytes,
  14462. ownerPassword)) {
  14463. return pdfAlgorithm.getOwnerKey(password, ownerKeySalt, uBytes,
  14464. ownerEncryption);
  14465. }
  14466. }
  14467. return null;
  14468. }
  14469. function prepareKeyData(fileId, password, ownerPassword, userPassword,
  14470. flags, revision, keyLength, encryptMetadata) {
  14471. var hashDataSize = 40 + ownerPassword.length + fileId.length;
  14472. var hashData = new Uint8Array(hashDataSize), i = 0, j, n;
  14473. if (password) {
  14474. n = Math.min(32, password.length);
  14475. for (; i < n; ++i) {
  14476. hashData[i] = password[i];
  14477. }
  14478. }
  14479. j = 0;
  14480. while (i < 32) {
  14481. hashData[i++] = defaultPasswordBytes[j++];
  14482. }
  14483. // as now the padded password in the hashData[0..i]
  14484. for (j = 0, n = ownerPassword.length; j < n; ++j) {
  14485. hashData[i++] = ownerPassword[j];
  14486. }
  14487. hashData[i++] = flags & 0xFF;
  14488. hashData[i++] = (flags >> 8) & 0xFF;
  14489. hashData[i++] = (flags >> 16) & 0xFF;
  14490. hashData[i++] = (flags >>> 24) & 0xFF;
  14491. for (j = 0, n = fileId.length; j < n; ++j) {
  14492. hashData[i++] = fileId[j];
  14493. }
  14494. if (revision >= 4 && !encryptMetadata) {
  14495. hashData[i++] = 0xFF;
  14496. hashData[i++] = 0xFF;
  14497. hashData[i++] = 0xFF;
  14498. hashData[i++] = 0xFF;
  14499. }
  14500. var hash = calculateMD5(hashData, 0, i);
  14501. var keyLengthInBytes = keyLength >> 3;
  14502. if (revision >= 3) {
  14503. for (j = 0; j < 50; ++j) {
  14504. hash = calculateMD5(hash, 0, keyLengthInBytes);
  14505. }
  14506. }
  14507. var encryptionKey = hash.subarray(0, keyLengthInBytes);
  14508. var cipher, checkData;
  14509. if (revision >= 3) {
  14510. for (i = 0; i < 32; ++i) {
  14511. hashData[i] = defaultPasswordBytes[i];
  14512. }
  14513. for (j = 0, n = fileId.length; j < n; ++j) {
  14514. hashData[i++] = fileId[j];
  14515. }
  14516. cipher = new ARCFourCipher(encryptionKey);
  14517. checkData = cipher.encryptBlock(calculateMD5(hashData, 0, i));
  14518. n = encryptionKey.length;
  14519. var derivedKey = new Uint8Array(n), k;
  14520. for (j = 1; j <= 19; ++j) {
  14521. for (k = 0; k < n; ++k) {
  14522. derivedKey[k] = encryptionKey[k] ^ j;
  14523. }
  14524. cipher = new ARCFourCipher(derivedKey);
  14525. checkData = cipher.encryptBlock(checkData);
  14526. }
  14527. for (j = 0, n = checkData.length; j < n; ++j) {
  14528. if (userPassword[j] !== checkData[j]) {
  14529. return null;
  14530. }
  14531. }
  14532. } else {
  14533. cipher = new ARCFourCipher(encryptionKey);
  14534. checkData = cipher.encryptBlock(defaultPasswordBytes);
  14535. for (j = 0, n = checkData.length; j < n; ++j) {
  14536. if (userPassword[j] !== checkData[j]) {
  14537. return null;
  14538. }
  14539. }
  14540. }
  14541. return encryptionKey;
  14542. }
  14543. function decodeUserPassword(password, ownerPassword, revision, keyLength) {
  14544. var hashData = new Uint8Array(32), i = 0, j, n;
  14545. n = Math.min(32, password.length);
  14546. for (; i < n; ++i) {
  14547. hashData[i] = password[i];
  14548. }
  14549. j = 0;
  14550. while (i < 32) {
  14551. hashData[i++] = defaultPasswordBytes[j++];
  14552. }
  14553. var hash = calculateMD5(hashData, 0, i);
  14554. var keyLengthInBytes = keyLength >> 3;
  14555. if (revision >= 3) {
  14556. for (j = 0; j < 50; ++j) {
  14557. hash = calculateMD5(hash, 0, hash.length);
  14558. }
  14559. }
  14560. var cipher, userPassword;
  14561. if (revision >= 3) {
  14562. userPassword = ownerPassword;
  14563. var derivedKey = new Uint8Array(keyLengthInBytes), k;
  14564. for (j = 19; j >= 0; j--) {
  14565. for (k = 0; k < keyLengthInBytes; ++k) {
  14566. derivedKey[k] = hash[k] ^ j;
  14567. }
  14568. cipher = new ARCFourCipher(derivedKey);
  14569. userPassword = cipher.encryptBlock(userPassword);
  14570. }
  14571. } else {
  14572. cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
  14573. userPassword = cipher.encryptBlock(ownerPassword);
  14574. }
  14575. return userPassword;
  14576. }
  14577. var identityName = Name.get('Identity');
  14578. function CipherTransformFactory(dict, fileId, password) {
  14579. var filter = dict.get('Filter');
  14580. if (!isName(filter) || filter.name !== 'Standard') {
  14581. error('unknown encryption method');
  14582. }
  14583. this.dict = dict;
  14584. var algorithm = dict.get('V');
  14585. if (!isInt(algorithm) ||
  14586. (algorithm !== 1 && algorithm !== 2 && algorithm !== 4 &&
  14587. algorithm !== 5)) {
  14588. error('unsupported encryption algorithm');
  14589. }
  14590. this.algorithm = algorithm;
  14591. var keyLength = dict.get('Length') || 40;
  14592. if (!isInt(keyLength) ||
  14593. keyLength < 40 || (keyLength % 8) !== 0) {
  14594. error('invalid key length');
  14595. }
  14596. // prepare keys
  14597. var ownerPassword = stringToBytes(dict.get('O')).subarray(0, 32);
  14598. var userPassword = stringToBytes(dict.get('U')).subarray(0, 32);
  14599. var flags = dict.get('P');
  14600. var revision = dict.get('R');
  14601. // meaningful when V is 4 or 5
  14602. var encryptMetadata = ((algorithm === 4 || algorithm === 5) &&
  14603. dict.get('EncryptMetadata') !== false);
  14604. this.encryptMetadata = encryptMetadata;
  14605. var fileIdBytes = stringToBytes(fileId);
  14606. var passwordBytes;
  14607. if (password) {
  14608. if (revision === 6) {
  14609. try {
  14610. password = utf8StringToString(password);
  14611. } catch (ex) {
  14612. warn('CipherTransformFactory: ' +
  14613. 'Unable to convert UTF8 encoded password.');
  14614. }
  14615. }
  14616. passwordBytes = stringToBytes(password);
  14617. }
  14618. var encryptionKey;
  14619. if (algorithm !== 5) {
  14620. encryptionKey = prepareKeyData(fileIdBytes, passwordBytes,
  14621. ownerPassword, userPassword, flags,
  14622. revision, keyLength, encryptMetadata);
  14623. }
  14624. else {
  14625. var ownerValidationSalt = stringToBytes(dict.get('O')).subarray(32, 40);
  14626. var ownerKeySalt = stringToBytes(dict.get('O')).subarray(40, 48);
  14627. var uBytes = stringToBytes(dict.get('U')).subarray(0, 48);
  14628. var userValidationSalt = stringToBytes(dict.get('U')).subarray(32, 40);
  14629. var userKeySalt = stringToBytes(dict.get('U')).subarray(40, 48);
  14630. var ownerEncryption = stringToBytes(dict.get('OE'));
  14631. var userEncryption = stringToBytes(dict.get('UE'));
  14632. var perms = stringToBytes(dict.get('Perms'));
  14633. encryptionKey =
  14634. createEncryptionKey20(revision, passwordBytes,
  14635. ownerPassword, ownerValidationSalt,
  14636. ownerKeySalt, uBytes,
  14637. userPassword, userValidationSalt,
  14638. userKeySalt, ownerEncryption,
  14639. userEncryption, perms);
  14640. }
  14641. if (!encryptionKey && !password) {
  14642. throw new PasswordException('No password given',
  14643. PasswordResponses.NEED_PASSWORD);
  14644. } else if (!encryptionKey && password) {
  14645. // Attempting use the password as an owner password
  14646. var decodedPassword = decodeUserPassword(passwordBytes, ownerPassword,
  14647. revision, keyLength);
  14648. encryptionKey = prepareKeyData(fileIdBytes, decodedPassword,
  14649. ownerPassword, userPassword, flags,
  14650. revision, keyLength, encryptMetadata);
  14651. }
  14652. if (!encryptionKey) {
  14653. throw new PasswordException('Incorrect Password',
  14654. PasswordResponses.INCORRECT_PASSWORD);
  14655. }
  14656. this.encryptionKey = encryptionKey;
  14657. if (algorithm >= 4) {
  14658. this.cf = dict.get('CF');
  14659. this.stmf = dict.get('StmF') || identityName;
  14660. this.strf = dict.get('StrF') || identityName;
  14661. this.eff = dict.get('EFF') || this.stmf;
  14662. }
  14663. }
  14664. function buildObjectKey(num, gen, encryptionKey, isAes) {
  14665. var key = new Uint8Array(encryptionKey.length + 9), i, n;
  14666. for (i = 0, n = encryptionKey.length; i < n; ++i) {
  14667. key[i] = encryptionKey[i];
  14668. }
  14669. key[i++] = num & 0xFF;
  14670. key[i++] = (num >> 8) & 0xFF;
  14671. key[i++] = (num >> 16) & 0xFF;
  14672. key[i++] = gen & 0xFF;
  14673. key[i++] = (gen >> 8) & 0xFF;
  14674. if (isAes) {
  14675. key[i++] = 0x73;
  14676. key[i++] = 0x41;
  14677. key[i++] = 0x6C;
  14678. key[i++] = 0x54;
  14679. }
  14680. var hash = calculateMD5(key, 0, i);
  14681. return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
  14682. }
  14683. function buildCipherConstructor(cf, name, num, gen, key) {
  14684. var cryptFilter = cf.get(name.name);
  14685. var cfm;
  14686. if (cryptFilter !== null && cryptFilter !== undefined) {
  14687. cfm = cryptFilter.get('CFM');
  14688. }
  14689. if (!cfm || cfm.name === 'None') {
  14690. return function cipherTransformFactoryBuildCipherConstructorNone() {
  14691. return new NullCipher();
  14692. };
  14693. }
  14694. if ('V2' === cfm.name) {
  14695. return function cipherTransformFactoryBuildCipherConstructorV2() {
  14696. return new ARCFourCipher(buildObjectKey(num, gen, key, false));
  14697. };
  14698. }
  14699. if ('AESV2' === cfm.name) {
  14700. return function cipherTransformFactoryBuildCipherConstructorAESV2() {
  14701. return new AES128Cipher(buildObjectKey(num, gen, key, true));
  14702. };
  14703. }
  14704. if ('AESV3' === cfm.name) {
  14705. return function cipherTransformFactoryBuildCipherConstructorAESV3() {
  14706. return new AES256Cipher(key);
  14707. };
  14708. }
  14709. error('Unknown crypto method');
  14710. }
  14711. CipherTransformFactory.prototype = {
  14712. createCipherTransform:
  14713. function CipherTransformFactory_createCipherTransform(num, gen) {
  14714. if (this.algorithm === 4 || this.algorithm === 5) {
  14715. return new CipherTransform(
  14716. buildCipherConstructor(this.cf, this.stmf,
  14717. num, gen, this.encryptionKey),
  14718. buildCipherConstructor(this.cf, this.strf,
  14719. num, gen, this.encryptionKey));
  14720. }
  14721. // algorithms 1 and 2
  14722. var key = buildObjectKey(num, gen, this.encryptionKey, false);
  14723. var cipherConstructor = function buildCipherCipherConstructor() {
  14724. return new ARCFourCipher(key);
  14725. };
  14726. return new CipherTransform(cipherConstructor, cipherConstructor);
  14727. }
  14728. };
  14729. return CipherTransformFactory;
  14730. })();
  14731. var PatternType = {
  14732. FUNCTION_BASED: 1,
  14733. AXIAL: 2,
  14734. RADIAL: 3,
  14735. FREE_FORM_MESH: 4,
  14736. LATTICE_FORM_MESH: 5,
  14737. COONS_PATCH_MESH: 6,
  14738. TENSOR_PATCH_MESH: 7
  14739. };
  14740. var Pattern = (function PatternClosure() {
  14741. // Constructor should define this.getPattern
  14742. function Pattern() {
  14743. error('should not call Pattern constructor');
  14744. }
  14745. Pattern.prototype = {
  14746. // Input: current Canvas context
  14747. // Output: the appropriate fillStyle or strokeStyle
  14748. getPattern: function Pattern_getPattern(ctx) {
  14749. error('Should not call Pattern.getStyle: ' + ctx);
  14750. }
  14751. };
  14752. Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref,
  14753. res) {
  14754. var dict = isStream(shading) ? shading.dict : shading;
  14755. var type = dict.get('ShadingType');
  14756. try {
  14757. switch (type) {
  14758. case PatternType.AXIAL:
  14759. case PatternType.RADIAL:
  14760. // Both radial and axial shadings are handled by RadialAxial shading.
  14761. return new Shadings.RadialAxial(dict, matrix, xref, res);
  14762. case PatternType.FREE_FORM_MESH:
  14763. case PatternType.LATTICE_FORM_MESH:
  14764. case PatternType.COONS_PATCH_MESH:
  14765. case PatternType.TENSOR_PATCH_MESH:
  14766. return new Shadings.Mesh(shading, matrix, xref, res);
  14767. default:
  14768. throw new Error('Unknown PatternType: ' + type);
  14769. }
  14770. } catch (ex) {
  14771. if (ex instanceof MissingDataException) {
  14772. throw ex;
  14773. }
  14774. UnsupportedManager.notify(UNSUPPORTED_FEATURES.shadingPattern);
  14775. warn(ex);
  14776. return new Shadings.Dummy();
  14777. }
  14778. };
  14779. return Pattern;
  14780. })();
  14781. var Shadings = {};
  14782. // A small number to offset the first/last color stops so we can insert ones to
  14783. // support extend. Number.MIN_VALUE appears to be too small and breaks the
  14784. // extend. 1e-7 works in FF but chrome seems to use an even smaller sized number
  14785. // internally so we have to go bigger.
  14786. Shadings.SMALL_NUMBER = 1e-2;
  14787. // Radial and axial shading have very similar implementations
  14788. // If needed, the implementations can be broken into two classes
  14789. Shadings.RadialAxial = (function RadialAxialClosure() {
  14790. function RadialAxial(dict, matrix, xref, res) {
  14791. this.matrix = matrix;
  14792. this.coordsArr = dict.get('Coords');
  14793. this.shadingType = dict.get('ShadingType');
  14794. this.type = 'Pattern';
  14795. var cs = dict.get('ColorSpace', 'CS');
  14796. cs = ColorSpace.parse(cs, xref, res);
  14797. this.cs = cs;
  14798. var t0 = 0.0, t1 = 1.0;
  14799. if (dict.has('Domain')) {
  14800. var domainArr = dict.get('Domain');
  14801. t0 = domainArr[0];
  14802. t1 = domainArr[1];
  14803. }
  14804. var extendStart = false, extendEnd = false;
  14805. if (dict.has('Extend')) {
  14806. var extendArr = dict.get('Extend');
  14807. extendStart = extendArr[0];
  14808. extendEnd = extendArr[1];
  14809. }
  14810. if (this.shadingType === PatternType.RADIAL &&
  14811. (!extendStart || !extendEnd)) {
  14812. // Radial gradient only currently works if either circle is fully within
  14813. // the other circle.
  14814. var x1 = this.coordsArr[0];
  14815. var y1 = this.coordsArr[1];
  14816. var r1 = this.coordsArr[2];
  14817. var x2 = this.coordsArr[3];
  14818. var y2 = this.coordsArr[4];
  14819. var r2 = this.coordsArr[5];
  14820. var distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  14821. if (r1 <= r2 + distance &&
  14822. r2 <= r1 + distance) {
  14823. warn('Unsupported radial gradient.');
  14824. }
  14825. }
  14826. this.extendStart = extendStart;
  14827. this.extendEnd = extendEnd;
  14828. var fnObj = dict.get('Function');
  14829. var fn = PDFFunction.parseArray(xref, fnObj);
  14830. // 10 samples seems good enough for now, but probably won't work
  14831. // if there are sharp color changes. Ideally, we would implement
  14832. // the spec faithfully and add lossless optimizations.
  14833. var diff = t1 - t0;
  14834. var step = diff / 10;
  14835. var colorStops = this.colorStops = [];
  14836. // Protect against bad domains so we don't end up in an infinte loop below.
  14837. if (t0 >= t1 || step <= 0) {
  14838. // Acrobat doesn't seem to handle these cases so we'll ignore for
  14839. // now.
  14840. info('Bad shading domain.');
  14841. return;
  14842. }
  14843. var color = new Float32Array(cs.numComps), ratio = new Float32Array(1);
  14844. var rgbColor;
  14845. for (var i = t0; i <= t1; i += step) {
  14846. ratio[0] = i;
  14847. fn(ratio, 0, color, 0);
  14848. rgbColor = cs.getRgb(color, 0);
  14849. var cssColor = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
  14850. colorStops.push([(i - t0) / diff, cssColor]);
  14851. }
  14852. var background = 'transparent';
  14853. if (dict.has('Background')) {
  14854. rgbColor = cs.getRgb(dict.get('Background'), 0);
  14855. background = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
  14856. }
  14857. if (!extendStart) {
  14858. // Insert a color stop at the front and offset the first real color stop
  14859. // so it doesn't conflict with the one we insert.
  14860. colorStops.unshift([0, background]);
  14861. colorStops[1][0] += Shadings.SMALL_NUMBER;
  14862. }
  14863. if (!extendEnd) {
  14864. // Same idea as above in extendStart but for the end.
  14865. colorStops[colorStops.length - 1][0] -= Shadings.SMALL_NUMBER;
  14866. colorStops.push([1, background]);
  14867. }
  14868. this.colorStops = colorStops;
  14869. }
  14870. RadialAxial.prototype = {
  14871. getIR: function RadialAxial_getIR() {
  14872. var coordsArr = this.coordsArr;
  14873. var shadingType = this.shadingType;
  14874. var type, p0, p1, r0, r1;
  14875. if (shadingType === PatternType.AXIAL) {
  14876. p0 = [coordsArr[0], coordsArr[1]];
  14877. p1 = [coordsArr[2], coordsArr[3]];
  14878. r0 = null;
  14879. r1 = null;
  14880. type = 'axial';
  14881. } else if (shadingType === PatternType.RADIAL) {
  14882. p0 = [coordsArr[0], coordsArr[1]];
  14883. p1 = [coordsArr[3], coordsArr[4]];
  14884. r0 = coordsArr[2];
  14885. r1 = coordsArr[5];
  14886. type = 'radial';
  14887. } else {
  14888. error('getPattern type unknown: ' + shadingType);
  14889. }
  14890. var matrix = this.matrix;
  14891. if (matrix) {
  14892. p0 = Util.applyTransform(p0, matrix);
  14893. p1 = Util.applyTransform(p1, matrix);
  14894. }
  14895. return ['RadialAxial', type, this.colorStops, p0, p1, r0, r1];
  14896. }
  14897. };
  14898. return RadialAxial;
  14899. })();
  14900. // All mesh shading. For now, they will be presented as set of the triangles
  14901. // to be drawn on the canvas and rgb color for each vertex.
  14902. Shadings.Mesh = (function MeshClosure() {
  14903. function MeshStreamReader(stream, context) {
  14904. this.stream = stream;
  14905. this.context = context;
  14906. this.buffer = 0;
  14907. this.bufferLength = 0;
  14908. var numComps = context.numComps;
  14909. this.tmpCompsBuf = new Float32Array(numComps);
  14910. var csNumComps = context.colorSpace;
  14911. this.tmpCsCompsBuf = context.colorFn ? new Float32Array(csNumComps) :
  14912. this.tmpCompsBuf;
  14913. }
  14914. MeshStreamReader.prototype = {
  14915. get hasData() {
  14916. if (this.stream.end) {
  14917. return this.stream.pos < this.stream.end;
  14918. }
  14919. if (this.bufferLength > 0) {
  14920. return true;
  14921. }
  14922. var nextByte = this.stream.getByte();
  14923. if (nextByte < 0) {
  14924. return false;
  14925. }
  14926. this.buffer = nextByte;
  14927. this.bufferLength = 8;
  14928. return true;
  14929. },
  14930. readBits: function MeshStreamReader_readBits(n) {
  14931. var buffer = this.buffer;
  14932. var bufferLength = this.bufferLength;
  14933. if (n === 32) {
  14934. if (bufferLength === 0) {
  14935. return ((this.stream.getByte() << 24) |
  14936. (this.stream.getByte() << 16) | (this.stream.getByte() << 8) |
  14937. this.stream.getByte()) >>> 0;
  14938. }
  14939. buffer = (buffer << 24) | (this.stream.getByte() << 16) |
  14940. (this.stream.getByte() << 8) | this.stream.getByte();
  14941. var nextByte = this.stream.getByte();
  14942. this.buffer = nextByte & ((1 << bufferLength) - 1);
  14943. return ((buffer << (8 - bufferLength)) |
  14944. ((nextByte & 0xFF) >> bufferLength)) >>> 0;
  14945. }
  14946. if (n === 8 && bufferLength === 0) {
  14947. return this.stream.getByte();
  14948. }
  14949. while (bufferLength < n) {
  14950. buffer = (buffer << 8) | this.stream.getByte();
  14951. bufferLength += 8;
  14952. }
  14953. bufferLength -= n;
  14954. this.bufferLength = bufferLength;
  14955. this.buffer = buffer & ((1 << bufferLength) - 1);
  14956. return buffer >> bufferLength;
  14957. },
  14958. align: function MeshStreamReader_align() {
  14959. this.buffer = 0;
  14960. this.bufferLength = 0;
  14961. },
  14962. readFlag: function MeshStreamReader_readFlag() {
  14963. return this.readBits(this.context.bitsPerFlag);
  14964. },
  14965. readCoordinate: function MeshStreamReader_readCoordinate() {
  14966. var bitsPerCoordinate = this.context.bitsPerCoordinate;
  14967. var xi = this.readBits(bitsPerCoordinate);
  14968. var yi = this.readBits(bitsPerCoordinate);
  14969. var decode = this.context.decode;
  14970. var scale = bitsPerCoordinate < 32 ? 1 / ((1 << bitsPerCoordinate) - 1) :
  14971. 2.3283064365386963e-10; // 2 ^ -32
  14972. return [
  14973. xi * scale * (decode[1] - decode[0]) + decode[0],
  14974. yi * scale * (decode[3] - decode[2]) + decode[2]
  14975. ];
  14976. },
  14977. readComponents: function MeshStreamReader_readComponents() {
  14978. var numComps = this.context.numComps;
  14979. var bitsPerComponent = this.context.bitsPerComponent;
  14980. var scale = bitsPerComponent < 32 ? 1 / ((1 << bitsPerComponent) - 1) :
  14981. 2.3283064365386963e-10; // 2 ^ -32
  14982. var decode = this.context.decode;
  14983. var components = this.tmpCompsBuf;
  14984. for (var i = 0, j = 4; i < numComps; i++, j += 2) {
  14985. var ci = this.readBits(bitsPerComponent);
  14986. components[i] = ci * scale * (decode[j + 1] - decode[j]) + decode[j];
  14987. }
  14988. var color = this.tmpCsCompsBuf;
  14989. if (this.context.colorFn) {
  14990. this.context.colorFn(components, 0, color, 0);
  14991. }
  14992. return this.context.colorSpace.getRgb(color, 0);
  14993. }
  14994. };
  14995. function decodeType4Shading(mesh, reader) {
  14996. var coords = mesh.coords;
  14997. var colors = mesh.colors;
  14998. var operators = [];
  14999. var ps = []; // not maintaining cs since that will match ps
  15000. var verticesLeft = 0; // assuming we have all data to start a new triangle
  15001. while (reader.hasData) {
  15002. var f = reader.readFlag();
  15003. var coord = reader.readCoordinate();
  15004. var color = reader.readComponents();
  15005. if (verticesLeft === 0) { // ignoring flags if we started a triangle
  15006. assert(0 <= f && f <= 2, 'Unknown type4 flag');
  15007. switch (f) {
  15008. case 0:
  15009. verticesLeft = 3;
  15010. break;
  15011. case 1:
  15012. ps.push(ps[ps.length - 2], ps[ps.length - 1]);
  15013. verticesLeft = 1;
  15014. break;
  15015. case 2:
  15016. ps.push(ps[ps.length - 3], ps[ps.length - 1]);
  15017. verticesLeft = 1;
  15018. break;
  15019. }
  15020. operators.push(f);
  15021. }
  15022. ps.push(coords.length);
  15023. coords.push(coord);
  15024. colors.push(color);
  15025. verticesLeft--;
  15026. reader.align();
  15027. }
  15028. var psPacked = new Int32Array(ps);
  15029. mesh.figures.push({
  15030. type: 'triangles',
  15031. coords: psPacked,
  15032. colors: psPacked
  15033. });
  15034. }
  15035. function decodeType5Shading(mesh, reader, verticesPerRow) {
  15036. var coords = mesh.coords;
  15037. var colors = mesh.colors;
  15038. var ps = []; // not maintaining cs since that will match ps
  15039. while (reader.hasData) {
  15040. var coord = reader.readCoordinate();
  15041. var color = reader.readComponents();
  15042. ps.push(coords.length);
  15043. coords.push(coord);
  15044. colors.push(color);
  15045. }
  15046. var psPacked = new Int32Array(ps);
  15047. mesh.figures.push({
  15048. type: 'lattice',
  15049. coords: psPacked,
  15050. colors: psPacked,
  15051. verticesPerRow: verticesPerRow
  15052. });
  15053. }
  15054. var MIN_SPLIT_PATCH_CHUNKS_AMOUNT = 3;
  15055. var MAX_SPLIT_PATCH_CHUNKS_AMOUNT = 20;
  15056. var TRIANGLE_DENSITY = 20; // count of triangles per entire mesh bounds
  15057. var getB = (function getBClosure() {
  15058. function buildB(count) {
  15059. var lut = [];
  15060. for (var i = 0; i <= count; i++) {
  15061. var t = i / count, t_ = 1 - t;
  15062. lut.push(new Float32Array([t_ * t_ * t_, 3 * t * t_ * t_,
  15063. 3 * t * t * t_, t * t * t]));
  15064. }
  15065. return lut;
  15066. }
  15067. var cache = [];
  15068. return function getB(count) {
  15069. if (!cache[count]) {
  15070. cache[count] = buildB(count);
  15071. }
  15072. return cache[count];
  15073. };
  15074. })();
  15075. function buildFigureFromPatch(mesh, index) {
  15076. var figure = mesh.figures[index];
  15077. assert(figure.type === 'patch', 'Unexpected patch mesh figure');
  15078. var coords = mesh.coords, colors = mesh.colors;
  15079. var pi = figure.coords;
  15080. var ci = figure.colors;
  15081. var figureMinX = Math.min(coords[pi[0]][0], coords[pi[3]][0],
  15082. coords[pi[12]][0], coords[pi[15]][0]);
  15083. var figureMinY = Math.min(coords[pi[0]][1], coords[pi[3]][1],
  15084. coords[pi[12]][1], coords[pi[15]][1]);
  15085. var figureMaxX = Math.max(coords[pi[0]][0], coords[pi[3]][0],
  15086. coords[pi[12]][0], coords[pi[15]][0]);
  15087. var figureMaxY = Math.max(coords[pi[0]][1], coords[pi[3]][1],
  15088. coords[pi[12]][1], coords[pi[15]][1]);
  15089. var splitXBy = Math.ceil((figureMaxX - figureMinX) * TRIANGLE_DENSITY /
  15090. (mesh.bounds[2] - mesh.bounds[0]));
  15091. splitXBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
  15092. Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitXBy));
  15093. var splitYBy = Math.ceil((figureMaxY - figureMinY) * TRIANGLE_DENSITY /
  15094. (mesh.bounds[3] - mesh.bounds[1]));
  15095. splitYBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
  15096. Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitYBy));
  15097. var verticesPerRow = splitXBy + 1;
  15098. var figureCoords = new Int32Array((splitYBy + 1) * verticesPerRow);
  15099. var figureColors = new Int32Array((splitYBy + 1) * verticesPerRow);
  15100. var k = 0;
  15101. var cl = new Uint8Array(3), cr = new Uint8Array(3);
  15102. var c0 = colors[ci[0]], c1 = colors[ci[1]],
  15103. c2 = colors[ci[2]], c3 = colors[ci[3]];
  15104. var bRow = getB(splitYBy), bCol = getB(splitXBy);
  15105. for (var row = 0; row <= splitYBy; row++) {
  15106. cl[0] = ((c0[0] * (splitYBy - row) + c2[0] * row) / splitYBy) | 0;
  15107. cl[1] = ((c0[1] * (splitYBy - row) + c2[1] * row) / splitYBy) | 0;
  15108. cl[2] = ((c0[2] * (splitYBy - row) + c2[2] * row) / splitYBy) | 0;
  15109. cr[0] = ((c1[0] * (splitYBy - row) + c3[0] * row) / splitYBy) | 0;
  15110. cr[1] = ((c1[1] * (splitYBy - row) + c3[1] * row) / splitYBy) | 0;
  15111. cr[2] = ((c1[2] * (splitYBy - row) + c3[2] * row) / splitYBy) | 0;
  15112. for (var col = 0; col <= splitXBy; col++, k++) {
  15113. if ((row === 0 || row === splitYBy) &&
  15114. (col === 0 || col === splitXBy)) {
  15115. continue;
  15116. }
  15117. var x = 0, y = 0;
  15118. var q = 0;
  15119. for (var i = 0; i <= 3; i++) {
  15120. for (var j = 0; j <= 3; j++, q++) {
  15121. var m = bRow[row][i] * bCol[col][j];
  15122. x += coords[pi[q]][0] * m;
  15123. y += coords[pi[q]][1] * m;
  15124. }
  15125. }
  15126. figureCoords[k] = coords.length;
  15127. coords.push([x, y]);
  15128. figureColors[k] = colors.length;
  15129. var newColor = new Uint8Array(3);
  15130. newColor[0] = ((cl[0] * (splitXBy - col) + cr[0] * col) / splitXBy) | 0;
  15131. newColor[1] = ((cl[1] * (splitXBy - col) + cr[1] * col) / splitXBy) | 0;
  15132. newColor[2] = ((cl[2] * (splitXBy - col) + cr[2] * col) / splitXBy) | 0;
  15133. colors.push(newColor);
  15134. }
  15135. }
  15136. figureCoords[0] = pi[0];
  15137. figureColors[0] = ci[0];
  15138. figureCoords[splitXBy] = pi[3];
  15139. figureColors[splitXBy] = ci[1];
  15140. figureCoords[verticesPerRow * splitYBy] = pi[12];
  15141. figureColors[verticesPerRow * splitYBy] = ci[2];
  15142. figureCoords[verticesPerRow * splitYBy + splitXBy] = pi[15];
  15143. figureColors[verticesPerRow * splitYBy + splitXBy] = ci[3];
  15144. mesh.figures[index] = {
  15145. type: 'lattice',
  15146. coords: figureCoords,
  15147. colors: figureColors,
  15148. verticesPerRow: verticesPerRow
  15149. };
  15150. }
  15151. function decodeType6Shading(mesh, reader) {
  15152. // A special case of Type 7. The p11, p12, p21, p22 automatically filled
  15153. var coords = mesh.coords;
  15154. var colors = mesh.colors;
  15155. var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33
  15156. var cs = new Int32Array(4); // c00, c30, c03, c33
  15157. while (reader.hasData) {
  15158. var f = reader.readFlag();
  15159. assert(0 <= f && f <= 3, 'Unknown type6 flag');
  15160. var i, ii;
  15161. var pi = coords.length;
  15162. for (i = 0, ii = (f !== 0 ? 8 : 12); i < ii; i++) {
  15163. coords.push(reader.readCoordinate());
  15164. }
  15165. var ci = colors.length;
  15166. for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {
  15167. colors.push(reader.readComponents());
  15168. }
  15169. var tmp1, tmp2, tmp3, tmp4;
  15170. switch (f) {
  15171. case 0:
  15172. ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;
  15173. ps[ 8] = pi + 2; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;
  15174. ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 8;
  15175. ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;
  15176. cs[2] = ci + 1; cs[3] = ci + 2;
  15177. cs[0] = ci; cs[1] = ci + 3;
  15178. break;
  15179. case 1:
  15180. tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];
  15181. ps[12] = pi + 5; ps[13] = pi + 4; ps[14] = pi + 3; ps[15] = pi + 2;
  15182. ps[ 8] = pi + 6; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 1;
  15183. ps[ 4] = pi + 7; /* calculated below */ ps[ 7] = pi;
  15184. ps[ 0] = tmp1; ps[ 1] = tmp2; ps[ 2] = tmp3; ps[ 3] = tmp4;
  15185. tmp1 = cs[2]; tmp2 = cs[3];
  15186. cs[2] = ci + 1; cs[3] = ci;
  15187. cs[0] = tmp1; cs[1] = tmp2;
  15188. break;
  15189. case 2:
  15190. ps[12] = ps[15]; ps[13] = pi + 7; ps[14] = pi + 6; ps[15] = pi + 5;
  15191. ps[ 8] = ps[11]; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 4;
  15192. ps[ 4] = ps[7]; /* calculated below */ ps[ 7] = pi + 3;
  15193. ps[ 0] = ps[3]; ps[ 1] = pi; ps[ 2] = pi + 1; ps[ 3] = pi + 2;
  15194. cs[2] = cs[3]; cs[3] = ci + 1;
  15195. cs[0] = cs[1]; cs[1] = ci;
  15196. break;
  15197. case 3:
  15198. ps[12] = ps[0]; ps[13] = ps[1]; ps[14] = ps[2]; ps[15] = ps[3];
  15199. ps[ 8] = pi; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;
  15200. ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 6;
  15201. ps[ 0] = pi + 2; ps[ 1] = pi + 3; ps[ 2] = pi + 4; ps[ 3] = pi + 5;
  15202. cs[2] = cs[0]; cs[3] = cs[1];
  15203. cs[0] = ci; cs[1] = ci + 1;
  15204. break;
  15205. }
  15206. // set p11, p12, p21, p22
  15207. ps[5] = coords.length;
  15208. coords.push([
  15209. (-4 * coords[ps[0]][0] - coords[ps[15]][0] +
  15210. 6 * (coords[ps[4]][0] + coords[ps[1]][0]) -
  15211. 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +
  15212. 3 * (coords[ps[13]][0] + coords[ps[7]][0])) / 9,
  15213. (-4 * coords[ps[0]][1] - coords[ps[15]][1] +
  15214. 6 * (coords[ps[4]][1] + coords[ps[1]][1]) -
  15215. 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +
  15216. 3 * (coords[ps[13]][1] + coords[ps[7]][1])) / 9
  15217. ]);
  15218. ps[6] = coords.length;
  15219. coords.push([
  15220. (-4 * coords[ps[3]][0] - coords[ps[12]][0] +
  15221. 6 * (coords[ps[2]][0] + coords[ps[7]][0]) -
  15222. 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +
  15223. 3 * (coords[ps[4]][0] + coords[ps[14]][0])) / 9,
  15224. (-4 * coords[ps[3]][1] - coords[ps[12]][1] +
  15225. 6 * (coords[ps[2]][1] + coords[ps[7]][1]) -
  15226. 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +
  15227. 3 * (coords[ps[4]][1] + coords[ps[14]][1])) / 9
  15228. ]);
  15229. ps[9] = coords.length;
  15230. coords.push([
  15231. (-4 * coords[ps[12]][0] - coords[ps[3]][0] +
  15232. 6 * (coords[ps[8]][0] + coords[ps[13]][0]) -
  15233. 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +
  15234. 3 * (coords[ps[11]][0] + coords[ps[1]][0])) / 9,
  15235. (-4 * coords[ps[12]][1] - coords[ps[3]][1] +
  15236. 6 * (coords[ps[8]][1] + coords[ps[13]][1]) -
  15237. 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +
  15238. 3 * (coords[ps[11]][1] + coords[ps[1]][1])) / 9
  15239. ]);
  15240. ps[10] = coords.length;
  15241. coords.push([
  15242. (-4 * coords[ps[15]][0] - coords[ps[0]][0] +
  15243. 6 * (coords[ps[11]][0] + coords[ps[14]][0]) -
  15244. 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +
  15245. 3 * (coords[ps[2]][0] + coords[ps[8]][0])) / 9,
  15246. (-4 * coords[ps[15]][1] - coords[ps[0]][1] +
  15247. 6 * (coords[ps[11]][1] + coords[ps[14]][1]) -
  15248. 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +
  15249. 3 * (coords[ps[2]][1] + coords[ps[8]][1])) / 9
  15250. ]);
  15251. mesh.figures.push({
  15252. type: 'patch',
  15253. coords: new Int32Array(ps), // making copies of ps and cs
  15254. colors: new Int32Array(cs)
  15255. });
  15256. }
  15257. }
  15258. function decodeType7Shading(mesh, reader) {
  15259. var coords = mesh.coords;
  15260. var colors = mesh.colors;
  15261. var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33
  15262. var cs = new Int32Array(4); // c00, c30, c03, c33
  15263. while (reader.hasData) {
  15264. var f = reader.readFlag();
  15265. assert(0 <= f && f <= 3, 'Unknown type7 flag');
  15266. var i, ii;
  15267. var pi = coords.length;
  15268. for (i = 0, ii = (f !== 0 ? 12 : 16); i < ii; i++) {
  15269. coords.push(reader.readCoordinate());
  15270. }
  15271. var ci = colors.length;
  15272. for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {
  15273. colors.push(reader.readComponents());
  15274. }
  15275. var tmp1, tmp2, tmp3, tmp4;
  15276. switch (f) {
  15277. case 0:
  15278. ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;
  15279. ps[ 8] = pi + 2; ps[ 9] = pi + 13; ps[10] = pi + 14; ps[11] = pi + 7;
  15280. ps[ 4] = pi + 1; ps[ 5] = pi + 12; ps[ 6] = pi + 15; ps[ 7] = pi + 8;
  15281. ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;
  15282. cs[2] = ci + 1; cs[3] = ci + 2;
  15283. cs[0] = ci; cs[1] = ci + 3;
  15284. break;
  15285. case 1:
  15286. tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];
  15287. ps[12] = pi + 5; ps[13] = pi + 4; ps[14] = pi + 3; ps[15] = pi + 2;
  15288. ps[ 8] = pi + 6; ps[ 9] = pi + 11; ps[10] = pi + 10; ps[11] = pi + 1;
  15289. ps[ 4] = pi + 7; ps[ 5] = pi + 8; ps[ 6] = pi + 9; ps[ 7] = pi;
  15290. ps[ 0] = tmp1; ps[ 1] = tmp2; ps[ 2] = tmp3; ps[ 3] = tmp4;
  15291. tmp1 = cs[2]; tmp2 = cs[3];
  15292. cs[2] = ci + 1; cs[3] = ci;
  15293. cs[0] = tmp1; cs[1] = tmp2;
  15294. break;
  15295. case 2:
  15296. ps[12] = ps[15]; ps[13] = pi + 7; ps[14] = pi + 6; ps[15] = pi + 5;
  15297. ps[ 8] = ps[11]; ps[ 9] = pi + 8; ps[10] = pi + 11; ps[11] = pi + 4;
  15298. ps[ 4] = ps[7]; ps[ 5] = pi + 9; ps[ 6] = pi + 10; ps[ 7] = pi + 3;
  15299. ps[ 0] = ps[3]; ps[ 1] = pi; ps[ 2] = pi + 1; ps[ 3] = pi + 2;
  15300. cs[2] = cs[3]; cs[3] = ci + 1;
  15301. cs[0] = cs[1]; cs[1] = ci;
  15302. break;
  15303. case 3:
  15304. ps[12] = ps[0]; ps[13] = ps[1]; ps[14] = ps[2]; ps[15] = ps[3];
  15305. ps[ 8] = pi; ps[ 9] = pi + 9; ps[10] = pi + 8; ps[11] = pi + 7;
  15306. ps[ 4] = pi + 1; ps[ 5] = pi + 10; ps[ 6] = pi + 11; ps[ 7] = pi + 6;
  15307. ps[ 0] = pi + 2; ps[ 1] = pi + 3; ps[ 2] = pi + 4; ps[ 3] = pi + 5;
  15308. cs[2] = cs[0]; cs[3] = cs[1];
  15309. cs[0] = ci; cs[1] = ci + 1;
  15310. break;
  15311. }
  15312. mesh.figures.push({
  15313. type: 'patch',
  15314. coords: new Int32Array(ps), // making copies of ps and cs
  15315. colors: new Int32Array(cs)
  15316. });
  15317. }
  15318. }
  15319. function updateBounds(mesh) {
  15320. var minX = mesh.coords[0][0], minY = mesh.coords[0][1],
  15321. maxX = minX, maxY = minY;
  15322. for (var i = 1, ii = mesh.coords.length; i < ii; i++) {
  15323. var x = mesh.coords[i][0], y = mesh.coords[i][1];
  15324. minX = minX > x ? x : minX;
  15325. minY = minY > y ? y : minY;
  15326. maxX = maxX < x ? x : maxX;
  15327. maxY = maxY < y ? y : maxY;
  15328. }
  15329. mesh.bounds = [minX, minY, maxX, maxY];
  15330. }
  15331. function packData(mesh) {
  15332. var i, ii, j, jj;
  15333. var coords = mesh.coords;
  15334. var coordsPacked = new Float32Array(coords.length * 2);
  15335. for (i = 0, j = 0, ii = coords.length; i < ii; i++) {
  15336. var xy = coords[i];
  15337. coordsPacked[j++] = xy[0];
  15338. coordsPacked[j++] = xy[1];
  15339. }
  15340. mesh.coords = coordsPacked;
  15341. var colors = mesh.colors;
  15342. var colorsPacked = new Uint8Array(colors.length * 3);
  15343. for (i = 0, j = 0, ii = colors.length; i < ii; i++) {
  15344. var c = colors[i];
  15345. colorsPacked[j++] = c[0];
  15346. colorsPacked[j++] = c[1];
  15347. colorsPacked[j++] = c[2];
  15348. }
  15349. mesh.colors = colorsPacked;
  15350. var figures = mesh.figures;
  15351. for (i = 0, ii = figures.length; i < ii; i++) {
  15352. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  15353. for (j = 0, jj = ps.length; j < jj; j++) {
  15354. ps[j] *= 2;
  15355. cs[j] *= 3;
  15356. }
  15357. }
  15358. }
  15359. function Mesh(stream, matrix, xref, res) {
  15360. assert(isStream(stream), 'Mesh data is not a stream');
  15361. var dict = stream.dict;
  15362. this.matrix = matrix;
  15363. this.shadingType = dict.get('ShadingType');
  15364. this.type = 'Pattern';
  15365. this.bbox = dict.get('BBox');
  15366. var cs = dict.get('ColorSpace', 'CS');
  15367. cs = ColorSpace.parse(cs, xref, res);
  15368. this.cs = cs;
  15369. this.background = dict.has('Background') ?
  15370. cs.getRgb(dict.get('Background'), 0) : null;
  15371. var fnObj = dict.get('Function');
  15372. var fn = fnObj ? PDFFunction.parseArray(xref, fnObj) : null;
  15373. this.coords = [];
  15374. this.colors = [];
  15375. this.figures = [];
  15376. var decodeContext = {
  15377. bitsPerCoordinate: dict.get('BitsPerCoordinate'),
  15378. bitsPerComponent: dict.get('BitsPerComponent'),
  15379. bitsPerFlag: dict.get('BitsPerFlag'),
  15380. decode: dict.get('Decode'),
  15381. colorFn: fn,
  15382. colorSpace: cs,
  15383. numComps: fn ? 1 : cs.numComps
  15384. };
  15385. var reader = new MeshStreamReader(stream, decodeContext);
  15386. var patchMesh = false;
  15387. switch (this.shadingType) {
  15388. case PatternType.FREE_FORM_MESH:
  15389. decodeType4Shading(this, reader);
  15390. break;
  15391. case PatternType.LATTICE_FORM_MESH:
  15392. var verticesPerRow = dict.get('VerticesPerRow') | 0;
  15393. assert(verticesPerRow >= 2, 'Invalid VerticesPerRow');
  15394. decodeType5Shading(this, reader, verticesPerRow);
  15395. break;
  15396. case PatternType.COONS_PATCH_MESH:
  15397. decodeType6Shading(this, reader);
  15398. patchMesh = true;
  15399. break;
  15400. case PatternType.TENSOR_PATCH_MESH:
  15401. decodeType7Shading(this, reader);
  15402. patchMesh = true;
  15403. break;
  15404. default:
  15405. error('Unsupported mesh type.');
  15406. break;
  15407. }
  15408. if (patchMesh) {
  15409. // dirty bounds calculation for determining, how dense shall be triangles
  15410. updateBounds(this);
  15411. for (var i = 0, ii = this.figures.length; i < ii; i++) {
  15412. buildFigureFromPatch(this, i);
  15413. }
  15414. }
  15415. // calculate bounds
  15416. updateBounds(this);
  15417. packData(this);
  15418. }
  15419. Mesh.prototype = {
  15420. getIR: function Mesh_getIR() {
  15421. return ['Mesh', this.shadingType, this.coords, this.colors, this.figures,
  15422. this.bounds, this.matrix, this.bbox, this.background];
  15423. }
  15424. };
  15425. return Mesh;
  15426. })();
  15427. Shadings.Dummy = (function DummyClosure() {
  15428. function Dummy() {
  15429. this.type = 'Pattern';
  15430. }
  15431. Dummy.prototype = {
  15432. getIR: function Dummy_getIR() {
  15433. return ['Dummy'];
  15434. }
  15435. };
  15436. return Dummy;
  15437. })();
  15438. function getTilingPatternIR(operatorList, dict, args) {
  15439. var matrix = dict.get('Matrix');
  15440. var bbox = dict.get('BBox');
  15441. var xstep = dict.get('XStep');
  15442. var ystep = dict.get('YStep');
  15443. var paintType = dict.get('PaintType');
  15444. var tilingType = dict.get('TilingType');
  15445. return [
  15446. 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep,
  15447. paintType, tilingType
  15448. ];
  15449. }
  15450. var PartialEvaluator = (function PartialEvaluatorClosure() {
  15451. function PartialEvaluator(pdfManager, xref, handler, pageIndex,
  15452. uniquePrefix, idCounters, fontCache) {
  15453. this.pdfManager = pdfManager;
  15454. this.xref = xref;
  15455. this.handler = handler;
  15456. this.pageIndex = pageIndex;
  15457. this.uniquePrefix = uniquePrefix;
  15458. this.idCounters = idCounters;
  15459. this.fontCache = fontCache;
  15460. }
  15461. // Trying to minimize Date.now() usage and check every 100 time
  15462. var TIME_SLOT_DURATION_MS = 20;
  15463. var CHECK_TIME_EVERY = 100;
  15464. function TimeSlotManager() {
  15465. this.reset();
  15466. }
  15467. TimeSlotManager.prototype = {
  15468. check: function TimeSlotManager_check() {
  15469. if (++this.checked < CHECK_TIME_EVERY) {
  15470. return false;
  15471. }
  15472. this.checked = 0;
  15473. return this.endTime <= Date.now();
  15474. },
  15475. reset: function TimeSlotManager_reset() {
  15476. this.endTime = Date.now() + TIME_SLOT_DURATION_MS;
  15477. this.checked = 0;
  15478. }
  15479. };
  15480. var deferred = Promise.resolve();
  15481. var TILING_PATTERN = 1, SHADING_PATTERN = 2;
  15482. PartialEvaluator.prototype = {
  15483. hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {
  15484. if (!isDict(resources)) {
  15485. return false;
  15486. }
  15487. var processed = Object.create(null);
  15488. if (resources.objId) {
  15489. processed[resources.objId] = true;
  15490. }
  15491. var nodes = [resources];
  15492. while (nodes.length) {
  15493. var key;
  15494. var node = nodes.shift();
  15495. // First check the current resources for blend modes.
  15496. var graphicStates = node.get('ExtGState');
  15497. if (isDict(graphicStates)) {
  15498. graphicStates = graphicStates.getAll();
  15499. for (key in graphicStates) {
  15500. var graphicState = graphicStates[key];
  15501. var bm = graphicState['BM'];
  15502. if (isName(bm) && bm.name !== 'Normal') {
  15503. return true;
  15504. }
  15505. }
  15506. }
  15507. // Descend into the XObjects to look for more resources and blend modes.
  15508. var xObjects = node.get('XObject');
  15509. if (!isDict(xObjects)) {
  15510. continue;
  15511. }
  15512. xObjects = xObjects.getAll();
  15513. for (key in xObjects) {
  15514. var xObject = xObjects[key];
  15515. if (!isStream(xObject)) {
  15516. continue;
  15517. }
  15518. if (xObject.dict.objId) {
  15519. if (processed[xObject.dict.objId]) {
  15520. // stream has objId and is processed already
  15521. continue;
  15522. }
  15523. processed[xObject.dict.objId] = true;
  15524. }
  15525. var xResources = xObject.dict.get('Resources');
  15526. // Checking objId to detect an infinite loop.
  15527. if (isDict(xResources) &&
  15528. (!xResources.objId || !processed[xResources.objId])) {
  15529. nodes.push(xResources);
  15530. if (xResources.objId) {
  15531. processed[xResources.objId] = true;
  15532. }
  15533. }
  15534. }
  15535. }
  15536. return false;
  15537. },
  15538. buildFormXObject: function PartialEvaluator_buildFormXObject(resources,
  15539. xobj, smask,
  15540. operatorList,
  15541. initialState) {
  15542. var matrix = xobj.dict.get('Matrix');
  15543. var bbox = xobj.dict.get('BBox');
  15544. var group = xobj.dict.get('Group');
  15545. if (group) {
  15546. var groupOptions = {
  15547. matrix: matrix,
  15548. bbox: bbox,
  15549. smask: smask,
  15550. isolated: false,
  15551. knockout: false
  15552. };
  15553. var groupSubtype = group.get('S');
  15554. var colorSpace;
  15555. if (isName(groupSubtype) && groupSubtype.name === 'Transparency') {
  15556. groupOptions.isolated = (group.get('I') || false);
  15557. groupOptions.knockout = (group.get('K') || false);
  15558. colorSpace = (group.has('CS') ?
  15559. ColorSpace.parse(group.get('CS'), this.xref, resources) : null);
  15560. }
  15561. if (smask && smask.backdrop) {
  15562. colorSpace = colorSpace || ColorSpace.singletons.rgb;
  15563. smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
  15564. }
  15565. operatorList.addOp(OPS.beginGroup, [groupOptions]);
  15566. }
  15567. operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]);
  15568. return this.getOperatorList(xobj,
  15569. (xobj.dict.get('Resources') || resources), operatorList, initialState).
  15570. then(function () {
  15571. operatorList.addOp(OPS.paintFormXObjectEnd, []);
  15572. if (group) {
  15573. operatorList.addOp(OPS.endGroup, [groupOptions]);
  15574. }
  15575. });
  15576. },
  15577. buildPaintImageXObject:
  15578. function PartialEvaluator_buildPaintImageXObject(resources, image,
  15579. inline, operatorList,
  15580. cacheKey, imageCache) {
  15581. var self = this;
  15582. var dict = image.dict;
  15583. var w = dict.get('Width', 'W');
  15584. var h = dict.get('Height', 'H');
  15585. if (!(w && isNum(w)) || !(h && isNum(h))) {
  15586. warn('Image dimensions are missing, or not numbers.');
  15587. return;
  15588. }
  15589. if (PDFJS.maxImageSize !== -1 && w * h > PDFJS.maxImageSize) {
  15590. warn('Image exceeded maximum allowed size and was removed.');
  15591. return;
  15592. }
  15593. var imageMask = (dict.get('ImageMask', 'IM') || false);
  15594. var imgData, args;
  15595. if (imageMask) {
  15596. // This depends on a tmpCanvas being filled with the
  15597. // current fillStyle, such that processing the pixel
  15598. // data can't be done here. Instead of creating a
  15599. // complete PDFImage, only read the information needed
  15600. // for later.
  15601. var width = dict.get('Width', 'W');
  15602. var height = dict.get('Height', 'H');
  15603. var bitStrideLength = (width + 7) >> 3;
  15604. var imgArray = image.getBytes(bitStrideLength * height);
  15605. var decode = dict.get('Decode', 'D');
  15606. var inverseDecode = (!!decode && decode[0] > 0);
  15607. imgData = PDFImage.createMask(imgArray, width, height,
  15608. image instanceof DecodeStream,
  15609. inverseDecode);
  15610. imgData.cached = true;
  15611. args = [imgData];
  15612. operatorList.addOp(OPS.paintImageMaskXObject, args);
  15613. if (cacheKey) {
  15614. imageCache[cacheKey] = {
  15615. fn: OPS.paintImageMaskXObject,
  15616. args: args
  15617. };
  15618. }
  15619. return;
  15620. }
  15621. var softMask = (dict.get('SMask', 'SM') || false);
  15622. var mask = (dict.get('Mask') || false);
  15623. var SMALL_IMAGE_DIMENSIONS = 200;
  15624. // Inlining small images into the queue as RGB data
  15625. if (inline && !softMask && !mask && !(image instanceof JpegStream) &&
  15626. (w + h) < SMALL_IMAGE_DIMENSIONS) {
  15627. var imageObj = new PDFImage(this.xref, resources, image,
  15628. inline, null, null);
  15629. // We force the use of RGBA_32BPP images here, because we can't handle
  15630. // any other kind.
  15631. imgData = imageObj.createImageData(/* forceRGBA = */ true);
  15632. operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);
  15633. return;
  15634. }
  15635. // If there is no imageMask, create the PDFImage and a lot
  15636. // of image processing can be done here.
  15637. var uniquePrefix = (this.uniquePrefix || '');
  15638. var objId = 'img_' + uniquePrefix + (++this.idCounters.obj);
  15639. operatorList.addDependency(objId);
  15640. args = [objId, w, h];
  15641. if (!softMask && !mask && image instanceof JpegStream &&
  15642. image.isNativelySupported(this.xref, resources)) {
  15643. // These JPEGs don't need any more processing so we can just send it.
  15644. operatorList.addOp(OPS.paintJpegXObject, args);
  15645. this.handler.send('obj',
  15646. [objId, this.pageIndex, 'JpegStream', image.getIR()]);
  15647. return;
  15648. }
  15649. PDFImage.buildImage(self.handler, self.xref, resources, image, inline).
  15650. then(function(imageObj) {
  15651. var imgData = imageObj.createImageData(/* forceRGBA = */ false);
  15652. self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData],
  15653. [imgData.data.buffer]);
  15654. }).then(undefined, function (reason) {
  15655. warn('Unable to decode image: ' + reason);
  15656. self.handler.send('obj', [objId, self.pageIndex, 'Image', null]);
  15657. });
  15658. operatorList.addOp(OPS.paintImageXObject, args);
  15659. if (cacheKey) {
  15660. imageCache[cacheKey] = {
  15661. fn: OPS.paintImageXObject,
  15662. args: args
  15663. };
  15664. }
  15665. },
  15666. handleSMask: function PartialEvaluator_handleSmask(smask, resources,
  15667. operatorList,
  15668. stateManager) {
  15669. var smaskContent = smask.get('G');
  15670. var smaskOptions = {
  15671. subtype: smask.get('S').name,
  15672. backdrop: smask.get('BC')
  15673. };
  15674. return this.buildFormXObject(resources, smaskContent, smaskOptions,
  15675. operatorList, stateManager.state.clone());
  15676. },
  15677. handleTilingType:
  15678. function PartialEvaluator_handleTilingType(fn, args, resources,
  15679. pattern, patternDict,
  15680. operatorList) {
  15681. // Create an IR of the pattern code.
  15682. var tilingOpList = new OperatorList();
  15683. return this.getOperatorList(pattern,
  15684. (patternDict.get('Resources') || resources), tilingOpList).
  15685. then(function () {
  15686. // Add the dependencies to the parent operator list so they are
  15687. // resolved before sub operator list is executed synchronously.
  15688. operatorList.addDependencies(tilingOpList.dependencies);
  15689. operatorList.addOp(fn, getTilingPatternIR({
  15690. fnArray: tilingOpList.fnArray,
  15691. argsArray: tilingOpList.argsArray
  15692. }, patternDict, args));
  15693. });
  15694. },
  15695. handleSetFont:
  15696. function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef,
  15697. operatorList, state) {
  15698. // TODO(mack): Not needed?
  15699. var fontName;
  15700. if (fontArgs) {
  15701. fontArgs = fontArgs.slice();
  15702. fontName = fontArgs[0].name;
  15703. }
  15704. var self = this;
  15705. return this.loadFont(fontName, fontRef, this.xref, resources).then(
  15706. function (translated) {
  15707. if (!translated.font.isType3Font) {
  15708. return translated;
  15709. }
  15710. return translated.loadType3Data(self, resources, operatorList).then(
  15711. function () {
  15712. return translated;
  15713. });
  15714. }).then(function (translated) {
  15715. state.font = translated.font;
  15716. translated.send(self.handler);
  15717. return translated.loadedName;
  15718. });
  15719. },
  15720. handleText: function PartialEvaluator_handleText(chars, state) {
  15721. var font = state.font;
  15722. var glyphs = font.charsToGlyphs(chars);
  15723. var isAddToPathSet = !!(state.textRenderingMode &
  15724. TextRenderingMode.ADD_TO_PATH_FLAG);
  15725. if (font.data && (isAddToPathSet || PDFJS.disableFontFace)) {
  15726. var buildPath = function (fontChar) {
  15727. if (!font.renderer.hasBuiltPath(fontChar)) {
  15728. var path = font.renderer.getPathJs(fontChar);
  15729. this.handler.send('commonobj', [
  15730. font.loadedName + '_path_' + fontChar,
  15731. 'FontPath',
  15732. path
  15733. ]);
  15734. }
  15735. }.bind(this);
  15736. for (var i = 0, ii = glyphs.length; i < ii; i++) {
  15737. var glyph = glyphs[i];
  15738. if (glyph === null) {
  15739. continue;
  15740. }
  15741. buildPath(glyph.fontChar);
  15742. // If the glyph has an accent we need to build a path for its
  15743. // fontChar too, otherwise CanvasGraphics_paintChar will fail.
  15744. var accent = glyph.accent;
  15745. if (accent && accent.fontChar) {
  15746. buildPath(accent.fontChar);
  15747. }
  15748. }
  15749. }
  15750. return glyphs;
  15751. },
  15752. setGState: function PartialEvaluator_setGState(resources, gState,
  15753. operatorList, xref,
  15754. stateManager) {
  15755. // This array holds the converted/processed state data.
  15756. var gStateObj = [];
  15757. var gStateMap = gState.map;
  15758. var self = this;
  15759. var promise = Promise.resolve();
  15760. for (var key in gStateMap) {
  15761. var value = gStateMap[key];
  15762. switch (key) {
  15763. case 'Type':
  15764. break;
  15765. case 'LW':
  15766. case 'LC':
  15767. case 'LJ':
  15768. case 'ML':
  15769. case 'D':
  15770. case 'RI':
  15771. case 'FL':
  15772. case 'CA':
  15773. case 'ca':
  15774. gStateObj.push([key, value]);
  15775. break;
  15776. case 'Font':
  15777. promise = promise.then(function () {
  15778. return self.handleSetFont(resources, null, value[0],
  15779. operatorList, stateManager.state).
  15780. then(function (loadedName) {
  15781. operatorList.addDependency(loadedName);
  15782. gStateObj.push([key, [loadedName, value[1]]]);
  15783. });
  15784. });
  15785. break;
  15786. case 'BM':
  15787. gStateObj.push([key, value]);
  15788. break;
  15789. case 'SMask':
  15790. if (isName(value) && value.name === 'None') {
  15791. gStateObj.push([key, false]);
  15792. break;
  15793. }
  15794. var dict = xref.fetchIfRef(value);
  15795. if (isDict(dict)) {
  15796. promise = promise.then(function () {
  15797. return self.handleSMask(dict, resources, operatorList,
  15798. stateManager);
  15799. });
  15800. gStateObj.push([key, true]);
  15801. } else {
  15802. warn('Unsupported SMask type');
  15803. }
  15804. break;
  15805. // Only generate info log messages for the following since
  15806. // they are unlikely to have a big impact on the rendering.
  15807. case 'OP':
  15808. case 'op':
  15809. case 'OPM':
  15810. case 'BG':
  15811. case 'BG2':
  15812. case 'UCR':
  15813. case 'UCR2':
  15814. case 'TR':
  15815. case 'TR2':
  15816. case 'HT':
  15817. case 'SM':
  15818. case 'SA':
  15819. case 'AIS':
  15820. case 'TK':
  15821. // TODO implement these operators.
  15822. info('graphic state operator ' + key);
  15823. break;
  15824. default:
  15825. info('Unknown graphic state operator ' + key);
  15826. break;
  15827. }
  15828. }
  15829. return promise.then(function () {
  15830. if (gStateObj.length >= 0) {
  15831. operatorList.addOp(OPS.setGState, [gStateObj]);
  15832. }
  15833. });
  15834. },
  15835. loadFont: function PartialEvaluator_loadFont(fontName, font, xref,
  15836. resources) {
  15837. function errorFont() {
  15838. return Promise.resolve(new TranslatedFont('g_font_error',
  15839. new ErrorFont('Font ' + fontName + ' is not available'), font));
  15840. }
  15841. var fontRef;
  15842. if (font) { // Loading by ref.
  15843. assert(isRef(font));
  15844. fontRef = font;
  15845. } else { // Loading by name.
  15846. var fontRes = resources.get('Font');
  15847. if (fontRes) {
  15848. fontRef = fontRes.getRaw(fontName);
  15849. } else {
  15850. warn('fontRes not available');
  15851. return errorFont();
  15852. }
  15853. }
  15854. if (!fontRef) {
  15855. warn('fontRef not available');
  15856. return errorFont();
  15857. }
  15858. if (this.fontCache.has(fontRef)) {
  15859. return this.fontCache.get(fontRef);
  15860. }
  15861. font = xref.fetchIfRef(fontRef);
  15862. if (!isDict(font)) {
  15863. return errorFont();
  15864. }
  15865. // We are holding font.translated references just for fontRef that are not
  15866. // dictionaries (Dict). See explanation below.
  15867. if (font.translated) {
  15868. return font.translated;
  15869. }
  15870. var fontCapability = createPromiseCapability();
  15871. var preEvaluatedFont = this.preEvaluateFont(font, xref);
  15872. var descriptor = preEvaluatedFont.descriptor;
  15873. var fontID = fontRef.num + '_' + fontRef.gen;
  15874. if (isDict(descriptor)) {
  15875. if (!descriptor.fontAliases) {
  15876. descriptor.fontAliases = Object.create(null);
  15877. }
  15878. var fontAliases = descriptor.fontAliases;
  15879. var hash = preEvaluatedFont.hash;
  15880. if (fontAliases[hash]) {
  15881. var aliasFontRef = fontAliases[hash].aliasRef;
  15882. if (aliasFontRef && this.fontCache.has(aliasFontRef)) {
  15883. this.fontCache.putAlias(fontRef, aliasFontRef);
  15884. return this.fontCache.get(fontRef);
  15885. }
  15886. }
  15887. if (!fontAliases[hash]) {
  15888. fontAliases[hash] = {
  15889. fontID: Font.getFontID()
  15890. };
  15891. }
  15892. fontAliases[hash].aliasRef = fontRef;
  15893. fontID = fontAliases[hash].fontID;
  15894. }
  15895. // Workaround for bad PDF generators that don't reference fonts
  15896. // properly, i.e. by not using an object identifier.
  15897. // Check if the fontRef is a Dict (as opposed to a standard object),
  15898. // in which case we don't cache the font and instead reference it by
  15899. // fontName in font.loadedName below.
  15900. var fontRefIsDict = isDict(fontRef);
  15901. if (!fontRefIsDict) {
  15902. this.fontCache.put(fontRef, fontCapability.promise);
  15903. }
  15904. // Keep track of each font we translated so the caller can
  15905. // load them asynchronously before calling display on a page.
  15906. font.loadedName = 'g_font_' + (fontRefIsDict ?
  15907. fontName.replace(/\W/g, '') : fontID);
  15908. font.translated = fontCapability.promise;
  15909. // TODO move promises into translate font
  15910. var translatedPromise;
  15911. try {
  15912. translatedPromise = Promise.resolve(
  15913. this.translateFont(preEvaluatedFont, xref));
  15914. } catch (e) {
  15915. translatedPromise = Promise.reject(e);
  15916. }
  15917. translatedPromise.then(function (translatedFont) {
  15918. if (translatedFont.fontType !== undefined) {
  15919. var xrefFontStats = xref.stats.fontTypes;
  15920. xrefFontStats[translatedFont.fontType] = true;
  15921. }
  15922. fontCapability.resolve(new TranslatedFont(font.loadedName,
  15923. translatedFont, font));
  15924. }, function (reason) {
  15925. // TODO fontCapability.reject?
  15926. UnsupportedManager.notify(UNSUPPORTED_FEATURES.font);
  15927. try {
  15928. // error, but it's still nice to have font type reported
  15929. var descriptor = preEvaluatedFont.descriptor;
  15930. var fontFile3 = descriptor && descriptor.get('FontFile3');
  15931. var subtype = fontFile3 && fontFile3.get('Subtype');
  15932. var fontType = getFontType(preEvaluatedFont.type,
  15933. subtype && subtype.name);
  15934. var xrefFontStats = xref.stats.fontTypes;
  15935. xrefFontStats[fontType] = true;
  15936. } catch (ex) { }
  15937. fontCapability.resolve(new TranslatedFont(font.loadedName,
  15938. new ErrorFont(reason instanceof Error ? reason.message : reason),
  15939. font));
  15940. });
  15941. return fontCapability.promise;
  15942. },
  15943. buildPath: function PartialEvaluator_buildPath(operatorList, fn, args) {
  15944. var lastIndex = operatorList.length - 1;
  15945. if (!args) {
  15946. args = [];
  15947. }
  15948. if (lastIndex < 0 ||
  15949. operatorList.fnArray[lastIndex] !== OPS.constructPath) {
  15950. operatorList.addOp(OPS.constructPath, [[fn], args]);
  15951. } else {
  15952. var opArgs = operatorList.argsArray[lastIndex];
  15953. opArgs[0].push(fn);
  15954. Array.prototype.push.apply(opArgs[1], args);
  15955. }
  15956. },
  15957. handleColorN: function PartialEvaluator_handleColorN(operatorList, fn, args,
  15958. cs, patterns, resources, xref) {
  15959. // compile tiling patterns
  15960. var patternName = args[args.length - 1];
  15961. // SCN/scn applies patterns along with normal colors
  15962. var pattern;
  15963. if (isName(patternName) &&
  15964. (pattern = patterns.get(patternName.name))) {
  15965. var dict = (isStream(pattern) ? pattern.dict : pattern);
  15966. var typeNum = dict.get('PatternType');
  15967. if (typeNum === TILING_PATTERN) {
  15968. var color = cs.base ? cs.base.getRgb(args, 0) : null;
  15969. return this.handleTilingType(fn, color, resources, pattern,
  15970. dict, operatorList);
  15971. } else if (typeNum === SHADING_PATTERN) {
  15972. var shading = dict.get('Shading');
  15973. var matrix = dict.get('Matrix');
  15974. pattern = Pattern.parseShading(shading, matrix, xref, resources);
  15975. operatorList.addOp(fn, pattern.getIR());
  15976. return Promise.resolve();
  15977. } else {
  15978. return Promise.reject('Unknown PatternType: ' + typeNum);
  15979. }
  15980. }
  15981. // TODO shall we fail here?
  15982. operatorList.addOp(fn, args);
  15983. return Promise.resolve();
  15984. },
  15985. getOperatorList: function PartialEvaluator_getOperatorList(stream,
  15986. resources,
  15987. operatorList,
  15988. initialState) {
  15989. var self = this;
  15990. var xref = this.xref;
  15991. var imageCache = {};
  15992. assert(operatorList);
  15993. resources = (resources || Dict.empty);
  15994. var xobjs = (resources.get('XObject') || Dict.empty);
  15995. var patterns = (resources.get('Pattern') || Dict.empty);
  15996. var stateManager = new StateManager(initialState || new EvalState());
  15997. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  15998. var timeSlotManager = new TimeSlotManager();
  15999. return new Promise(function next(resolve, reject) {
  16000. timeSlotManager.reset();
  16001. var stop, operation = {}, i, ii, cs;
  16002. while (!(stop = timeSlotManager.check())) {
  16003. // The arguments parsed by read() are used beyond this loop, so we
  16004. // cannot reuse the same array on each iteration. Therefore we pass
  16005. // in |null| as the initial value (see the comment on
  16006. // EvaluatorPreprocessor_read() for why).
  16007. operation.args = null;
  16008. if (!(preprocessor.read(operation))) {
  16009. break;
  16010. }
  16011. var args = operation.args;
  16012. var fn = operation.fn;
  16013. switch (fn | 0) {
  16014. case OPS.paintXObject:
  16015. if (args[0].code) {
  16016. break;
  16017. }
  16018. // eagerly compile XForm objects
  16019. var name = args[0].name;
  16020. if (!name) {
  16021. warn('XObject must be referred to by name.');
  16022. continue;
  16023. }
  16024. if (imageCache[name] !== undefined) {
  16025. operatorList.addOp(imageCache[name].fn, imageCache[name].args);
  16026. args = null;
  16027. continue;
  16028. }
  16029. var xobj = xobjs.get(name);
  16030. if (xobj) {
  16031. assert(isStream(xobj), 'XObject should be a stream');
  16032. var type = xobj.dict.get('Subtype');
  16033. assert(isName(type),
  16034. 'XObject should have a Name subtype');
  16035. if (type.name === 'Form') {
  16036. stateManager.save();
  16037. return self.buildFormXObject(resources, xobj, null,
  16038. operatorList,
  16039. stateManager.state.clone()).
  16040. then(function () {
  16041. stateManager.restore();
  16042. next(resolve, reject);
  16043. }, reject);
  16044. } else if (type.name === 'Image') {
  16045. self.buildPaintImageXObject(resources, xobj, false,
  16046. operatorList, name, imageCache);
  16047. args = null;
  16048. continue;
  16049. } else if (type.name === 'PS') {
  16050. // PostScript XObjects are unused when viewing documents.
  16051. // See section 4.7.1 of Adobe's PDF reference.
  16052. info('Ignored XObject subtype PS');
  16053. continue;
  16054. } else {
  16055. error('Unhandled XObject subtype ' + type.name);
  16056. }
  16057. }
  16058. break;
  16059. case OPS.setFont:
  16060. var fontSize = args[1];
  16061. // eagerly collect all fonts
  16062. return self.handleSetFont(resources, args, null,
  16063. operatorList, stateManager.state).
  16064. then(function (loadedName) {
  16065. operatorList.addDependency(loadedName);
  16066. operatorList.addOp(OPS.setFont, [loadedName, fontSize]);
  16067. next(resolve, reject);
  16068. }, reject);
  16069. case OPS.endInlineImage:
  16070. var cacheKey = args[0].cacheKey;
  16071. if (cacheKey) {
  16072. var cacheEntry = imageCache[cacheKey];
  16073. if (cacheEntry !== undefined) {
  16074. operatorList.addOp(cacheEntry.fn, cacheEntry.args);
  16075. args = null;
  16076. continue;
  16077. }
  16078. }
  16079. self.buildPaintImageXObject(resources, args[0], true,
  16080. operatorList, cacheKey, imageCache);
  16081. args = null;
  16082. continue;
  16083. case OPS.showText:
  16084. args[0] = self.handleText(args[0], stateManager.state);
  16085. break;
  16086. case OPS.showSpacedText:
  16087. var arr = args[0];
  16088. var combinedGlyphs = [];
  16089. var arrLength = arr.length;
  16090. for (i = 0; i < arrLength; ++i) {
  16091. var arrItem = arr[i];
  16092. if (isString(arrItem)) {
  16093. Array.prototype.push.apply(combinedGlyphs,
  16094. self.handleText(arrItem, stateManager.state));
  16095. } else if (isNum(arrItem)) {
  16096. combinedGlyphs.push(arrItem);
  16097. }
  16098. }
  16099. args[0] = combinedGlyphs;
  16100. fn = OPS.showText;
  16101. break;
  16102. case OPS.nextLineShowText:
  16103. operatorList.addOp(OPS.nextLine);
  16104. args[0] = self.handleText(args[0], stateManager.state);
  16105. fn = OPS.showText;
  16106. break;
  16107. case OPS.nextLineSetSpacingShowText:
  16108. operatorList.addOp(OPS.nextLine);
  16109. operatorList.addOp(OPS.setWordSpacing, [args.shift()]);
  16110. operatorList.addOp(OPS.setCharSpacing, [args.shift()]);
  16111. args[0] = self.handleText(args[0], stateManager.state);
  16112. fn = OPS.showText;
  16113. break;
  16114. case OPS.setTextRenderingMode:
  16115. stateManager.state.textRenderingMode = args[0];
  16116. break;
  16117. case OPS.setFillColorSpace:
  16118. stateManager.state.fillColorSpace =
  16119. ColorSpace.parse(args[0], xref, resources);
  16120. continue;
  16121. case OPS.setStrokeColorSpace:
  16122. stateManager.state.strokeColorSpace =
  16123. ColorSpace.parse(args[0], xref, resources);
  16124. continue;
  16125. case OPS.setFillColor:
  16126. cs = stateManager.state.fillColorSpace;
  16127. args = cs.getRgb(args, 0);
  16128. fn = OPS.setFillRGBColor;
  16129. break;
  16130. case OPS.setStrokeColor:
  16131. cs = stateManager.state.strokeColorSpace;
  16132. args = cs.getRgb(args, 0);
  16133. fn = OPS.setStrokeRGBColor;
  16134. break;
  16135. case OPS.setFillGray:
  16136. stateManager.state.fillColorSpace = ColorSpace.singletons.gray;
  16137. args = ColorSpace.singletons.gray.getRgb(args, 0);
  16138. fn = OPS.setFillRGBColor;
  16139. break;
  16140. case OPS.setStrokeGray:
  16141. stateManager.state.strokeColorSpace = ColorSpace.singletons.gray;
  16142. args = ColorSpace.singletons.gray.getRgb(args, 0);
  16143. fn = OPS.setStrokeRGBColor;
  16144. break;
  16145. case OPS.setFillCMYKColor:
  16146. stateManager.state.fillColorSpace = ColorSpace.singletons.cmyk;
  16147. args = ColorSpace.singletons.cmyk.getRgb(args, 0);
  16148. fn = OPS.setFillRGBColor;
  16149. break;
  16150. case OPS.setStrokeCMYKColor:
  16151. stateManager.state.strokeColorSpace = ColorSpace.singletons.cmyk;
  16152. args = ColorSpace.singletons.cmyk.getRgb(args, 0);
  16153. fn = OPS.setStrokeRGBColor;
  16154. break;
  16155. case OPS.setFillRGBColor:
  16156. stateManager.state.fillColorSpace = ColorSpace.singletons.rgb;
  16157. args = ColorSpace.singletons.rgb.getRgb(args, 0);
  16158. break;
  16159. case OPS.setStrokeRGBColor:
  16160. stateManager.state.strokeColorSpace = ColorSpace.singletons.rgb;
  16161. args = ColorSpace.singletons.rgb.getRgb(args, 0);
  16162. break;
  16163. case OPS.setFillColorN:
  16164. cs = stateManager.state.fillColorSpace;
  16165. if (cs.name === 'Pattern') {
  16166. return self.handleColorN(operatorList, OPS.setFillColorN,
  16167. args, cs, patterns, resources, xref).then(function() {
  16168. next(resolve, reject);
  16169. }, reject);
  16170. }
  16171. args = cs.getRgb(args, 0);
  16172. fn = OPS.setFillRGBColor;
  16173. break;
  16174. case OPS.setStrokeColorN:
  16175. cs = stateManager.state.strokeColorSpace;
  16176. if (cs.name === 'Pattern') {
  16177. return self.handleColorN(operatorList, OPS.setStrokeColorN,
  16178. args, cs, patterns, resources, xref).then(function() {
  16179. next(resolve, reject);
  16180. }, reject);
  16181. }
  16182. args = cs.getRgb(args, 0);
  16183. fn = OPS.setStrokeRGBColor;
  16184. break;
  16185. case OPS.shadingFill:
  16186. var shadingRes = resources.get('Shading');
  16187. if (!shadingRes) {
  16188. error('No shading resource found');
  16189. }
  16190. var shading = shadingRes.get(args[0].name);
  16191. if (!shading) {
  16192. error('No shading object found');
  16193. }
  16194. var shadingFill = Pattern.parseShading(shading, null, xref,
  16195. resources);
  16196. var patternIR = shadingFill.getIR();
  16197. args = [patternIR];
  16198. fn = OPS.shadingFill;
  16199. break;
  16200. case OPS.setGState:
  16201. var dictName = args[0];
  16202. var extGState = resources.get('ExtGState');
  16203. if (!isDict(extGState) || !extGState.has(dictName.name)) {
  16204. break;
  16205. }
  16206. var gState = extGState.get(dictName.name);
  16207. return self.setGState(resources, gState, operatorList, xref,
  16208. stateManager).then(function() {
  16209. next(resolve, reject);
  16210. }, reject);
  16211. case OPS.moveTo:
  16212. case OPS.lineTo:
  16213. case OPS.curveTo:
  16214. case OPS.curveTo2:
  16215. case OPS.curveTo3:
  16216. case OPS.closePath:
  16217. self.buildPath(operatorList, fn, args);
  16218. continue;
  16219. case OPS.rectangle:
  16220. self.buildPath(operatorList, fn, args);
  16221. continue;
  16222. }
  16223. operatorList.addOp(fn, args);
  16224. }
  16225. if (stop) {
  16226. deferred.then(function () {
  16227. next(resolve, reject);
  16228. });
  16229. return;
  16230. }
  16231. // Some PDFs don't close all restores inside object/form.
  16232. // Closing those for them.
  16233. for (i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
  16234. operatorList.addOp(OPS.restore, []);
  16235. }
  16236. resolve();
  16237. });
  16238. },
  16239. getTextContent: function PartialEvaluator_getTextContent(stream, resources,
  16240. stateManager) {
  16241. stateManager = (stateManager || new StateManager(new TextState()));
  16242. var textContent = {
  16243. items: [],
  16244. styles: Object.create(null)
  16245. };
  16246. var bidiTexts = textContent.items;
  16247. var SPACE_FACTOR = 0.3;
  16248. var MULTI_SPACE_FACTOR = 1.5;
  16249. var self = this;
  16250. var xref = this.xref;
  16251. resources = (xref.fetchIfRef(resources) || Dict.empty);
  16252. // The xobj is parsed iff it's needed, e.g. if there is a `DO` cmd.
  16253. var xobjs = null;
  16254. var xobjsCache = {};
  16255. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  16256. var textState;
  16257. function newTextChunk() {
  16258. var font = textState.font;
  16259. if (!(font.loadedName in textContent.styles)) {
  16260. textContent.styles[font.loadedName] = {
  16261. fontFamily: font.fallbackName,
  16262. ascent: font.ascent,
  16263. descent: font.descent,
  16264. vertical: font.vertical
  16265. };
  16266. }
  16267. return {
  16268. // |str| is initially an array which we push individual chars to, and
  16269. // then runBidi() overwrites it with the final string.
  16270. str: [],
  16271. dir: null,
  16272. width: 0,
  16273. height: 0,
  16274. transform: null,
  16275. fontName: font.loadedName
  16276. };
  16277. }
  16278. function runBidi(textChunk) {
  16279. var str = textChunk.str.join('');
  16280. var bidiResult = PDFJS.bidi(str, -1, textState.font.vertical);
  16281. textChunk.str = bidiResult.str;
  16282. textChunk.dir = bidiResult.dir;
  16283. return textChunk;
  16284. }
  16285. function handleSetFont(fontName, fontRef) {
  16286. return self.loadFont(fontName, fontRef, xref, resources).
  16287. then(function (translated) {
  16288. textState.font = translated.font;
  16289. textState.fontMatrix = translated.font.fontMatrix ||
  16290. FONT_IDENTITY_MATRIX;
  16291. });
  16292. }
  16293. function buildTextGeometry(chars, textChunk) {
  16294. var font = textState.font;
  16295. textChunk = textChunk || newTextChunk();
  16296. if (!textChunk.transform) {
  16297. // 9.4.4 Text Space Details
  16298. var tsm = [textState.fontSize * textState.textHScale, 0,
  16299. 0, textState.fontSize,
  16300. 0, textState.textRise];
  16301. if (font.isType3Font &&
  16302. textState.fontMatrix !== FONT_IDENTITY_MATRIX &&
  16303. textState.fontSize === 1) {
  16304. var glyphHeight = font.bbox[3] - font.bbox[1];
  16305. if (glyphHeight > 0) {
  16306. glyphHeight = glyphHeight * textState.fontMatrix[3];
  16307. tsm[3] *= glyphHeight;
  16308. }
  16309. }
  16310. var trm = textChunk.transform = Util.transform(textState.ctm,
  16311. Util.transform(textState.textMatrix, tsm));
  16312. if (!font.vertical) {
  16313. textChunk.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]);
  16314. } else {
  16315. textChunk.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]);
  16316. }
  16317. }
  16318. var width = 0;
  16319. var height = 0;
  16320. var glyphs = font.charsToGlyphs(chars);
  16321. var defaultVMetrics = font.defaultVMetrics;
  16322. for (var i = 0; i < glyphs.length; i++) {
  16323. var glyph = glyphs[i];
  16324. if (!glyph) { // Previous glyph was a space.
  16325. width += textState.wordSpacing * textState.textHScale;
  16326. continue;
  16327. }
  16328. var vMetricX = null;
  16329. var vMetricY = null;
  16330. var glyphWidth = null;
  16331. if (font.vertical) {
  16332. if (glyph.vmetric) {
  16333. glyphWidth = glyph.vmetric[0];
  16334. vMetricX = glyph.vmetric[1];
  16335. vMetricY = glyph.vmetric[2];
  16336. } else {
  16337. glyphWidth = glyph.width;
  16338. vMetricX = glyph.width * 0.5;
  16339. vMetricY = defaultVMetrics[2];
  16340. }
  16341. } else {
  16342. glyphWidth = glyph.width;
  16343. }
  16344. var glyphUnicode = glyph.unicode;
  16345. if (NormalizedUnicodes[glyphUnicode] !== undefined) {
  16346. glyphUnicode = NormalizedUnicodes[glyphUnicode];
  16347. }
  16348. glyphUnicode = reverseIfRtl(glyphUnicode);
  16349. // The following will calculate the x and y of the individual glyphs.
  16350. // if (font.vertical) {
  16351. // tsm[4] -= vMetricX * Math.abs(textState.fontSize) *
  16352. // textState.fontMatrix[0];
  16353. // tsm[5] -= vMetricY * textState.fontSize *
  16354. // textState.fontMatrix[0];
  16355. // }
  16356. // var trm = Util.transform(textState.textMatrix, tsm);
  16357. // var pt = Util.applyTransform([trm[4], trm[5]], textState.ctm);
  16358. // var x = pt[0];
  16359. // var y = pt[1];
  16360. var charSpacing = 0;
  16361. if (textChunk.str.length > 0) {
  16362. // Apply char spacing only when there are chars.
  16363. // As a result there is only spacing between glyphs.
  16364. charSpacing = textState.charSpacing;
  16365. }
  16366. var tx = 0;
  16367. var ty = 0;
  16368. if (!font.vertical) {
  16369. var w0 = glyphWidth * textState.fontMatrix[0];
  16370. tx = (w0 * textState.fontSize + charSpacing) *
  16371. textState.textHScale;
  16372. width += tx;
  16373. } else {
  16374. var w1 = glyphWidth * textState.fontMatrix[0];
  16375. ty = w1 * textState.fontSize + charSpacing;
  16376. height += ty;
  16377. }
  16378. textState.translateTextMatrix(tx, ty);
  16379. textChunk.str.push(glyphUnicode);
  16380. }
  16381. var a = textState.textLineMatrix[0];
  16382. var b = textState.textLineMatrix[1];
  16383. var scaleLineX = Math.sqrt(a * a + b * b);
  16384. a = textState.ctm[0];
  16385. b = textState.ctm[1];
  16386. var scaleCtmX = Math.sqrt(a * a + b * b);
  16387. if (!font.vertical) {
  16388. textChunk.width += width * scaleCtmX * scaleLineX;
  16389. } else {
  16390. textChunk.height += Math.abs(height * scaleCtmX * scaleLineX);
  16391. }
  16392. return textChunk;
  16393. }
  16394. var timeSlotManager = new TimeSlotManager();
  16395. return new Promise(function next(resolve, reject) {
  16396. timeSlotManager.reset();
  16397. var stop, operation = {}, args = [];
  16398. while (!(stop = timeSlotManager.check())) {
  16399. // The arguments parsed by read() are not used beyond this loop, so
  16400. // we can reuse the same array on every iteration, thus avoiding
  16401. // unnecessary allocations.
  16402. args.length = 0;
  16403. operation.args = args;
  16404. if (!(preprocessor.read(operation))) {
  16405. break;
  16406. }
  16407. textState = stateManager.state;
  16408. var fn = operation.fn;
  16409. args = operation.args;
  16410. switch (fn | 0) {
  16411. case OPS.setFont:
  16412. textState.fontSize = args[1];
  16413. return handleSetFont(args[0].name).then(function() {
  16414. next(resolve, reject);
  16415. }, reject);
  16416. case OPS.setTextRise:
  16417. textState.textRise = args[0];
  16418. break;
  16419. case OPS.setHScale:
  16420. textState.textHScale = args[0] / 100;
  16421. break;
  16422. case OPS.setLeading:
  16423. textState.leading = args[0];
  16424. break;
  16425. case OPS.moveText:
  16426. textState.translateTextLineMatrix(args[0], args[1]);
  16427. textState.textMatrix = textState.textLineMatrix.slice();
  16428. break;
  16429. case OPS.setLeadingMoveText:
  16430. textState.leading = -args[1];
  16431. textState.translateTextLineMatrix(args[0], args[1]);
  16432. textState.textMatrix = textState.textLineMatrix.slice();
  16433. break;
  16434. case OPS.nextLine:
  16435. textState.carriageReturn();
  16436. break;
  16437. case OPS.setTextMatrix:
  16438. textState.setTextMatrix(args[0], args[1], args[2], args[3],
  16439. args[4], args[5]);
  16440. textState.setTextLineMatrix(args[0], args[1], args[2], args[3],
  16441. args[4], args[5]);
  16442. break;
  16443. case OPS.setCharSpacing:
  16444. textState.charSpacing = args[0];
  16445. break;
  16446. case OPS.setWordSpacing:
  16447. textState.wordSpacing = args[0];
  16448. break;
  16449. case OPS.beginText:
  16450. textState.textMatrix = IDENTITY_MATRIX.slice();
  16451. textState.textLineMatrix = IDENTITY_MATRIX.slice();
  16452. break;
  16453. case OPS.showSpacedText:
  16454. var items = args[0];
  16455. var textChunk = newTextChunk();
  16456. var offset;
  16457. for (var j = 0, jj = items.length; j < jj; j++) {
  16458. if (typeof items[j] === 'string') {
  16459. buildTextGeometry(items[j], textChunk);
  16460. } else {
  16461. var val = items[j] / 1000;
  16462. if (!textState.font.vertical) {
  16463. offset = -val * textState.fontSize * textState.textHScale *
  16464. textState.textMatrix[0];
  16465. textState.translateTextMatrix(offset, 0);
  16466. textChunk.width += offset;
  16467. } else {
  16468. offset = -val * textState.fontSize *
  16469. textState.textMatrix[3];
  16470. textState.translateTextMatrix(0, offset);
  16471. textChunk.height += offset;
  16472. }
  16473. if (items[j] < 0 && textState.font.spaceWidth > 0) {
  16474. var fakeSpaces = -items[j] / textState.font.spaceWidth;
  16475. if (fakeSpaces > MULTI_SPACE_FACTOR) {
  16476. fakeSpaces = Math.round(fakeSpaces);
  16477. while (fakeSpaces--) {
  16478. textChunk.str.push(' ');
  16479. }
  16480. } else if (fakeSpaces > SPACE_FACTOR) {
  16481. textChunk.str.push(' ');
  16482. }
  16483. }
  16484. }
  16485. }
  16486. bidiTexts.push(runBidi(textChunk));
  16487. break;
  16488. case OPS.showText:
  16489. bidiTexts.push(runBidi(buildTextGeometry(args[0])));
  16490. break;
  16491. case OPS.nextLineShowText:
  16492. textState.carriageReturn();
  16493. bidiTexts.push(runBidi(buildTextGeometry(args[0])));
  16494. break;
  16495. case OPS.nextLineSetSpacingShowText:
  16496. textState.wordSpacing = args[0];
  16497. textState.charSpacing = args[1];
  16498. textState.carriageReturn();
  16499. bidiTexts.push(runBidi(buildTextGeometry(args[2])));
  16500. break;
  16501. case OPS.paintXObject:
  16502. if (args[0].code) {
  16503. break;
  16504. }
  16505. if (!xobjs) {
  16506. xobjs = (resources.get('XObject') || Dict.empty);
  16507. }
  16508. var name = args[0].name;
  16509. if (xobjsCache.key === name) {
  16510. if (xobjsCache.texts) {
  16511. Util.appendToArray(bidiTexts, xobjsCache.texts.items);
  16512. Util.extendObj(textContent.styles, xobjsCache.texts.styles);
  16513. }
  16514. break;
  16515. }
  16516. var xobj = xobjs.get(name);
  16517. if (!xobj) {
  16518. break;
  16519. }
  16520. assert(isStream(xobj), 'XObject should be a stream');
  16521. var type = xobj.dict.get('Subtype');
  16522. assert(isName(type),
  16523. 'XObject should have a Name subtype');
  16524. if ('Form' !== type.name) {
  16525. xobjsCache.key = name;
  16526. xobjsCache.texts = null;
  16527. break;
  16528. }
  16529. stateManager.save();
  16530. var matrix = xobj.dict.get('Matrix');
  16531. if (isArray(matrix) && matrix.length === 6) {
  16532. stateManager.transform(matrix);
  16533. }
  16534. return self.getTextContent(xobj,
  16535. xobj.dict.get('Resources') || resources, stateManager).
  16536. then(function (formTextContent) {
  16537. Util.appendToArray(bidiTexts, formTextContent.items);
  16538. Util.extendObj(textContent.styles, formTextContent.styles);
  16539. stateManager.restore();
  16540. xobjsCache.key = name;
  16541. xobjsCache.texts = formTextContent;
  16542. next(resolve, reject);
  16543. }, reject);
  16544. case OPS.setGState:
  16545. var dictName = args[0];
  16546. var extGState = resources.get('ExtGState');
  16547. if (!isDict(extGState) || !extGState.has(dictName.name)) {
  16548. break;
  16549. }
  16550. var gsStateMap = extGState.get(dictName.name);
  16551. var gsStateFont = null;
  16552. for (var key in gsStateMap) {
  16553. if (key === 'Font') {
  16554. assert(!gsStateFont);
  16555. gsStateFont = gsStateMap[key];
  16556. }
  16557. }
  16558. if (gsStateFont) {
  16559. textState.fontSize = gsStateFont[1];
  16560. return handleSetFont(gsStateFont[0]).then(function() {
  16561. next(resolve, reject);
  16562. }, reject);
  16563. }
  16564. break;
  16565. } // switch
  16566. } // while
  16567. if (stop) {
  16568. deferred.then(function () {
  16569. next(resolve, reject);
  16570. });
  16571. return;
  16572. }
  16573. resolve(textContent);
  16574. });
  16575. },
  16576. extractDataStructures: function
  16577. partialEvaluatorExtractDataStructures(dict, baseDict,
  16578. xref, properties) {
  16579. // 9.10.2
  16580. var toUnicode = (dict.get('ToUnicode') || baseDict.get('ToUnicode'));
  16581. if (toUnicode) {
  16582. properties.toUnicode = this.readToUnicode(toUnicode);
  16583. }
  16584. if (properties.composite) {
  16585. // CIDSystemInfo helps to match CID to glyphs
  16586. var cidSystemInfo = dict.get('CIDSystemInfo');
  16587. if (isDict(cidSystemInfo)) {
  16588. properties.cidSystemInfo = {
  16589. registry: cidSystemInfo.get('Registry'),
  16590. ordering: cidSystemInfo.get('Ordering'),
  16591. supplement: cidSystemInfo.get('Supplement')
  16592. };
  16593. }
  16594. var cidToGidMap = dict.get('CIDToGIDMap');
  16595. if (isStream(cidToGidMap)) {
  16596. properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
  16597. }
  16598. }
  16599. // Based on 9.6.6 of the spec the encoding can come from multiple places
  16600. // and depends on the font type. The base encoding and differences are
  16601. // read here, but the encoding that is actually used is chosen during
  16602. // glyph mapping in the font.
  16603. // TODO: Loading the built in encoding in the font would allow the
  16604. // differences to be merged in here not require us to hold on to it.
  16605. var differences = [];
  16606. var baseEncodingName = null;
  16607. var encoding;
  16608. if (dict.has('Encoding')) {
  16609. encoding = dict.get('Encoding');
  16610. if (isDict(encoding)) {
  16611. baseEncodingName = encoding.get('BaseEncoding');
  16612. baseEncodingName = (isName(baseEncodingName) ?
  16613. baseEncodingName.name : null);
  16614. // Load the differences between the base and original
  16615. if (encoding.has('Differences')) {
  16616. var diffEncoding = encoding.get('Differences');
  16617. var index = 0;
  16618. for (var j = 0, jj = diffEncoding.length; j < jj; j++) {
  16619. var data = diffEncoding[j];
  16620. if (isNum(data)) {
  16621. index = data;
  16622. } else if (isName(data)) {
  16623. differences[index++] = data.name;
  16624. } else if (isRef(data)) {
  16625. diffEncoding[j--] = xref.fetch(data);
  16626. continue;
  16627. } else {
  16628. error('Invalid entry in \'Differences\' array: ' + data);
  16629. }
  16630. }
  16631. }
  16632. } else if (isName(encoding)) {
  16633. baseEncodingName = encoding.name;
  16634. } else {
  16635. error('Encoding is not a Name nor a Dict');
  16636. }
  16637. // According to table 114 if the encoding is a named encoding it must be
  16638. // one of these predefined encodings.
  16639. if ((baseEncodingName !== 'MacRomanEncoding' &&
  16640. baseEncodingName !== 'MacExpertEncoding' &&
  16641. baseEncodingName !== 'WinAnsiEncoding')) {
  16642. baseEncodingName = null;
  16643. }
  16644. }
  16645. if (baseEncodingName) {
  16646. properties.defaultEncoding = Encodings[baseEncodingName].slice();
  16647. } else {
  16648. encoding = (properties.type === 'TrueType' ?
  16649. Encodings.WinAnsiEncoding : Encodings.StandardEncoding);
  16650. // The Symbolic attribute can be misused for regular fonts
  16651. // Heuristic: we have to check if the font is a standard one also
  16652. if (!!(properties.flags & FontFlags.Symbolic)) {
  16653. encoding = Encodings.MacRomanEncoding;
  16654. if (!properties.file) {
  16655. if (/Symbol/i.test(properties.name)) {
  16656. encoding = Encodings.SymbolSetEncoding;
  16657. } else if (/Dingbats/i.test(properties.name)) {
  16658. encoding = Encodings.ZapfDingbatsEncoding;
  16659. }
  16660. }
  16661. }
  16662. properties.defaultEncoding = encoding;
  16663. }
  16664. properties.differences = differences;
  16665. properties.baseEncodingName = baseEncodingName;
  16666. properties.dict = dict;
  16667. },
  16668. readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
  16669. var cmap, cmapObj = toUnicode;
  16670. if (isName(cmapObj)) {
  16671. cmap = CMapFactory.create(cmapObj,
  16672. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  16673. if (cmap instanceof IdentityCMap) {
  16674. return new IdentityToUnicodeMap(0, 0xFFFF);
  16675. }
  16676. return new ToUnicodeMap(cmap.getMap());
  16677. } else if (isStream(cmapObj)) {
  16678. cmap = CMapFactory.create(cmapObj,
  16679. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  16680. if (cmap instanceof IdentityCMap) {
  16681. return new IdentityToUnicodeMap(0, 0xFFFF);
  16682. }
  16683. cmap = cmap.getMap();
  16684. // Convert UTF-16BE
  16685. // NOTE: cmap can be a sparse array, so use forEach instead of for(;;)
  16686. // to iterate over all keys.
  16687. cmap.forEach(function(token, i) {
  16688. var str = [];
  16689. for (var k = 0; k < token.length; k += 2) {
  16690. var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
  16691. if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF
  16692. str.push(w1);
  16693. continue;
  16694. }
  16695. k += 2;
  16696. var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
  16697. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  16698. }
  16699. cmap[i] = String.fromCharCode.apply(String, str);
  16700. });
  16701. return new ToUnicodeMap(cmap);
  16702. }
  16703. return null;
  16704. },
  16705. readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
  16706. // Extract the encoding from the CIDToGIDMap
  16707. var glyphsData = cidToGidStream.getBytes();
  16708. // Set encoding 0 to later verify the font has an encoding
  16709. var result = [];
  16710. for (var j = 0, jj = glyphsData.length; j < jj; j++) {
  16711. var glyphID = (glyphsData[j++] << 8) | glyphsData[j];
  16712. if (glyphID === 0) {
  16713. continue;
  16714. }
  16715. var code = j >> 1;
  16716. result[code] = glyphID;
  16717. }
  16718. return result;
  16719. },
  16720. extractWidths: function PartialEvaluator_extractWidths(dict, xref,
  16721. descriptor,
  16722. properties) {
  16723. var glyphsWidths = [];
  16724. var defaultWidth = 0;
  16725. var glyphsVMetrics = [];
  16726. var defaultVMetrics;
  16727. var i, ii, j, jj, start, code, widths;
  16728. if (properties.composite) {
  16729. defaultWidth = dict.get('DW') || 1000;
  16730. widths = dict.get('W');
  16731. if (widths) {
  16732. for (i = 0, ii = widths.length; i < ii; i++) {
  16733. start = widths[i++];
  16734. code = xref.fetchIfRef(widths[i]);
  16735. if (isArray(code)) {
  16736. for (j = 0, jj = code.length; j < jj; j++) {
  16737. glyphsWidths[start++] = code[j];
  16738. }
  16739. } else {
  16740. var width = widths[++i];
  16741. for (j = start; j <= code; j++) {
  16742. glyphsWidths[j] = width;
  16743. }
  16744. }
  16745. }
  16746. }
  16747. if (properties.vertical) {
  16748. var vmetrics = (dict.get('DW2') || [880, -1000]);
  16749. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  16750. vmetrics = dict.get('W2');
  16751. if (vmetrics) {
  16752. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  16753. start = vmetrics[i++];
  16754. code = xref.fetchIfRef(vmetrics[i]);
  16755. if (isArray(code)) {
  16756. for (j = 0, jj = code.length; j < jj; j++) {
  16757. glyphsVMetrics[start++] = [code[j++], code[j++], code[j]];
  16758. }
  16759. } else {
  16760. var vmetric = [vmetrics[++i], vmetrics[++i], vmetrics[++i]];
  16761. for (j = start; j <= code; j++) {
  16762. glyphsVMetrics[j] = vmetric;
  16763. }
  16764. }
  16765. }
  16766. }
  16767. }
  16768. } else {
  16769. var firstChar = properties.firstChar;
  16770. widths = dict.get('Widths');
  16771. if (widths) {
  16772. j = firstChar;
  16773. for (i = 0, ii = widths.length; i < ii; i++) {
  16774. glyphsWidths[j++] = widths[i];
  16775. }
  16776. defaultWidth = (parseFloat(descriptor.get('MissingWidth')) || 0);
  16777. } else {
  16778. // Trying get the BaseFont metrics (see comment above).
  16779. var baseFontName = dict.get('BaseFont');
  16780. if (isName(baseFontName)) {
  16781. var metrics = this.getBaseFontMetrics(baseFontName.name);
  16782. glyphsWidths = this.buildCharCodeToWidth(metrics.widths,
  16783. properties);
  16784. defaultWidth = metrics.defaultWidth;
  16785. }
  16786. }
  16787. }
  16788. // Heuristic: detection of monospace font by checking all non-zero widths
  16789. var isMonospace = true;
  16790. var firstWidth = defaultWidth;
  16791. for (var glyph in glyphsWidths) {
  16792. var glyphWidth = glyphsWidths[glyph];
  16793. if (!glyphWidth) {
  16794. continue;
  16795. }
  16796. if (!firstWidth) {
  16797. firstWidth = glyphWidth;
  16798. continue;
  16799. }
  16800. if (firstWidth !== glyphWidth) {
  16801. isMonospace = false;
  16802. break;
  16803. }
  16804. }
  16805. if (isMonospace) {
  16806. properties.flags |= FontFlags.FixedPitch;
  16807. }
  16808. properties.defaultWidth = defaultWidth;
  16809. properties.widths = glyphsWidths;
  16810. properties.defaultVMetrics = defaultVMetrics;
  16811. properties.vmetrics = glyphsVMetrics;
  16812. },
  16813. isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
  16814. // Simulating descriptor flags attribute
  16815. var fontNameWoStyle = baseFontName.split('-')[0];
  16816. return (fontNameWoStyle in serifFonts) ||
  16817. (fontNameWoStyle.search(/serif/gi) !== -1);
  16818. },
  16819. getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
  16820. var defaultWidth = 0;
  16821. var widths = [];
  16822. var monospace = false;
  16823. var lookupName = (stdFontMap[name] || name);
  16824. if (!(lookupName in Metrics)) {
  16825. // Use default fonts for looking up font metrics if the passed
  16826. // font is not a base font
  16827. if (this.isSerifFont(name)) {
  16828. lookupName = 'Times-Roman';
  16829. } else {
  16830. lookupName = 'Helvetica';
  16831. }
  16832. }
  16833. var glyphWidths = Metrics[lookupName];
  16834. if (isNum(glyphWidths)) {
  16835. defaultWidth = glyphWidths;
  16836. monospace = true;
  16837. } else {
  16838. widths = glyphWidths;
  16839. }
  16840. return {
  16841. defaultWidth: defaultWidth,
  16842. monospace: monospace,
  16843. widths: widths
  16844. };
  16845. },
  16846. buildCharCodeToWidth:
  16847. function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName,
  16848. properties) {
  16849. var widths = Object.create(null);
  16850. var differences = properties.differences;
  16851. var encoding = properties.defaultEncoding;
  16852. for (var charCode = 0; charCode < 256; charCode++) {
  16853. if (charCode in differences &&
  16854. widthsByGlyphName[differences[charCode]]) {
  16855. widths[charCode] = widthsByGlyphName[differences[charCode]];
  16856. continue;
  16857. }
  16858. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  16859. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  16860. continue;
  16861. }
  16862. }
  16863. return widths;
  16864. },
  16865. preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict, xref) {
  16866. var baseDict = dict;
  16867. var type = dict.get('Subtype');
  16868. assert(isName(type), 'invalid font Subtype');
  16869. var composite = false;
  16870. var uint8array;
  16871. if (type.name === 'Type0') {
  16872. // If font is a composite
  16873. // - get the descendant font
  16874. // - set the type according to the descendant font
  16875. // - get the FontDescriptor from the descendant font
  16876. var df = dict.get('DescendantFonts');
  16877. if (!df) {
  16878. error('Descendant fonts are not specified');
  16879. }
  16880. dict = (isArray(df) ? xref.fetchIfRef(df[0]) : df);
  16881. type = dict.get('Subtype');
  16882. assert(isName(type), 'invalid font Subtype');
  16883. composite = true;
  16884. }
  16885. var descriptor = dict.get('FontDescriptor');
  16886. if (descriptor) {
  16887. var hash = new MurmurHash3_64();
  16888. var encoding = baseDict.getRaw('Encoding');
  16889. if (isName(encoding)) {
  16890. hash.update(encoding.name);
  16891. } else if (isRef(encoding)) {
  16892. hash.update(encoding.num + '_' + encoding.gen);
  16893. } else if (isDict(encoding)) {
  16894. var keys = encoding.getKeys();
  16895. for (var i = 0, ii = keys.length; i < ii; i++) {
  16896. var entry = encoding.getRaw(keys[i]);
  16897. if (isName(entry)) {
  16898. hash.update(entry.name);
  16899. } else if (isRef(entry)) {
  16900. hash.update(entry.num + '_' + entry.gen);
  16901. } else if (isArray(entry)) { // 'Differences' entry.
  16902. // Ideally we should check the contents of the array, but to avoid
  16903. // parsing it here and then again in |extractDataStructures|,
  16904. // we only use the array length for now (fixes bug1157493.pdf).
  16905. hash.update(entry.length.toString());
  16906. }
  16907. }
  16908. }
  16909. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  16910. if (isStream(toUnicode)) {
  16911. var stream = toUnicode.str || toUnicode;
  16912. uint8array = stream.buffer ?
  16913. new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) :
  16914. new Uint8Array(stream.bytes.buffer,
  16915. stream.start, stream.end - stream.start);
  16916. hash.update(uint8array);
  16917. } else if (isName(toUnicode)) {
  16918. hash.update(toUnicode.name);
  16919. }
  16920. var widths = dict.get('Widths') || baseDict.get('Widths');
  16921. if (widths) {
  16922. uint8array = new Uint8Array(new Uint32Array(widths).buffer);
  16923. hash.update(uint8array);
  16924. }
  16925. }
  16926. return {
  16927. descriptor: descriptor,
  16928. dict: dict,
  16929. baseDict: baseDict,
  16930. composite: composite,
  16931. type: type.name,
  16932. hash: hash ? hash.hexdigest() : ''
  16933. };
  16934. },
  16935. translateFont: function PartialEvaluator_translateFont(preEvaluatedFont,
  16936. xref) {
  16937. var baseDict = preEvaluatedFont.baseDict;
  16938. var dict = preEvaluatedFont.dict;
  16939. var composite = preEvaluatedFont.composite;
  16940. var descriptor = preEvaluatedFont.descriptor;
  16941. var type = preEvaluatedFont.type;
  16942. var maxCharIndex = (composite ? 0xFFFF : 0xFF);
  16943. var properties;
  16944. if (!descriptor) {
  16945. if (type === 'Type3') {
  16946. // FontDescriptor is only required for Type3 fonts when the document
  16947. // is a tagged pdf. Create a barbebones one to get by.
  16948. descriptor = new Dict(null);
  16949. descriptor.set('FontName', Name.get(type));
  16950. descriptor.set('FontBBox', dict.get('FontBBox'));
  16951. } else {
  16952. // Before PDF 1.5 if the font was one of the base 14 fonts, having a
  16953. // FontDescriptor was not required.
  16954. // This case is here for compatibility.
  16955. var baseFontName = dict.get('BaseFont');
  16956. if (!isName(baseFontName)) {
  16957. error('Base font is not specified');
  16958. }
  16959. // Using base font name as a font name.
  16960. baseFontName = baseFontName.name.replace(/[,_]/g, '-');
  16961. var metrics = this.getBaseFontMetrics(baseFontName);
  16962. // Simulating descriptor flags attribute
  16963. var fontNameWoStyle = baseFontName.split('-')[0];
  16964. var flags =
  16965. (this.isSerifFont(fontNameWoStyle) ? FontFlags.Serif : 0) |
  16966. (metrics.monospace ? FontFlags.FixedPitch : 0) |
  16967. (symbolsFonts[fontNameWoStyle] ? FontFlags.Symbolic :
  16968. FontFlags.Nonsymbolic);
  16969. properties = {
  16970. type: type,
  16971. name: baseFontName,
  16972. widths: metrics.widths,
  16973. defaultWidth: metrics.defaultWidth,
  16974. flags: flags,
  16975. firstChar: 0,
  16976. lastChar: maxCharIndex
  16977. };
  16978. this.extractDataStructures(dict, dict, xref, properties);
  16979. properties.widths = this.buildCharCodeToWidth(metrics.widths,
  16980. properties);
  16981. return new Font(baseFontName, null, properties);
  16982. }
  16983. }
  16984. // According to the spec if 'FontDescriptor' is declared, 'FirstChar',
  16985. // 'LastChar' and 'Widths' should exist too, but some PDF encoders seem
  16986. // to ignore this rule when a variant of a standart font is used.
  16987. // TODO Fill the width array depending on which of the base font this is
  16988. // a variant.
  16989. var firstChar = (dict.get('FirstChar') || 0);
  16990. var lastChar = (dict.get('LastChar') || maxCharIndex);
  16991. var fontName = descriptor.get('FontName');
  16992. var baseFont = dict.get('BaseFont');
  16993. // Some bad PDFs have a string as the font name.
  16994. if (isString(fontName)) {
  16995. fontName = Name.get(fontName);
  16996. }
  16997. if (isString(baseFont)) {
  16998. baseFont = Name.get(baseFont);
  16999. }
  17000. if (type !== 'Type3') {
  17001. var fontNameStr = fontName && fontName.name;
  17002. var baseFontStr = baseFont && baseFont.name;
  17003. if (fontNameStr !== baseFontStr) {
  17004. info('The FontDescriptor\'s FontName is "' + fontNameStr +
  17005. '" but should be the same as the Font\'s BaseFont "' +
  17006. baseFontStr + '"');
  17007. // Workaround for cases where e.g. fontNameStr = 'Arial' and
  17008. // baseFontStr = 'Arial,Bold' (needed when no font file is embedded).
  17009. if (fontNameStr && baseFontStr &&
  17010. baseFontStr.indexOf(fontNameStr) === 0) {
  17011. fontName = baseFont;
  17012. }
  17013. }
  17014. }
  17015. fontName = (fontName || baseFont);
  17016. assert(isName(fontName), 'invalid font name');
  17017. var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
  17018. if (fontFile) {
  17019. if (fontFile.dict) {
  17020. var subtype = fontFile.dict.get('Subtype');
  17021. if (subtype) {
  17022. subtype = subtype.name;
  17023. }
  17024. var length1 = fontFile.dict.get('Length1');
  17025. var length2 = fontFile.dict.get('Length2');
  17026. }
  17027. }
  17028. properties = {
  17029. type: type,
  17030. name: fontName.name,
  17031. subtype: subtype,
  17032. file: fontFile,
  17033. length1: length1,
  17034. length2: length2,
  17035. loadedName: baseDict.loadedName,
  17036. composite: composite,
  17037. wideChars: composite,
  17038. fixedPitch: false,
  17039. fontMatrix: (dict.get('FontMatrix') || FONT_IDENTITY_MATRIX),
  17040. firstChar: firstChar || 0,
  17041. lastChar: (lastChar || maxCharIndex),
  17042. bbox: descriptor.get('FontBBox'),
  17043. ascent: descriptor.get('Ascent'),
  17044. descent: descriptor.get('Descent'),
  17045. xHeight: descriptor.get('XHeight'),
  17046. capHeight: descriptor.get('CapHeight'),
  17047. flags: descriptor.get('Flags'),
  17048. italicAngle: descriptor.get('ItalicAngle'),
  17049. coded: false
  17050. };
  17051. if (composite) {
  17052. var cidEncoding = baseDict.get('Encoding');
  17053. if (isName(cidEncoding)) {
  17054. properties.cidEncoding = cidEncoding.name;
  17055. }
  17056. properties.cMap = CMapFactory.create(cidEncoding,
  17057. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  17058. properties.vertical = properties.cMap.vertical;
  17059. }
  17060. this.extractDataStructures(dict, baseDict, xref, properties);
  17061. this.extractWidths(dict, xref, descriptor, properties);
  17062. if (type === 'Type3') {
  17063. properties.isType3Font = true;
  17064. }
  17065. return new Font(fontName.name, fontFile, properties);
  17066. }
  17067. };
  17068. return PartialEvaluator;
  17069. })();
  17070. var TranslatedFont = (function TranslatedFontClosure() {
  17071. function TranslatedFont(loadedName, font, dict) {
  17072. this.loadedName = loadedName;
  17073. this.font = font;
  17074. this.dict = dict;
  17075. this.type3Loaded = null;
  17076. this.sent = false;
  17077. }
  17078. TranslatedFont.prototype = {
  17079. send: function (handler) {
  17080. if (this.sent) {
  17081. return;
  17082. }
  17083. var fontData = this.font.exportData();
  17084. handler.send('commonobj', [
  17085. this.loadedName,
  17086. 'Font',
  17087. fontData
  17088. ]);
  17089. this.sent = true;
  17090. },
  17091. loadType3Data: function (evaluator, resources, parentOperatorList) {
  17092. assert(this.font.isType3Font);
  17093. if (this.type3Loaded) {
  17094. return this.type3Loaded;
  17095. }
  17096. var translatedFont = this.font;
  17097. var loadCharProcsPromise = Promise.resolve();
  17098. var charProcs = this.dict.get('CharProcs').getAll();
  17099. var fontResources = this.dict.get('Resources') || resources;
  17100. var charProcKeys = Object.keys(charProcs);
  17101. var charProcOperatorList = {};
  17102. for (var i = 0, n = charProcKeys.length; i < n; ++i) {
  17103. loadCharProcsPromise = loadCharProcsPromise.then(function (key) {
  17104. var glyphStream = charProcs[key];
  17105. var operatorList = new OperatorList();
  17106. return evaluator.getOperatorList(glyphStream, fontResources,
  17107. operatorList).then(function () {
  17108. charProcOperatorList[key] = operatorList.getIR();
  17109. // Add the dependencies to the parent operator list so they are
  17110. // resolved before sub operator list is executed synchronously.
  17111. parentOperatorList.addDependencies(operatorList.dependencies);
  17112. }, function (reason) {
  17113. warn('Type3 font resource \"' + key + '\" is not available');
  17114. var operatorList = new OperatorList();
  17115. charProcOperatorList[key] = operatorList.getIR();
  17116. });
  17117. }.bind(this, charProcKeys[i]));
  17118. }
  17119. this.type3Loaded = loadCharProcsPromise.then(function () {
  17120. translatedFont.charProcOperatorList = charProcOperatorList;
  17121. });
  17122. return this.type3Loaded;
  17123. }
  17124. };
  17125. return TranslatedFont;
  17126. })();
  17127. var OperatorList = (function OperatorListClosure() {
  17128. var CHUNK_SIZE = 1000;
  17129. var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5; // close to chunk size
  17130. function getTransfers(queue) {
  17131. var transfers = [];
  17132. var fnArray = queue.fnArray, argsArray = queue.argsArray;
  17133. for (var i = 0, ii = queue.length; i < ii; i++) {
  17134. switch (fnArray[i]) {
  17135. case OPS.paintInlineImageXObject:
  17136. case OPS.paintInlineImageXObjectGroup:
  17137. case OPS.paintImageMaskXObject:
  17138. var arg = argsArray[i][0]; // first param in imgData
  17139. if (!arg.cached) {
  17140. transfers.push(arg.data.buffer);
  17141. }
  17142. break;
  17143. }
  17144. }
  17145. return transfers;
  17146. }
  17147. function OperatorList(intent, messageHandler, pageIndex) {
  17148. this.messageHandler = messageHandler;
  17149. this.fnArray = [];
  17150. this.argsArray = [];
  17151. this.dependencies = {};
  17152. this.pageIndex = pageIndex;
  17153. this.intent = intent;
  17154. }
  17155. OperatorList.prototype = {
  17156. get length() {
  17157. return this.argsArray.length;
  17158. },
  17159. addOp: function(fn, args) {
  17160. this.fnArray.push(fn);
  17161. this.argsArray.push(args);
  17162. if (this.messageHandler) {
  17163. if (this.fnArray.length >= CHUNK_SIZE) {
  17164. this.flush();
  17165. } else if (this.fnArray.length >= CHUNK_SIZE_ABOUT &&
  17166. (fn === OPS.restore || fn === OPS.endText)) {
  17167. // heuristic to flush on boundary of restore or endText
  17168. this.flush();
  17169. }
  17170. }
  17171. },
  17172. addDependency: function(dependency) {
  17173. if (dependency in this.dependencies) {
  17174. return;
  17175. }
  17176. this.dependencies[dependency] = true;
  17177. this.addOp(OPS.dependency, [dependency]);
  17178. },
  17179. addDependencies: function(dependencies) {
  17180. for (var key in dependencies) {
  17181. this.addDependency(key);
  17182. }
  17183. },
  17184. addOpList: function(opList) {
  17185. Util.extendObj(this.dependencies, opList.dependencies);
  17186. for (var i = 0, ii = opList.length; i < ii; i++) {
  17187. this.addOp(opList.fnArray[i], opList.argsArray[i]);
  17188. }
  17189. },
  17190. getIR: function() {
  17191. return {
  17192. fnArray: this.fnArray,
  17193. argsArray: this.argsArray,
  17194. length: this.length
  17195. };
  17196. },
  17197. flush: function(lastChunk) {
  17198. if (this.intent !== 'oplist') {
  17199. new QueueOptimizer().optimize(this);
  17200. }
  17201. var transfers = getTransfers(this);
  17202. this.messageHandler.send('RenderPageChunk', {
  17203. operatorList: {
  17204. fnArray: this.fnArray,
  17205. argsArray: this.argsArray,
  17206. lastChunk: lastChunk,
  17207. length: this.length
  17208. },
  17209. pageIndex: this.pageIndex,
  17210. intent: this.intent
  17211. }, transfers);
  17212. this.dependencies = {};
  17213. this.fnArray.length = 0;
  17214. this.argsArray.length = 0;
  17215. }
  17216. };
  17217. return OperatorList;
  17218. })();
  17219. var StateManager = (function StateManagerClosure() {
  17220. function StateManager(initialState) {
  17221. this.state = initialState;
  17222. this.stateStack = [];
  17223. }
  17224. StateManager.prototype = {
  17225. save: function () {
  17226. var old = this.state;
  17227. this.stateStack.push(this.state);
  17228. this.state = old.clone();
  17229. },
  17230. restore: function () {
  17231. var prev = this.stateStack.pop();
  17232. if (prev) {
  17233. this.state = prev;
  17234. }
  17235. },
  17236. transform: function (args) {
  17237. this.state.ctm = Util.transform(this.state.ctm, args);
  17238. }
  17239. };
  17240. return StateManager;
  17241. })();
  17242. var TextState = (function TextStateClosure() {
  17243. function TextState() {
  17244. this.ctm = new Float32Array(IDENTITY_MATRIX);
  17245. this.fontSize = 0;
  17246. this.font = null;
  17247. this.fontMatrix = FONT_IDENTITY_MATRIX;
  17248. this.textMatrix = IDENTITY_MATRIX.slice();
  17249. this.textLineMatrix = IDENTITY_MATRIX.slice();
  17250. this.charSpacing = 0;
  17251. this.wordSpacing = 0;
  17252. this.leading = 0;
  17253. this.textHScale = 1;
  17254. this.textRise = 0;
  17255. }
  17256. TextState.prototype = {
  17257. setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  17258. var m = this.textMatrix;
  17259. m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
  17260. },
  17261. setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  17262. var m = this.textLineMatrix;
  17263. m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
  17264. },
  17265. translateTextMatrix: function TextState_translateTextMatrix(x, y) {
  17266. var m = this.textMatrix;
  17267. m[4] = m[0] * x + m[2] * y + m[4];
  17268. m[5] = m[1] * x + m[3] * y + m[5];
  17269. },
  17270. translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
  17271. var m = this.textLineMatrix;
  17272. m[4] = m[0] * x + m[2] * y + m[4];
  17273. m[5] = m[1] * x + m[3] * y + m[5];
  17274. },
  17275. calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
  17276. // 9.4.4 Text Space Details
  17277. var tsm = [this.fontSize * this.textHScale, 0,
  17278. 0, this.fontSize,
  17279. 0, this.textRise];
  17280. return Util.transform(ctm, Util.transform(this.textMatrix, tsm));
  17281. },
  17282. carriageReturn: function TextState_carriageReturn() {
  17283. this.translateTextLineMatrix(0, -this.leading);
  17284. this.textMatrix = this.textLineMatrix.slice();
  17285. },
  17286. clone: function TextState_clone() {
  17287. var clone = Object.create(this);
  17288. clone.textMatrix = this.textMatrix.slice();
  17289. clone.textLineMatrix = this.textLineMatrix.slice();
  17290. clone.fontMatrix = this.fontMatrix.slice();
  17291. return clone;
  17292. }
  17293. };
  17294. return TextState;
  17295. })();
  17296. var EvalState = (function EvalStateClosure() {
  17297. function EvalState() {
  17298. this.ctm = new Float32Array(IDENTITY_MATRIX);
  17299. this.font = null;
  17300. this.textRenderingMode = TextRenderingMode.FILL;
  17301. this.fillColorSpace = ColorSpace.singletons.gray;
  17302. this.strokeColorSpace = ColorSpace.singletons.gray;
  17303. }
  17304. EvalState.prototype = {
  17305. clone: function CanvasExtraState_clone() {
  17306. return Object.create(this);
  17307. },
  17308. };
  17309. return EvalState;
  17310. })();
  17311. var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
  17312. // Specifies properties for each command
  17313. //
  17314. // If variableArgs === true: [0, `numArgs`] expected
  17315. // If variableArgs === false: exactly `numArgs` expected
  17316. var OP_MAP = {
  17317. // Graphic state
  17318. w: { id: OPS.setLineWidth, numArgs: 1, variableArgs: false },
  17319. J: { id: OPS.setLineCap, numArgs: 1, variableArgs: false },
  17320. j: { id: OPS.setLineJoin, numArgs: 1, variableArgs: false },
  17321. M: { id: OPS.setMiterLimit, numArgs: 1, variableArgs: false },
  17322. d: { id: OPS.setDash, numArgs: 2, variableArgs: false },
  17323. ri: { id: OPS.setRenderingIntent, numArgs: 1, variableArgs: false },
  17324. i: { id: OPS.setFlatness, numArgs: 1, variableArgs: false },
  17325. gs: { id: OPS.setGState, numArgs: 1, variableArgs: false },
  17326. q: { id: OPS.save, numArgs: 0, variableArgs: false },
  17327. Q: { id: OPS.restore, numArgs: 0, variableArgs: false },
  17328. cm: { id: OPS.transform, numArgs: 6, variableArgs: false },
  17329. // Path
  17330. m: { id: OPS.moveTo, numArgs: 2, variableArgs: false },
  17331. l: { id: OPS.lineTo, numArgs: 2, variableArgs: false },
  17332. c: { id: OPS.curveTo, numArgs: 6, variableArgs: false },
  17333. v: { id: OPS.curveTo2, numArgs: 4, variableArgs: false },
  17334. y: { id: OPS.curveTo3, numArgs: 4, variableArgs: false },
  17335. h: { id: OPS.closePath, numArgs: 0, variableArgs: false },
  17336. re: { id: OPS.rectangle, numArgs: 4, variableArgs: false },
  17337. S: { id: OPS.stroke, numArgs: 0, variableArgs: false },
  17338. s: { id: OPS.closeStroke, numArgs: 0, variableArgs: false },
  17339. f: { id: OPS.fill, numArgs: 0, variableArgs: false },
  17340. F: { id: OPS.fill, numArgs: 0, variableArgs: false },
  17341. 'f*': { id: OPS.eoFill, numArgs: 0, variableArgs: false },
  17342. B: { id: OPS.fillStroke, numArgs: 0, variableArgs: false },
  17343. 'B*': { id: OPS.eoFillStroke, numArgs: 0, variableArgs: false },
  17344. b: { id: OPS.closeFillStroke, numArgs: 0, variableArgs: false },
  17345. 'b*': { id: OPS.closeEOFillStroke, numArgs: 0, variableArgs: false },
  17346. n: { id: OPS.endPath, numArgs: 0, variableArgs: false },
  17347. // Clipping
  17348. W: { id: OPS.clip, numArgs: 0, variableArgs: false },
  17349. 'W*': { id: OPS.eoClip, numArgs: 0, variableArgs: false },
  17350. // Text
  17351. BT: { id: OPS.beginText, numArgs: 0, variableArgs: false },
  17352. ET: { id: OPS.endText, numArgs: 0, variableArgs: false },
  17353. Tc: { id: OPS.setCharSpacing, numArgs: 1, variableArgs: false },
  17354. Tw: { id: OPS.setWordSpacing, numArgs: 1, variableArgs: false },
  17355. Tz: { id: OPS.setHScale, numArgs: 1, variableArgs: false },
  17356. TL: { id: OPS.setLeading, numArgs: 1, variableArgs: false },
  17357. Tf: { id: OPS.setFont, numArgs: 2, variableArgs: false },
  17358. Tr: { id: OPS.setTextRenderingMode, numArgs: 1, variableArgs: false },
  17359. Ts: { id: OPS.setTextRise, numArgs: 1, variableArgs: false },
  17360. Td: { id: OPS.moveText, numArgs: 2, variableArgs: false },
  17361. TD: { id: OPS.setLeadingMoveText, numArgs: 2, variableArgs: false },
  17362. Tm: { id: OPS.setTextMatrix, numArgs: 6, variableArgs: false },
  17363. 'T*': { id: OPS.nextLine, numArgs: 0, variableArgs: false },
  17364. Tj: { id: OPS.showText, numArgs: 1, variableArgs: false },
  17365. TJ: { id: OPS.showSpacedText, numArgs: 1, variableArgs: false },
  17366. '\'': { id: OPS.nextLineShowText, numArgs: 1, variableArgs: false },
  17367. '"': { id: OPS.nextLineSetSpacingShowText, numArgs: 3,
  17368. variableArgs: false },
  17369. // Type3 fonts
  17370. d0: { id: OPS.setCharWidth, numArgs: 2, variableArgs: false },
  17371. d1: { id: OPS.setCharWidthAndBounds, numArgs: 6, variableArgs: false },
  17372. // Color
  17373. CS: { id: OPS.setStrokeColorSpace, numArgs: 1, variableArgs: false },
  17374. cs: { id: OPS.setFillColorSpace, numArgs: 1, variableArgs: false },
  17375. SC: { id: OPS.setStrokeColor, numArgs: 4, variableArgs: true },
  17376. SCN: { id: OPS.setStrokeColorN, numArgs: 33, variableArgs: true },
  17377. sc: { id: OPS.setFillColor, numArgs: 4, variableArgs: true },
  17378. scn: { id: OPS.setFillColorN, numArgs: 33, variableArgs: true },
  17379. G: { id: OPS.setStrokeGray, numArgs: 1, variableArgs: false },
  17380. g: { id: OPS.setFillGray, numArgs: 1, variableArgs: false },
  17381. RG: { id: OPS.setStrokeRGBColor, numArgs: 3, variableArgs: false },
  17382. rg: { id: OPS.setFillRGBColor, numArgs: 3, variableArgs: false },
  17383. K: { id: OPS.setStrokeCMYKColor, numArgs: 4, variableArgs: false },
  17384. k: { id: OPS.setFillCMYKColor, numArgs: 4, variableArgs: false },
  17385. // Shading
  17386. sh: { id: OPS.shadingFill, numArgs: 1, variableArgs: false },
  17387. // Images
  17388. BI: { id: OPS.beginInlineImage, numArgs: 0, variableArgs: false },
  17389. ID: { id: OPS.beginImageData, numArgs: 0, variableArgs: false },
  17390. EI: { id: OPS.endInlineImage, numArgs: 1, variableArgs: false },
  17391. // XObjects
  17392. Do: { id: OPS.paintXObject, numArgs: 1, variableArgs: false },
  17393. MP: { id: OPS.markPoint, numArgs: 1, variableArgs: false },
  17394. DP: { id: OPS.markPointProps, numArgs: 2, variableArgs: false },
  17395. BMC: { id: OPS.beginMarkedContent, numArgs: 1, variableArgs: false },
  17396. BDC: { id: OPS.beginMarkedContentProps, numArgs: 2,
  17397. variableArgs: false },
  17398. EMC: { id: OPS.endMarkedContent, numArgs: 0, variableArgs: false },
  17399. // Compatibility
  17400. BX: { id: OPS.beginCompat, numArgs: 0, variableArgs: false },
  17401. EX: { id: OPS.endCompat, numArgs: 0, variableArgs: false },
  17402. // (reserved partial commands for the lexer)
  17403. BM: null,
  17404. BD: null,
  17405. 'true': null,
  17406. fa: null,
  17407. fal: null,
  17408. fals: null,
  17409. 'false': null,
  17410. nu: null,
  17411. nul: null,
  17412. 'null': null
  17413. };
  17414. function EvaluatorPreprocessor(stream, xref, stateManager) {
  17415. // TODO(mduan): pass array of knownCommands rather than OP_MAP
  17416. // dictionary
  17417. this.parser = new Parser(new Lexer(stream, OP_MAP), false, xref);
  17418. this.stateManager = stateManager;
  17419. this.nonProcessedArgs = [];
  17420. }
  17421. EvaluatorPreprocessor.prototype = {
  17422. get savedStatesDepth() {
  17423. return this.stateManager.stateStack.length;
  17424. },
  17425. // |operation| is an object with two fields:
  17426. //
  17427. // - |fn| is an out param.
  17428. //
  17429. // - |args| is an inout param. On entry, it should have one of two values.
  17430. //
  17431. // - An empty array. This indicates that the caller is providing the
  17432. // array in which the args will be stored in. The caller should use
  17433. // this value if it can reuse a single array for each call to read().
  17434. //
  17435. // - |null|. This indicates that the caller needs this function to create
  17436. // the array in which any args are stored in. If there are zero args,
  17437. // this function will leave |operation.args| as |null| (thus avoiding
  17438. // allocations that would occur if we used an empty array to represent
  17439. // zero arguments). Otherwise, it will replace |null| with a new array
  17440. // containing the arguments. The caller should use this value if it
  17441. // cannot reuse an array for each call to read().
  17442. //
  17443. // These two modes are present because this function is very hot and so
  17444. // avoiding allocations where possible is worthwhile.
  17445. //
  17446. read: function EvaluatorPreprocessor_read(operation) {
  17447. var args = operation.args;
  17448. while (true) {
  17449. var obj = this.parser.getObj();
  17450. if (isCmd(obj)) {
  17451. var cmd = obj.cmd;
  17452. // Check that the command is valid
  17453. var opSpec = OP_MAP[cmd];
  17454. if (!opSpec) {
  17455. warn('Unknown command "' + cmd + '"');
  17456. continue;
  17457. }
  17458. var fn = opSpec.id;
  17459. var numArgs = opSpec.numArgs;
  17460. var argsLength = args !== null ? args.length : 0;
  17461. if (!opSpec.variableArgs) {
  17462. // Postscript commands can be nested, e.g. /F2 /GS2 gs 5.711 Tf
  17463. if (argsLength !== numArgs) {
  17464. var nonProcessedArgs = this.nonProcessedArgs;
  17465. while (argsLength > numArgs) {
  17466. nonProcessedArgs.push(args.shift());
  17467. argsLength--;
  17468. }
  17469. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  17470. if (!args) {
  17471. args = [];
  17472. }
  17473. args.unshift(nonProcessedArgs.pop());
  17474. argsLength++;
  17475. }
  17476. }
  17477. if (argsLength < numArgs) {
  17478. // If we receive too few args, it's not possible to possible
  17479. // to execute the command, so skip the command
  17480. info('Command ' + fn + ': because expected ' +
  17481. numArgs + ' args, but received ' + argsLength +
  17482. ' args; skipping');
  17483. args = null;
  17484. continue;
  17485. }
  17486. } else if (argsLength > numArgs) {
  17487. info('Command ' + fn + ': expected [0,' + numArgs +
  17488. '] args, but received ' + argsLength + ' args');
  17489. }
  17490. // TODO figure out how to type-check vararg functions
  17491. this.preprocessCommand(fn, args);
  17492. operation.fn = fn;
  17493. operation.args = args;
  17494. return true;
  17495. } else {
  17496. if (isEOF(obj)) {
  17497. return false; // no more commands
  17498. }
  17499. // argument
  17500. if (obj !== null) {
  17501. if (!args) {
  17502. args = [];
  17503. }
  17504. args.push((obj instanceof Dict ? obj.getAll() : obj));
  17505. assert(args.length <= 33, 'Too many arguments');
  17506. }
  17507. }
  17508. }
  17509. },
  17510. preprocessCommand:
  17511. function EvaluatorPreprocessor_preprocessCommand(fn, args) {
  17512. switch (fn | 0) {
  17513. case OPS.save:
  17514. this.stateManager.save();
  17515. break;
  17516. case OPS.restore:
  17517. this.stateManager.restore();
  17518. break;
  17519. case OPS.transform:
  17520. this.stateManager.transform(args);
  17521. break;
  17522. }
  17523. }
  17524. };
  17525. return EvaluatorPreprocessor;
  17526. })();
  17527. var QueueOptimizer = (function QueueOptimizerClosure() {
  17528. function addState(parentState, pattern, fn) {
  17529. var state = parentState;
  17530. for (var i = 0, ii = pattern.length - 1; i < ii; i++) {
  17531. var item = pattern[i];
  17532. state = (state[item] || (state[item] = []));
  17533. }
  17534. state[pattern[pattern.length - 1]] = fn;
  17535. }
  17536. function handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
  17537. argsArray) {
  17538. // Handles special case of mainly LaTeX documents which use image masks to
  17539. // draw lines with the current fill style.
  17540. // 'count' groups of (save, transform, paintImageMaskXObject, restore)+
  17541. // have been found at iFirstSave.
  17542. var iFirstPIMXO = iFirstSave + 2;
  17543. for (var i = 0; i < count; i++) {
  17544. var arg = argsArray[iFirstPIMXO + 4 * i];
  17545. var imageMask = arg.length === 1 && arg[0];
  17546. if (imageMask && imageMask.width === 1 && imageMask.height === 1 &&
  17547. (!imageMask.data.length ||
  17548. (imageMask.data.length === 1 && imageMask.data[0] === 0))) {
  17549. fnArray[iFirstPIMXO + 4 * i] = OPS.paintSolidColorImageMask;
  17550. continue;
  17551. }
  17552. break;
  17553. }
  17554. return count - i;
  17555. }
  17556. var InitialState = [];
  17557. // This replaces (save, transform, paintInlineImageXObject, restore)+
  17558. // sequences with one |paintInlineImageXObjectGroup| operation.
  17559. addState(InitialState,
  17560. [OPS.save, OPS.transform, OPS.paintInlineImageXObject, OPS.restore],
  17561. function foundInlineImageGroup(context) {
  17562. var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
  17563. var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
  17564. var MAX_WIDTH = 1000;
  17565. var IMAGE_PADDING = 1;
  17566. var fnArray = context.fnArray, argsArray = context.argsArray;
  17567. var curr = context.iCurr;
  17568. var iFirstSave = curr - 3;
  17569. var iFirstTransform = curr - 2;
  17570. var iFirstPIIXO = curr - 1;
  17571. // Look for the quartets.
  17572. var i = iFirstSave + 4;
  17573. var ii = fnArray.length;
  17574. while (i + 3 < ii) {
  17575. if (fnArray[i] !== OPS.save ||
  17576. fnArray[i + 1] !== OPS.transform ||
  17577. fnArray[i + 2] !== OPS.paintInlineImageXObject ||
  17578. fnArray[i + 3] !== OPS.restore) {
  17579. break; // ops don't match
  17580. }
  17581. i += 4;
  17582. }
  17583. // At this point, i is the index of the first op past the last valid
  17584. // quartet.
  17585. var count = Math.min((i - iFirstSave) / 4,
  17586. MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);
  17587. if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {
  17588. return i;
  17589. }
  17590. // assuming that heights of those image is too small (~1 pixel)
  17591. // packing as much as possible by lines
  17592. var maxX = 0;
  17593. var map = [], maxLineHeight = 0;
  17594. var currentX = IMAGE_PADDING, currentY = IMAGE_PADDING;
  17595. var q;
  17596. for (q = 0; q < count; q++) {
  17597. var transform = argsArray[iFirstTransform + (q << 2)];
  17598. var img = argsArray[iFirstPIIXO + (q << 2)][0];
  17599. if (currentX + img.width > MAX_WIDTH) {
  17600. // starting new line
  17601. maxX = Math.max(maxX, currentX);
  17602. currentY += maxLineHeight + 2 * IMAGE_PADDING;
  17603. currentX = 0;
  17604. maxLineHeight = 0;
  17605. }
  17606. map.push({
  17607. transform: transform,
  17608. x: currentX, y: currentY,
  17609. w: img.width, h: img.height
  17610. });
  17611. currentX += img.width + 2 * IMAGE_PADDING;
  17612. maxLineHeight = Math.max(maxLineHeight, img.height);
  17613. }
  17614. var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;
  17615. var imgHeight = currentY + maxLineHeight + IMAGE_PADDING;
  17616. var imgData = new Uint8Array(imgWidth * imgHeight * 4);
  17617. var imgRowSize = imgWidth << 2;
  17618. for (q = 0; q < count; q++) {
  17619. var data = argsArray[iFirstPIIXO + (q << 2)][0].data;
  17620. // Copy image by lines and extends pixels into padding.
  17621. var rowSize = map[q].w << 2;
  17622. var dataOffset = 0;
  17623. var offset = (map[q].x + map[q].y * imgWidth) << 2;
  17624. imgData.set(data.subarray(0, rowSize), offset - imgRowSize);
  17625. for (var k = 0, kk = map[q].h; k < kk; k++) {
  17626. imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);
  17627. dataOffset += rowSize;
  17628. offset += imgRowSize;
  17629. }
  17630. imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);
  17631. while (offset >= 0) {
  17632. data[offset - 4] = data[offset];
  17633. data[offset - 3] = data[offset + 1];
  17634. data[offset - 2] = data[offset + 2];
  17635. data[offset - 1] = data[offset + 3];
  17636. data[offset + rowSize] = data[offset + rowSize - 4];
  17637. data[offset + rowSize + 1] = data[offset + rowSize - 3];
  17638. data[offset + rowSize + 2] = data[offset + rowSize - 2];
  17639. data[offset + rowSize + 3] = data[offset + rowSize - 1];
  17640. offset -= imgRowSize;
  17641. }
  17642. }
  17643. // Replace queue items.
  17644. fnArray.splice(iFirstSave, count * 4, OPS.paintInlineImageXObjectGroup);
  17645. argsArray.splice(iFirstSave, count * 4,
  17646. [{ width: imgWidth, height: imgHeight, kind: ImageKind.RGBA_32BPP,
  17647. data: imgData }, map]);
  17648. return iFirstSave + 1;
  17649. });
  17650. // This replaces (save, transform, paintImageMaskXObject, restore)+
  17651. // sequences with one |paintImageMaskXObjectGroup| or one
  17652. // |paintImageMaskXObjectRepeat| operation.
  17653. addState(InitialState,
  17654. [OPS.save, OPS.transform, OPS.paintImageMaskXObject, OPS.restore],
  17655. function foundImageMaskGroup(context) {
  17656. var MIN_IMAGES_IN_MASKS_BLOCK = 10;
  17657. var MAX_IMAGES_IN_MASKS_BLOCK = 100;
  17658. var MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;
  17659. var fnArray = context.fnArray, argsArray = context.argsArray;
  17660. var curr = context.iCurr;
  17661. var iFirstSave = curr - 3;
  17662. var iFirstTransform = curr - 2;
  17663. var iFirstPIMXO = curr - 1;
  17664. // Look for the quartets.
  17665. var i = iFirstSave + 4;
  17666. var ii = fnArray.length;
  17667. while (i + 3 < ii) {
  17668. if (fnArray[i] !== OPS.save ||
  17669. fnArray[i + 1] !== OPS.transform ||
  17670. fnArray[i + 2] !== OPS.paintImageMaskXObject ||
  17671. fnArray[i + 3] !== OPS.restore) {
  17672. break; // ops don't match
  17673. }
  17674. i += 4;
  17675. }
  17676. // At this point, i is the index of the first op past the last valid
  17677. // quartet.
  17678. var count = (i - iFirstSave) / 4;
  17679. count = handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
  17680. argsArray);
  17681. if (count < MIN_IMAGES_IN_MASKS_BLOCK) {
  17682. return i;
  17683. }
  17684. var q;
  17685. var isSameImage = false;
  17686. var iTransform, transformArgs;
  17687. var firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
  17688. if (argsArray[iFirstTransform][1] === 0 &&
  17689. argsArray[iFirstTransform][2] === 0) {
  17690. isSameImage = true;
  17691. var firstTransformArg0 = argsArray[iFirstTransform][0];
  17692. var firstTransformArg3 = argsArray[iFirstTransform][3];
  17693. iTransform = iFirstTransform + 4;
  17694. var iPIMXO = iFirstPIMXO + 4;
  17695. for (q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) {
  17696. transformArgs = argsArray[iTransform];
  17697. if (argsArray[iPIMXO][0] !== firstPIMXOArg0 ||
  17698. transformArgs[0] !== firstTransformArg0 ||
  17699. transformArgs[1] !== 0 ||
  17700. transformArgs[2] !== 0 ||
  17701. transformArgs[3] !== firstTransformArg3) {
  17702. if (q < MIN_IMAGES_IN_MASKS_BLOCK) {
  17703. isSameImage = false;
  17704. } else {
  17705. count = q;
  17706. }
  17707. break; // different image or transform
  17708. }
  17709. }
  17710. }
  17711. if (isSameImage) {
  17712. count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);
  17713. var positions = new Float32Array(count * 2);
  17714. iTransform = iFirstTransform;
  17715. for (q = 0; q < count; q++, iTransform += 4) {
  17716. transformArgs = argsArray[iTransform];
  17717. positions[(q << 1)] = transformArgs[4];
  17718. positions[(q << 1) + 1] = transformArgs[5];
  17719. }
  17720. // Replace queue items.
  17721. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectRepeat);
  17722. argsArray.splice(iFirstSave, count * 4,
  17723. [firstPIMXOArg0, firstTransformArg0, firstTransformArg3, positions]);
  17724. } else {
  17725. count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);
  17726. var images = [];
  17727. for (q = 0; q < count; q++) {
  17728. transformArgs = argsArray[iFirstTransform + (q << 2)];
  17729. var maskParams = argsArray[iFirstPIMXO + (q << 2)][0];
  17730. images.push({ data: maskParams.data, width: maskParams.width,
  17731. height: maskParams.height,
  17732. transform: transformArgs });
  17733. }
  17734. // Replace queue items.
  17735. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectGroup);
  17736. argsArray.splice(iFirstSave, count * 4, [images]);
  17737. }
  17738. return iFirstSave + 1;
  17739. });
  17740. // This replaces (save, transform, paintImageXObject, restore)+ sequences
  17741. // with one paintImageXObjectRepeat operation, if the |transform| and
  17742. // |paintImageXObjectRepeat| ops are appropriate.
  17743. addState(InitialState,
  17744. [OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore],
  17745. function (context) {
  17746. var MIN_IMAGES_IN_BLOCK = 3;
  17747. var MAX_IMAGES_IN_BLOCK = 1000;
  17748. var fnArray = context.fnArray, argsArray = context.argsArray;
  17749. var curr = context.iCurr;
  17750. var iFirstSave = curr - 3;
  17751. var iFirstTransform = curr - 2;
  17752. var iFirstPIXO = curr - 1;
  17753. var iFirstRestore = curr;
  17754. if (argsArray[iFirstTransform][1] !== 0 ||
  17755. argsArray[iFirstTransform][2] !== 0) {
  17756. return iFirstRestore + 1; // transform has the wrong form
  17757. }
  17758. // Look for the quartets.
  17759. var firstPIXOArg0 = argsArray[iFirstPIXO][0];
  17760. var firstTransformArg0 = argsArray[iFirstTransform][0];
  17761. var firstTransformArg3 = argsArray[iFirstTransform][3];
  17762. var i = iFirstSave + 4;
  17763. var ii = fnArray.length;
  17764. while (i + 3 < ii) {
  17765. if (fnArray[i] !== OPS.save ||
  17766. fnArray[i + 1] !== OPS.transform ||
  17767. fnArray[i + 2] !== OPS.paintImageXObject ||
  17768. fnArray[i + 3] !== OPS.restore) {
  17769. break; // ops don't match
  17770. }
  17771. if (argsArray[i + 1][0] !== firstTransformArg0 ||
  17772. argsArray[i + 1][1] !== 0 ||
  17773. argsArray[i + 1][2] !== 0 ||
  17774. argsArray[i + 1][3] !== firstTransformArg3) {
  17775. break; // transforms don't match
  17776. }
  17777. if (argsArray[i + 2][0] !== firstPIXOArg0) {
  17778. break; // images don't match
  17779. }
  17780. i += 4;
  17781. }
  17782. // At this point, i is the index of the first op past the last valid
  17783. // quartet.
  17784. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_BLOCK);
  17785. if (count < MIN_IMAGES_IN_BLOCK) {
  17786. return i;
  17787. }
  17788. // Extract the (x,y) positions from all of the matching transforms.
  17789. var positions = new Float32Array(count * 2);
  17790. var iTransform = iFirstTransform;
  17791. for (var q = 0; q < count; q++, iTransform += 4) {
  17792. var transformArgs = argsArray[iTransform];
  17793. positions[(q << 1)] = transformArgs[4];
  17794. positions[(q << 1) + 1] = transformArgs[5];
  17795. }
  17796. // Replace queue items.
  17797. var args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3,
  17798. positions];
  17799. fnArray.splice(iFirstSave, count * 4, OPS.paintImageXObjectRepeat);
  17800. argsArray.splice(iFirstSave, count * 4, args);
  17801. return iFirstSave + 1;
  17802. });
  17803. // This replaces (beginText, setFont, setTextMatrix, showText, endText)+
  17804. // sequences with (beginText, setFont, (setTextMatrix, showText)+, endText)+
  17805. // sequences, if the font for each one is the same.
  17806. addState(InitialState,
  17807. [OPS.beginText, OPS.setFont, OPS.setTextMatrix, OPS.showText, OPS.endText],
  17808. function (context) {
  17809. var MIN_CHARS_IN_BLOCK = 3;
  17810. var MAX_CHARS_IN_BLOCK = 1000;
  17811. var fnArray = context.fnArray, argsArray = context.argsArray;
  17812. var curr = context.iCurr;
  17813. var iFirstBeginText = curr - 4;
  17814. var iFirstSetFont = curr - 3;
  17815. var iFirstSetTextMatrix = curr - 2;
  17816. var iFirstShowText = curr - 1;
  17817. var iFirstEndText = curr;
  17818. // Look for the quintets.
  17819. var firstSetFontArg0 = argsArray[iFirstSetFont][0];
  17820. var firstSetFontArg1 = argsArray[iFirstSetFont][1];
  17821. var i = iFirstBeginText + 5;
  17822. var ii = fnArray.length;
  17823. while (i + 4 < ii) {
  17824. if (fnArray[i] !== OPS.beginText ||
  17825. fnArray[i + 1] !== OPS.setFont ||
  17826. fnArray[i + 2] !== OPS.setTextMatrix ||
  17827. fnArray[i + 3] !== OPS.showText ||
  17828. fnArray[i + 4] !== OPS.endText) {
  17829. break; // ops don't match
  17830. }
  17831. if (argsArray[i + 1][0] !== firstSetFontArg0 ||
  17832. argsArray[i + 1][1] !== firstSetFontArg1) {
  17833. break; // fonts don't match
  17834. }
  17835. i += 5;
  17836. }
  17837. // At this point, i is the index of the first op past the last valid
  17838. // quintet.
  17839. var count = Math.min(((i - iFirstBeginText) / 5), MAX_CHARS_IN_BLOCK);
  17840. if (count < MIN_CHARS_IN_BLOCK) {
  17841. return i;
  17842. }
  17843. // If the preceding quintet is (<something>, setFont, setTextMatrix,
  17844. // showText, endText), include that as well. (E.g. <something> might be
  17845. // |dependency|.)
  17846. var iFirst = iFirstBeginText;
  17847. if (iFirstBeginText >= 4 &&
  17848. fnArray[iFirstBeginText - 4] === fnArray[iFirstSetFont] &&
  17849. fnArray[iFirstBeginText - 3] === fnArray[iFirstSetTextMatrix] &&
  17850. fnArray[iFirstBeginText - 2] === fnArray[iFirstShowText] &&
  17851. fnArray[iFirstBeginText - 1] === fnArray[iFirstEndText] &&
  17852. argsArray[iFirstBeginText - 4][0] === firstSetFontArg0 &&
  17853. argsArray[iFirstBeginText - 4][1] === firstSetFontArg1) {
  17854. count++;
  17855. iFirst -= 5;
  17856. }
  17857. // Remove (endText, beginText, setFont) trios.
  17858. var iEndText = iFirst + 4;
  17859. for (var q = 1; q < count; q++) {
  17860. fnArray.splice(iEndText, 3);
  17861. argsArray.splice(iEndText, 3);
  17862. iEndText += 2;
  17863. }
  17864. return iEndText + 1;
  17865. });
  17866. function QueueOptimizer() {}
  17867. QueueOptimizer.prototype = {
  17868. optimize: function QueueOptimizer_optimize(queue) {
  17869. var fnArray = queue.fnArray, argsArray = queue.argsArray;
  17870. var context = {
  17871. iCurr: 0,
  17872. fnArray: fnArray,
  17873. argsArray: argsArray
  17874. };
  17875. var state;
  17876. var i = 0, ii = fnArray.length;
  17877. while (i < ii) {
  17878. state = (state || InitialState)[fnArray[i]];
  17879. if (typeof state === 'function') { // we found some handler
  17880. context.iCurr = i;
  17881. // state() returns the index of the first non-matching op (if we
  17882. // didn't match) or the first op past the modified ops (if we did
  17883. // match and replace).
  17884. i = state(context);
  17885. state = undefined; // reset the state machine
  17886. ii = context.fnArray.length;
  17887. } else {
  17888. i++;
  17889. }
  17890. }
  17891. }
  17892. };
  17893. return QueueOptimizer;
  17894. })();
  17895. var BUILT_IN_CMAPS = [
  17896. // << Start unicode maps.
  17897. 'Adobe-GB1-UCS2',
  17898. 'Adobe-CNS1-UCS2',
  17899. 'Adobe-Japan1-UCS2',
  17900. 'Adobe-Korea1-UCS2',
  17901. // >> End unicode maps.
  17902. '78-EUC-H',
  17903. '78-EUC-V',
  17904. '78-H',
  17905. '78-RKSJ-H',
  17906. '78-RKSJ-V',
  17907. '78-V',
  17908. '78ms-RKSJ-H',
  17909. '78ms-RKSJ-V',
  17910. '83pv-RKSJ-H',
  17911. '90ms-RKSJ-H',
  17912. '90ms-RKSJ-V',
  17913. '90msp-RKSJ-H',
  17914. '90msp-RKSJ-V',
  17915. '90pv-RKSJ-H',
  17916. '90pv-RKSJ-V',
  17917. 'Add-H',
  17918. 'Add-RKSJ-H',
  17919. 'Add-RKSJ-V',
  17920. 'Add-V',
  17921. 'Adobe-CNS1-0',
  17922. 'Adobe-CNS1-1',
  17923. 'Adobe-CNS1-2',
  17924. 'Adobe-CNS1-3',
  17925. 'Adobe-CNS1-4',
  17926. 'Adobe-CNS1-5',
  17927. 'Adobe-CNS1-6',
  17928. 'Adobe-GB1-0',
  17929. 'Adobe-GB1-1',
  17930. 'Adobe-GB1-2',
  17931. 'Adobe-GB1-3',
  17932. 'Adobe-GB1-4',
  17933. 'Adobe-GB1-5',
  17934. 'Adobe-Japan1-0',
  17935. 'Adobe-Japan1-1',
  17936. 'Adobe-Japan1-2',
  17937. 'Adobe-Japan1-3',
  17938. 'Adobe-Japan1-4',
  17939. 'Adobe-Japan1-5',
  17940. 'Adobe-Japan1-6',
  17941. 'Adobe-Korea1-0',
  17942. 'Adobe-Korea1-1',
  17943. 'Adobe-Korea1-2',
  17944. 'B5-H',
  17945. 'B5-V',
  17946. 'B5pc-H',
  17947. 'B5pc-V',
  17948. 'CNS-EUC-H',
  17949. 'CNS-EUC-V',
  17950. 'CNS1-H',
  17951. 'CNS1-V',
  17952. 'CNS2-H',
  17953. 'CNS2-V',
  17954. 'ETHK-B5-H',
  17955. 'ETHK-B5-V',
  17956. 'ETen-B5-H',
  17957. 'ETen-B5-V',
  17958. 'ETenms-B5-H',
  17959. 'ETenms-B5-V',
  17960. 'EUC-H',
  17961. 'EUC-V',
  17962. 'Ext-H',
  17963. 'Ext-RKSJ-H',
  17964. 'Ext-RKSJ-V',
  17965. 'Ext-V',
  17966. 'GB-EUC-H',
  17967. 'GB-EUC-V',
  17968. 'GB-H',
  17969. 'GB-V',
  17970. 'GBK-EUC-H',
  17971. 'GBK-EUC-V',
  17972. 'GBK2K-H',
  17973. 'GBK2K-V',
  17974. 'GBKp-EUC-H',
  17975. 'GBKp-EUC-V',
  17976. 'GBT-EUC-H',
  17977. 'GBT-EUC-V',
  17978. 'GBT-H',
  17979. 'GBT-V',
  17980. 'GBTpc-EUC-H',
  17981. 'GBTpc-EUC-V',
  17982. 'GBpc-EUC-H',
  17983. 'GBpc-EUC-V',
  17984. 'H',
  17985. 'HKdla-B5-H',
  17986. 'HKdla-B5-V',
  17987. 'HKdlb-B5-H',
  17988. 'HKdlb-B5-V',
  17989. 'HKgccs-B5-H',
  17990. 'HKgccs-B5-V',
  17991. 'HKm314-B5-H',
  17992. 'HKm314-B5-V',
  17993. 'HKm471-B5-H',
  17994. 'HKm471-B5-V',
  17995. 'HKscs-B5-H',
  17996. 'HKscs-B5-V',
  17997. 'Hankaku',
  17998. 'Hiragana',
  17999. 'KSC-EUC-H',
  18000. 'KSC-EUC-V',
  18001. 'KSC-H',
  18002. 'KSC-Johab-H',
  18003. 'KSC-Johab-V',
  18004. 'KSC-V',
  18005. 'KSCms-UHC-H',
  18006. 'KSCms-UHC-HW-H',
  18007. 'KSCms-UHC-HW-V',
  18008. 'KSCms-UHC-V',
  18009. 'KSCpc-EUC-H',
  18010. 'KSCpc-EUC-V',
  18011. 'Katakana',
  18012. 'NWP-H',
  18013. 'NWP-V',
  18014. 'RKSJ-H',
  18015. 'RKSJ-V',
  18016. 'Roman',
  18017. 'UniCNS-UCS2-H',
  18018. 'UniCNS-UCS2-V',
  18019. 'UniCNS-UTF16-H',
  18020. 'UniCNS-UTF16-V',
  18021. 'UniCNS-UTF32-H',
  18022. 'UniCNS-UTF32-V',
  18023. 'UniCNS-UTF8-H',
  18024. 'UniCNS-UTF8-V',
  18025. 'UniGB-UCS2-H',
  18026. 'UniGB-UCS2-V',
  18027. 'UniGB-UTF16-H',
  18028. 'UniGB-UTF16-V',
  18029. 'UniGB-UTF32-H',
  18030. 'UniGB-UTF32-V',
  18031. 'UniGB-UTF8-H',
  18032. 'UniGB-UTF8-V',
  18033. 'UniJIS-UCS2-H',
  18034. 'UniJIS-UCS2-HW-H',
  18035. 'UniJIS-UCS2-HW-V',
  18036. 'UniJIS-UCS2-V',
  18037. 'UniJIS-UTF16-H',
  18038. 'UniJIS-UTF16-V',
  18039. 'UniJIS-UTF32-H',
  18040. 'UniJIS-UTF32-V',
  18041. 'UniJIS-UTF8-H',
  18042. 'UniJIS-UTF8-V',
  18043. 'UniJIS2004-UTF16-H',
  18044. 'UniJIS2004-UTF16-V',
  18045. 'UniJIS2004-UTF32-H',
  18046. 'UniJIS2004-UTF32-V',
  18047. 'UniJIS2004-UTF8-H',
  18048. 'UniJIS2004-UTF8-V',
  18049. 'UniJISPro-UCS2-HW-V',
  18050. 'UniJISPro-UCS2-V',
  18051. 'UniJISPro-UTF8-V',
  18052. 'UniJISX0213-UTF32-H',
  18053. 'UniJISX0213-UTF32-V',
  18054. 'UniJISX02132004-UTF32-H',
  18055. 'UniJISX02132004-UTF32-V',
  18056. 'UniKS-UCS2-H',
  18057. 'UniKS-UCS2-V',
  18058. 'UniKS-UTF16-H',
  18059. 'UniKS-UTF16-V',
  18060. 'UniKS-UTF32-H',
  18061. 'UniKS-UTF32-V',
  18062. 'UniKS-UTF8-H',
  18063. 'UniKS-UTF8-V',
  18064. 'V',
  18065. 'WP-Symbol'];
  18066. // CMap, not to be confused with TrueType's cmap.
  18067. var CMap = (function CMapClosure() {
  18068. function CMap(builtInCMap) {
  18069. // Codespace ranges are stored as follows:
  18070. // [[1BytePairs], [2BytePairs], [3BytePairs], [4BytePairs]]
  18071. // where nBytePairs are ranges e.g. [low1, high1, low2, high2, ...]
  18072. this.codespaceRanges = [[], [], [], []];
  18073. this.numCodespaceRanges = 0;
  18074. // Map entries have one of two forms.
  18075. // - cid chars are 16-bit unsigned integers, stored as integers.
  18076. // - bf chars are variable-length byte sequences, stored as strings, with
  18077. // one byte per character.
  18078. this._map = [];
  18079. this.name = '';
  18080. this.vertical = false;
  18081. this.useCMap = null;
  18082. this.builtInCMap = builtInCMap;
  18083. }
  18084. CMap.prototype = {
  18085. addCodespaceRange: function(n, low, high) {
  18086. this.codespaceRanges[n - 1].push(low, high);
  18087. this.numCodespaceRanges++;
  18088. },
  18089. mapCidRange: function(low, high, dstLow) {
  18090. while (low <= high) {
  18091. this._map[low++] = dstLow++;
  18092. }
  18093. },
  18094. mapBfRange: function(low, high, dstLow) {
  18095. var lastByte = dstLow.length - 1;
  18096. while (low <= high) {
  18097. this._map[low++] = dstLow;
  18098. // Only the last byte has to be incremented.
  18099. dstLow = dstLow.substr(0, lastByte) +
  18100. String.fromCharCode(dstLow.charCodeAt(lastByte) + 1);
  18101. }
  18102. },
  18103. mapBfRangeToArray: function(low, high, array) {
  18104. var i = 0, ii = array.length;
  18105. while (low <= high && i < ii) {
  18106. this._map[low] = array[i++];
  18107. ++low;
  18108. }
  18109. },
  18110. // This is used for both bf and cid chars.
  18111. mapOne: function(src, dst) {
  18112. this._map[src] = dst;
  18113. },
  18114. lookup: function(code) {
  18115. return this._map[code];
  18116. },
  18117. contains: function(code) {
  18118. return this._map[code] !== undefined;
  18119. },
  18120. forEach: function(callback) {
  18121. // Most maps have fewer than 65536 entries, and for those we use normal
  18122. // array iteration. But really sparse tables are possible -- e.g. with
  18123. // indices in the *billions*. For such tables we use for..in, which isn't
  18124. // ideal because it stringifies the indices for all present elements, but
  18125. // it does avoid iterating over every undefined entry.
  18126. var map = this._map;
  18127. var length = map.length;
  18128. var i;
  18129. if (length <= 0x10000) {
  18130. for (i = 0; i < length; i++) {
  18131. if (map[i] !== undefined) {
  18132. callback(i, map[i]);
  18133. }
  18134. }
  18135. } else {
  18136. for (i in this._map) {
  18137. callback(i, map[i]);
  18138. }
  18139. }
  18140. },
  18141. charCodeOf: function(value) {
  18142. return this._map.indexOf(value);
  18143. },
  18144. getMap: function() {
  18145. return this._map;
  18146. },
  18147. readCharCode: function(str, offset, out) {
  18148. var c = 0;
  18149. var codespaceRanges = this.codespaceRanges;
  18150. var codespaceRangesLen = this.codespaceRanges.length;
  18151. // 9.7.6.2 CMap Mapping
  18152. // The code length is at most 4.
  18153. for (var n = 0; n < codespaceRangesLen; n++) {
  18154. c = ((c << 8) | str.charCodeAt(offset + n)) >>> 0;
  18155. // Check each codespace range to see if it falls within.
  18156. var codespaceRange = codespaceRanges[n];
  18157. for (var k = 0, kk = codespaceRange.length; k < kk;) {
  18158. var low = codespaceRange[k++];
  18159. var high = codespaceRange[k++];
  18160. if (c >= low && c <= high) {
  18161. out.charcode = c;
  18162. out.length = n + 1;
  18163. return;
  18164. }
  18165. }
  18166. }
  18167. out.charcode = 0;
  18168. out.length = 1;
  18169. },
  18170. get isIdentityCMap() {
  18171. if (!(this.name === 'Identity-H' || this.name === 'Identity-V')) {
  18172. return false;
  18173. }
  18174. if (this._map.length !== 0x10000) {
  18175. return false;
  18176. }
  18177. for (var i = 0; i < 0x10000; i++) {
  18178. if (this._map[i] !== i) {
  18179. return false;
  18180. }
  18181. }
  18182. return true;
  18183. }
  18184. };
  18185. return CMap;
  18186. })();
  18187. // A special case of CMap, where the _map array implicitly has a length of
  18188. // 65536 and each element is equal to its index.
  18189. var IdentityCMap = (function IdentityCMapClosure() {
  18190. function IdentityCMap(vertical, n) {
  18191. CMap.call(this);
  18192. this.vertical = vertical;
  18193. this.addCodespaceRange(n, 0, 0xffff);
  18194. }
  18195. Util.inherit(IdentityCMap, CMap, {});
  18196. IdentityCMap.prototype = {
  18197. addCodespaceRange: CMap.prototype.addCodespaceRange,
  18198. mapCidRange: function(low, high, dstLow) {
  18199. error('should not call mapCidRange');
  18200. },
  18201. mapBfRange: function(low, high, dstLow) {
  18202. error('should not call mapBfRange');
  18203. },
  18204. mapBfRangeToArray: function(low, high, array) {
  18205. error('should not call mapBfRangeToArray');
  18206. },
  18207. mapOne: function(src, dst) {
  18208. error('should not call mapCidOne');
  18209. },
  18210. lookup: function(code) {
  18211. return (isInt(code) && code <= 0xffff) ? code : undefined;
  18212. },
  18213. contains: function(code) {
  18214. return isInt(code) && code <= 0xffff;
  18215. },
  18216. forEach: function(callback) {
  18217. for (var i = 0; i <= 0xffff; i++) {
  18218. callback(i, i);
  18219. }
  18220. },
  18221. charCodeOf: function(value) {
  18222. return (isInt(value) && value <= 0xffff) ? value : -1;
  18223. },
  18224. getMap: function() {
  18225. // Sometimes identity maps must be instantiated, but it's rare.
  18226. var map = new Array(0x10000);
  18227. for (var i = 0; i <= 0xffff; i++) {
  18228. map[i] = i;
  18229. }
  18230. return map;
  18231. },
  18232. readCharCode: CMap.prototype.readCharCode,
  18233. get isIdentityCMap() {
  18234. error('should not access .isIdentityCMap');
  18235. }
  18236. };
  18237. return IdentityCMap;
  18238. })();
  18239. var BinaryCMapReader = (function BinaryCMapReaderClosure() {
  18240. function fetchBinaryData(url) {
  18241. var nonBinaryRequest = PDFJS.disableWorker;
  18242. var request = new XMLHttpRequest();
  18243. request.open('GET', url, false);
  18244. if (!nonBinaryRequest) {
  18245. try {
  18246. request.responseType = 'arraybuffer';
  18247. nonBinaryRequest = request.responseType !== 'arraybuffer';
  18248. } catch (e) {
  18249. nonBinaryRequest = true;
  18250. }
  18251. }
  18252. if (nonBinaryRequest && request.overrideMimeType) {
  18253. request.overrideMimeType('text/plain; charset=x-user-defined');
  18254. }
  18255. request.send(null);
  18256. if (nonBinaryRequest ? !request.responseText : !request.response) {
  18257. error('Unable to get binary cMap at: ' + url);
  18258. }
  18259. if (nonBinaryRequest) {
  18260. var data = Array.prototype.map.call(request.responseText, function (ch) {
  18261. return ch.charCodeAt(0) & 255;
  18262. });
  18263. return new Uint8Array(data);
  18264. }
  18265. return new Uint8Array(request.response);
  18266. }
  18267. function hexToInt(a, size) {
  18268. var n = 0;
  18269. for (var i = 0; i <= size; i++) {
  18270. n = (n << 8) | a[i];
  18271. }
  18272. return n >>> 0;
  18273. }
  18274. function hexToStr(a, size) {
  18275. // This code is hot. Special-case some common values to avoid creating an
  18276. // object with subarray().
  18277. if (size === 1) {
  18278. return String.fromCharCode(a[0], a[1]);
  18279. }
  18280. if (size === 3) {
  18281. return String.fromCharCode(a[0], a[1], a[2], a[3]);
  18282. }
  18283. return String.fromCharCode.apply(null, a.subarray(0, size + 1));
  18284. }
  18285. function addHex(a, b, size) {
  18286. var c = 0;
  18287. for (var i = size; i >= 0; i--) {
  18288. c += a[i] + b[i];
  18289. a[i] = c & 255;
  18290. c >>= 8;
  18291. }
  18292. }
  18293. function incHex(a, size) {
  18294. var c = 1;
  18295. for (var i = size; i >= 0 && c > 0; i--) {
  18296. c += a[i];
  18297. a[i] = c & 255;
  18298. c >>= 8;
  18299. }
  18300. }
  18301. var MAX_NUM_SIZE = 16;
  18302. var MAX_ENCODED_NUM_SIZE = 19; // ceil(MAX_NUM_SIZE * 7 / 8)
  18303. function BinaryCMapStream(data) {
  18304. this.buffer = data;
  18305. this.pos = 0;
  18306. this.end = data.length;
  18307. this.tmpBuf = new Uint8Array(MAX_ENCODED_NUM_SIZE);
  18308. }
  18309. BinaryCMapStream.prototype = {
  18310. readByte: function () {
  18311. if (this.pos >= this.end) {
  18312. return -1;
  18313. }
  18314. return this.buffer[this.pos++];
  18315. },
  18316. readNumber: function () {
  18317. var n = 0;
  18318. var last;
  18319. do {
  18320. var b = this.readByte();
  18321. if (b < 0) {
  18322. error('unexpected EOF in bcmap');
  18323. }
  18324. last = !(b & 0x80);
  18325. n = (n << 7) | (b & 0x7F);
  18326. } while (!last);
  18327. return n;
  18328. },
  18329. readSigned: function () {
  18330. var n = this.readNumber();
  18331. return (n & 1) ? ~(n >>> 1) : n >>> 1;
  18332. },
  18333. readHex: function (num, size) {
  18334. num.set(this.buffer.subarray(this.pos,
  18335. this.pos + size + 1));
  18336. this.pos += size + 1;
  18337. },
  18338. readHexNumber: function (num, size) {
  18339. var last;
  18340. var stack = this.tmpBuf, sp = 0;
  18341. do {
  18342. var b = this.readByte();
  18343. if (b < 0) {
  18344. error('unexpected EOF in bcmap');
  18345. }
  18346. last = !(b & 0x80);
  18347. stack[sp++] = b & 0x7F;
  18348. } while (!last);
  18349. var i = size, buffer = 0, bufferSize = 0;
  18350. while (i >= 0) {
  18351. while (bufferSize < 8 && stack.length > 0) {
  18352. buffer = (stack[--sp] << bufferSize) | buffer;
  18353. bufferSize += 7;
  18354. }
  18355. num[i] = buffer & 255;
  18356. i--;
  18357. buffer >>= 8;
  18358. bufferSize -= 8;
  18359. }
  18360. },
  18361. readHexSigned: function (num, size) {
  18362. this.readHexNumber(num, size);
  18363. var sign = num[size] & 1 ? 255 : 0;
  18364. var c = 0;
  18365. for (var i = 0; i <= size; i++) {
  18366. c = ((c & 1) << 8) | num[i];
  18367. num[i] = (c >> 1) ^ sign;
  18368. }
  18369. },
  18370. readString: function () {
  18371. var len = this.readNumber();
  18372. var s = '';
  18373. for (var i = 0; i < len; i++) {
  18374. s += String.fromCharCode(this.readNumber());
  18375. }
  18376. return s;
  18377. }
  18378. };
  18379. function processBinaryCMap(url, cMap, extend) {
  18380. var data = fetchBinaryData(url);
  18381. var stream = new BinaryCMapStream(data);
  18382. var header = stream.readByte();
  18383. cMap.vertical = !!(header & 1);
  18384. var useCMap = null;
  18385. var start = new Uint8Array(MAX_NUM_SIZE);
  18386. var end = new Uint8Array(MAX_NUM_SIZE);
  18387. var char = new Uint8Array(MAX_NUM_SIZE);
  18388. var charCode = new Uint8Array(MAX_NUM_SIZE);
  18389. var tmp = new Uint8Array(MAX_NUM_SIZE);
  18390. var code;
  18391. var b;
  18392. while ((b = stream.readByte()) >= 0) {
  18393. var type = b >> 5;
  18394. if (type === 7) { // metadata, e.g. comment or usecmap
  18395. switch (b & 0x1F) {
  18396. case 0:
  18397. stream.readString(); // skipping comment
  18398. break;
  18399. case 1:
  18400. useCMap = stream.readString();
  18401. break;
  18402. }
  18403. continue;
  18404. }
  18405. var sequence = !!(b & 0x10);
  18406. var dataSize = b & 15;
  18407. assert(dataSize + 1 <= MAX_NUM_SIZE);
  18408. var ucs2DataSize = 1;
  18409. var subitemsCount = stream.readNumber();
  18410. var i;
  18411. switch (type) {
  18412. case 0: // codespacerange
  18413. stream.readHex(start, dataSize);
  18414. stream.readHexNumber(end, dataSize);
  18415. addHex(end, start, dataSize);
  18416. cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
  18417. hexToInt(end, dataSize));
  18418. for (i = 1; i < subitemsCount; i++) {
  18419. incHex(end, dataSize);
  18420. stream.readHexNumber(start, dataSize);
  18421. addHex(start, end, dataSize);
  18422. stream.readHexNumber(end, dataSize);
  18423. addHex(end, start, dataSize);
  18424. cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
  18425. hexToInt(end, dataSize));
  18426. }
  18427. break;
  18428. case 1: // notdefrange
  18429. stream.readHex(start, dataSize);
  18430. stream.readHexNumber(end, dataSize);
  18431. addHex(end, start, dataSize);
  18432. code = stream.readNumber();
  18433. // undefined range, skipping
  18434. for (i = 1; i < subitemsCount; i++) {
  18435. incHex(end, dataSize);
  18436. stream.readHexNumber(start, dataSize);
  18437. addHex(start, end, dataSize);
  18438. stream.readHexNumber(end, dataSize);
  18439. addHex(end, start, dataSize);
  18440. code = stream.readNumber();
  18441. // nop
  18442. }
  18443. break;
  18444. case 2: // cidchar
  18445. stream.readHex(char, dataSize);
  18446. code = stream.readNumber();
  18447. cMap.mapOne(hexToInt(char, dataSize), code);
  18448. for (i = 1; i < subitemsCount; i++) {
  18449. incHex(char, dataSize);
  18450. if (!sequence) {
  18451. stream.readHexNumber(tmp, dataSize);
  18452. addHex(char, tmp, dataSize);
  18453. }
  18454. code = stream.readSigned() + (code + 1);
  18455. cMap.mapOne(hexToInt(char, dataSize), code);
  18456. }
  18457. break;
  18458. case 3: // cidrange
  18459. stream.readHex(start, dataSize);
  18460. stream.readHexNumber(end, dataSize);
  18461. addHex(end, start, dataSize);
  18462. code = stream.readNumber();
  18463. cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
  18464. code);
  18465. for (i = 1; i < subitemsCount; i++) {
  18466. incHex(end, dataSize);
  18467. if (!sequence) {
  18468. stream.readHexNumber(start, dataSize);
  18469. addHex(start, end, dataSize);
  18470. } else {
  18471. start.set(end);
  18472. }
  18473. stream.readHexNumber(end, dataSize);
  18474. addHex(end, start, dataSize);
  18475. code = stream.readNumber();
  18476. cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
  18477. code);
  18478. }
  18479. break;
  18480. case 4: // bfchar
  18481. stream.readHex(char, ucs2DataSize);
  18482. stream.readHex(charCode, dataSize);
  18483. cMap.mapOne(hexToInt(char, ucs2DataSize),
  18484. hexToStr(charCode, dataSize));
  18485. for (i = 1; i < subitemsCount; i++) {
  18486. incHex(char, ucs2DataSize);
  18487. if (!sequence) {
  18488. stream.readHexNumber(tmp, ucs2DataSize);
  18489. addHex(char, tmp, ucs2DataSize);
  18490. }
  18491. incHex(charCode, dataSize);
  18492. stream.readHexSigned(tmp, dataSize);
  18493. addHex(charCode, tmp, dataSize);
  18494. cMap.mapOne(hexToInt(char, ucs2DataSize),
  18495. hexToStr(charCode, dataSize));
  18496. }
  18497. break;
  18498. case 5: // bfrange
  18499. stream.readHex(start, ucs2DataSize);
  18500. stream.readHexNumber(end, ucs2DataSize);
  18501. addHex(end, start, ucs2DataSize);
  18502. stream.readHex(charCode, dataSize);
  18503. cMap.mapBfRange(hexToInt(start, ucs2DataSize),
  18504. hexToInt(end, ucs2DataSize),
  18505. hexToStr(charCode, dataSize));
  18506. for (i = 1; i < subitemsCount; i++) {
  18507. incHex(end, ucs2DataSize);
  18508. if (!sequence) {
  18509. stream.readHexNumber(start, ucs2DataSize);
  18510. addHex(start, end, ucs2DataSize);
  18511. } else {
  18512. start.set(end);
  18513. }
  18514. stream.readHexNumber(end, ucs2DataSize);
  18515. addHex(end, start, ucs2DataSize);
  18516. stream.readHex(charCode, dataSize);
  18517. cMap.mapBfRange(hexToInt(start, ucs2DataSize),
  18518. hexToInt(end, ucs2DataSize),
  18519. hexToStr(charCode, dataSize));
  18520. }
  18521. break;
  18522. default:
  18523. error('Unknown type: ' + type);
  18524. break;
  18525. }
  18526. }
  18527. if (useCMap) {
  18528. extend(useCMap);
  18529. }
  18530. return cMap;
  18531. }
  18532. function BinaryCMapReader() {}
  18533. BinaryCMapReader.prototype = {
  18534. read: processBinaryCMap
  18535. };
  18536. return BinaryCMapReader;
  18537. })();
  18538. var CMapFactory = (function CMapFactoryClosure() {
  18539. function strToInt(str) {
  18540. var a = 0;
  18541. for (var i = 0; i < str.length; i++) {
  18542. a = (a << 8) | str.charCodeAt(i);
  18543. }
  18544. return a >>> 0;
  18545. }
  18546. function expectString(obj) {
  18547. if (!isString(obj)) {
  18548. error('Malformed CMap: expected string.');
  18549. }
  18550. }
  18551. function expectInt(obj) {
  18552. if (!isInt(obj)) {
  18553. error('Malformed CMap: expected int.');
  18554. }
  18555. }
  18556. function parseBfChar(cMap, lexer) {
  18557. while (true) {
  18558. var obj = lexer.getObj();
  18559. if (isEOF(obj)) {
  18560. break;
  18561. }
  18562. if (isCmd(obj, 'endbfchar')) {
  18563. return;
  18564. }
  18565. expectString(obj);
  18566. var src = strToInt(obj);
  18567. obj = lexer.getObj();
  18568. // TODO are /dstName used?
  18569. expectString(obj);
  18570. var dst = obj;
  18571. cMap.mapOne(src, dst);
  18572. }
  18573. }
  18574. function parseBfRange(cMap, lexer) {
  18575. while (true) {
  18576. var obj = lexer.getObj();
  18577. if (isEOF(obj)) {
  18578. break;
  18579. }
  18580. if (isCmd(obj, 'endbfrange')) {
  18581. return;
  18582. }
  18583. expectString(obj);
  18584. var low = strToInt(obj);
  18585. obj = lexer.getObj();
  18586. expectString(obj);
  18587. var high = strToInt(obj);
  18588. obj = lexer.getObj();
  18589. if (isInt(obj) || isString(obj)) {
  18590. var dstLow = isInt(obj) ? String.fromCharCode(obj) : obj;
  18591. cMap.mapBfRange(low, high, dstLow);
  18592. } else if (isCmd(obj, '[')) {
  18593. obj = lexer.getObj();
  18594. var array = [];
  18595. while (!isCmd(obj, ']') && !isEOF(obj)) {
  18596. array.push(obj);
  18597. obj = lexer.getObj();
  18598. }
  18599. cMap.mapBfRangeToArray(low, high, array);
  18600. } else {
  18601. break;
  18602. }
  18603. }
  18604. error('Invalid bf range.');
  18605. }
  18606. function parseCidChar(cMap, lexer) {
  18607. while (true) {
  18608. var obj = lexer.getObj();
  18609. if (isEOF(obj)) {
  18610. break;
  18611. }
  18612. if (isCmd(obj, 'endcidchar')) {
  18613. return;
  18614. }
  18615. expectString(obj);
  18616. var src = strToInt(obj);
  18617. obj = lexer.getObj();
  18618. expectInt(obj);
  18619. var dst = obj;
  18620. cMap.mapOne(src, dst);
  18621. }
  18622. }
  18623. function parseCidRange(cMap, lexer) {
  18624. while (true) {
  18625. var obj = lexer.getObj();
  18626. if (isEOF(obj)) {
  18627. break;
  18628. }
  18629. if (isCmd(obj, 'endcidrange')) {
  18630. return;
  18631. }
  18632. expectString(obj);
  18633. var low = strToInt(obj);
  18634. obj = lexer.getObj();
  18635. expectString(obj);
  18636. var high = strToInt(obj);
  18637. obj = lexer.getObj();
  18638. expectInt(obj);
  18639. var dstLow = obj;
  18640. cMap.mapCidRange(low, high, dstLow);
  18641. }
  18642. }
  18643. function parseCodespaceRange(cMap, lexer) {
  18644. while (true) {
  18645. var obj = lexer.getObj();
  18646. if (isEOF(obj)) {
  18647. break;
  18648. }
  18649. if (isCmd(obj, 'endcodespacerange')) {
  18650. return;
  18651. }
  18652. if (!isString(obj)) {
  18653. break;
  18654. }
  18655. var low = strToInt(obj);
  18656. obj = lexer.getObj();
  18657. if (!isString(obj)) {
  18658. break;
  18659. }
  18660. var high = strToInt(obj);
  18661. cMap.addCodespaceRange(obj.length, low, high);
  18662. }
  18663. error('Invalid codespace range.');
  18664. }
  18665. function parseWMode(cMap, lexer) {
  18666. var obj = lexer.getObj();
  18667. if (isInt(obj)) {
  18668. cMap.vertical = !!obj;
  18669. }
  18670. }
  18671. function parseCMapName(cMap, lexer) {
  18672. var obj = lexer.getObj();
  18673. if (isName(obj) && isString(obj.name)) {
  18674. cMap.name = obj.name;
  18675. }
  18676. }
  18677. function parseCMap(cMap, lexer, builtInCMapParams, useCMap) {
  18678. var previous;
  18679. var embededUseCMap;
  18680. objLoop: while (true) {
  18681. var obj = lexer.getObj();
  18682. if (isEOF(obj)) {
  18683. break;
  18684. } else if (isName(obj)) {
  18685. if (obj.name === 'WMode') {
  18686. parseWMode(cMap, lexer);
  18687. } else if (obj.name === 'CMapName') {
  18688. parseCMapName(cMap, lexer);
  18689. }
  18690. previous = obj;
  18691. } else if (isCmd(obj)) {
  18692. switch (obj.cmd) {
  18693. case 'endcmap':
  18694. break objLoop;
  18695. case 'usecmap':
  18696. if (isName(previous)) {
  18697. embededUseCMap = previous.name;
  18698. }
  18699. break;
  18700. case 'begincodespacerange':
  18701. parseCodespaceRange(cMap, lexer);
  18702. break;
  18703. case 'beginbfchar':
  18704. parseBfChar(cMap, lexer);
  18705. break;
  18706. case 'begincidchar':
  18707. parseCidChar(cMap, lexer);
  18708. break;
  18709. case 'beginbfrange':
  18710. parseBfRange(cMap, lexer);
  18711. break;
  18712. case 'begincidrange':
  18713. parseCidRange(cMap, lexer);
  18714. break;
  18715. }
  18716. }
  18717. }
  18718. if (!useCMap && embededUseCMap) {
  18719. // Load the usecmap definition from the file only if there wasn't one
  18720. // specified.
  18721. useCMap = embededUseCMap;
  18722. }
  18723. if (useCMap) {
  18724. extendCMap(cMap, builtInCMapParams, useCMap);
  18725. }
  18726. }
  18727. function extendCMap(cMap, builtInCMapParams, useCMap) {
  18728. cMap.useCMap = createBuiltInCMap(useCMap, builtInCMapParams);
  18729. // If there aren't any code space ranges defined clone all the parent ones
  18730. // into this cMap.
  18731. if (cMap.numCodespaceRanges === 0) {
  18732. var useCodespaceRanges = cMap.useCMap.codespaceRanges;
  18733. for (var i = 0; i < useCodespaceRanges.length; i++) {
  18734. cMap.codespaceRanges[i] = useCodespaceRanges[i].slice();
  18735. }
  18736. cMap.numCodespaceRanges = cMap.useCMap.numCodespaceRanges;
  18737. }
  18738. // Merge the map into the current one, making sure not to override
  18739. // any previously defined entries.
  18740. cMap.useCMap.forEach(function(key, value) {
  18741. if (!cMap.contains(key)) {
  18742. cMap.mapOne(key, cMap.useCMap.lookup(key));
  18743. }
  18744. });
  18745. }
  18746. function parseBinaryCMap(name, builtInCMapParams) {
  18747. var url = builtInCMapParams.url + name + '.bcmap';
  18748. var cMap = new CMap(true);
  18749. new BinaryCMapReader().read(url, cMap, function (useCMap) {
  18750. extendCMap(cMap, builtInCMapParams, useCMap);
  18751. });
  18752. return cMap;
  18753. }
  18754. function createBuiltInCMap(name, builtInCMapParams) {
  18755. if (name === 'Identity-H') {
  18756. return new IdentityCMap(false, 2);
  18757. } else if (name === 'Identity-V') {
  18758. return new IdentityCMap(true, 2);
  18759. }
  18760. if (BUILT_IN_CMAPS.indexOf(name) === -1) {
  18761. error('Unknown cMap name: ' + name);
  18762. }
  18763. assert(builtInCMapParams, 'built-in cMap parameters are not provided');
  18764. if (builtInCMapParams.packed) {
  18765. return parseBinaryCMap(name, builtInCMapParams);
  18766. }
  18767. var request = new XMLHttpRequest();
  18768. var url = builtInCMapParams.url + name;
  18769. request.open('GET', url, false);
  18770. request.send(null);
  18771. if (!request.responseText) {
  18772. error('Unable to get cMap at: ' + url);
  18773. }
  18774. var cMap = new CMap(true);
  18775. var lexer = new Lexer(new StringStream(request.responseText));
  18776. parseCMap(cMap, lexer, builtInCMapParams, null);
  18777. return cMap;
  18778. }
  18779. return {
  18780. create: function (encoding, builtInCMapParams, useCMap) {
  18781. if (isName(encoding)) {
  18782. return createBuiltInCMap(encoding.name, builtInCMapParams);
  18783. } else if (isStream(encoding)) {
  18784. var cMap = new CMap();
  18785. var lexer = new Lexer(encoding);
  18786. try {
  18787. parseCMap(cMap, lexer, builtInCMapParams, useCMap);
  18788. } catch (e) {
  18789. warn('Invalid CMap data. ' + e);
  18790. }
  18791. if (cMap.isIdentityCMap) {
  18792. return createBuiltInCMap(cMap.name, builtInCMapParams);
  18793. }
  18794. return cMap;
  18795. }
  18796. error('Encoding required.');
  18797. }
  18798. };
  18799. })();
  18800. // Unicode Private Use Area
  18801. var PRIVATE_USE_OFFSET_START = 0xE000;
  18802. var PRIVATE_USE_OFFSET_END = 0xF8FF;
  18803. var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false;
  18804. // PDF Glyph Space Units are one Thousandth of a TextSpace Unit
  18805. // except for Type 3 fonts
  18806. var PDF_GLYPH_SPACE_UNITS = 1000;
  18807. // Hinting is currently disabled due to unknown problems on windows
  18808. // in tracemonkey and various other pdfs with type1 fonts.
  18809. var HINTING_ENABLED = false;
  18810. // Accented charactars are not displayed properly on windows, using this flag
  18811. // to control analysis of seac charstrings.
  18812. var SEAC_ANALYSIS_ENABLED = false;
  18813. var FontFlags = {
  18814. FixedPitch: 1,
  18815. Serif: 2,
  18816. Symbolic: 4,
  18817. Script: 8,
  18818. Nonsymbolic: 32,
  18819. Italic: 64,
  18820. AllCap: 65536,
  18821. SmallCap: 131072,
  18822. ForceBold: 262144
  18823. };
  18824. var Encodings = {
  18825. ExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18826. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18827. 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle',
  18828. 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
  18829. 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
  18830. 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
  18831. 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
  18832. 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon',
  18833. 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior',
  18834. 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior',
  18835. 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior',
  18836. 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior',
  18837. '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '',
  18838. 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
  18839. 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
  18840. 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
  18841. 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
  18842. 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
  18843. 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '',
  18844. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18845. '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
  18846. '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall',
  18847. 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '',
  18848. 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall',
  18849. 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters',
  18850. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
  18851. 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior',
  18852. 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior',
  18853. 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior',
  18854. 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior',
  18855. 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior',
  18856. 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior',
  18857. 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall',
  18858. 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall',
  18859. 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
  18860. 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  18861. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
  18862. 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
  18863. 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  18864. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
  18865. 'Ydieresissmall'],
  18866. MacExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18867. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18868. 'space', 'exclamsmall', 'Hungarumlautsmall', 'centoldstyle',
  18869. 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall',
  18870. 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  18871. 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle',
  18872. 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle',
  18873. 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle',
  18874. 'nineoldstyle', 'colon', 'semicolon', '', 'threequartersemdash', '',
  18875. 'questionsmall', '', '', '', '', 'Ethsmall', '', '', 'onequarter',
  18876. 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
  18877. 'seveneighths', 'onethird', 'twothirds', '', '', '', '', '', '', 'ff',
  18878. 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior',
  18879. 'Circumflexsmall', 'hypheninferior', 'Gravesmall', 'Asmall', 'Bsmall',
  18880. 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
  18881. 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
  18882. 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  18883. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
  18884. 'Tildesmall', '', '', 'asuperior', 'centsuperior', '', '', '', '',
  18885. 'Aacutesmall', 'Agravesmall', 'Acircumflexsmall', 'Adieresissmall',
  18886. 'Atildesmall', 'Aringsmall', 'Ccedillasmall', 'Eacutesmall', 'Egravesmall',
  18887. 'Ecircumflexsmall', 'Edieresissmall', 'Iacutesmall', 'Igravesmall',
  18888. 'Icircumflexsmall', 'Idieresissmall', 'Ntildesmall', 'Oacutesmall',
  18889. 'Ogravesmall', 'Ocircumflexsmall', 'Odieresissmall', 'Otildesmall',
  18890. 'Uacutesmall', 'Ugravesmall', 'Ucircumflexsmall', 'Udieresissmall', '',
  18891. 'eightsuperior', 'fourinferior', 'threeinferior', 'sixinferior',
  18892. 'eightinferior', 'seveninferior', 'Scaronsmall', '', 'centinferior',
  18893. 'twoinferior', '', 'Dieresissmall', '', 'Caronsmall', 'osuperior',
  18894. 'fiveinferior', '', 'commainferior', 'periodinferior', 'Yacutesmall', '',
  18895. 'dollarinferior', '', 'Thornsmall', '', 'nineinferior', 'zeroinferior',
  18896. 'Zcaronsmall', 'AEsmall', 'Oslashsmall', 'questiondownsmall',
  18897. 'oneinferior', 'Lslashsmall', '', '', '', '', '', '', 'Cedillasmall', '',
  18898. '', '', '', '', 'OEsmall', 'figuredash', 'hyphensuperior', '', '', '', '',
  18899. 'exclamdownsmall', '', 'Ydieresissmall', '', 'onesuperior', 'twosuperior',
  18900. 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
  18901. 'sevensuperior', 'ninesuperior', 'zerosuperior', '', 'esuperior',
  18902. 'rsuperior', 'tsuperior', '', '', 'isuperior', 'ssuperior', 'dsuperior',
  18903. '', '', '', '', '', 'lsuperior', 'Ogoneksmall', 'Brevesmall',
  18904. 'Macronsmall', 'bsuperior', 'nsuperior', 'msuperior', 'commasuperior',
  18905. 'periodsuperior', 'Dotaccentsmall', 'Ringsmall'],
  18906. MacRomanEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18907. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18908. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  18909. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus',
  18910. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  18911. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  18912. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  18913. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  18914. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  18915. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  18916. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  18917. 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '',
  18918. 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis',
  18919. 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde',
  18920. 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  18921. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute',
  18922. 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave',
  18923. 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling',
  18924. 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright',
  18925. 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity',
  18926. 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff',
  18927. 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine',
  18928. 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot',
  18929. 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft',
  18930. 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE',
  18931. 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft',
  18932. 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction',
  18933. 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl',
  18934. 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand',
  18935. 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute',
  18936. 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple',
  18937. 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex',
  18938. 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut',
  18939. 'ogonek', 'caron'],
  18940. StandardEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18941. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18942. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  18943. 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
  18944. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  18945. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  18946. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  18947. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  18948. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  18949. 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f',
  18950. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
  18951. 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  18952. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18953. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdown',
  18954. 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  18955. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  18956. 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', 'daggerdbl',
  18957. 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase',
  18958. 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
  18959. 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex',
  18960. 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla',
  18961. '', 'hungarumlaut', 'ogonek', 'caron', 'emdash', '', '', '', '', '', '',
  18962. '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '',
  18963. '', '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae',
  18964. '', '', '', 'dotlessi', '', '', 'lslash', 'oslash', 'oe', 'germandbls'],
  18965. WinAnsiEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18966. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18967. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  18968. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus',
  18969. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  18970. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  18971. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  18972. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  18973. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  18974. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  18975. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  18976. 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  18977. 'bullet', 'Euro', 'bullet', 'quotesinglbase', 'florin', 'quotedblbase',
  18978. 'ellipsis', 'dagger', 'daggerdbl', 'circumflex', 'perthousand', 'Scaron',
  18979. 'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', 'quoteleft',
  18980. 'quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash',
  18981. 'emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', 'oe', 'bullet',
  18982. 'zcaron', 'Ydieresis', 'space', 'exclamdown', 'cent', 'sterling',
  18983. 'currency', 'yen', 'brokenbar', 'section', 'dieresis', 'copyright',
  18984. 'ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', 'registered',
  18985. 'macron', 'degree', 'plusminus', 'twosuperior', 'threesuperior', 'acute',
  18986. 'mu', 'paragraph', 'periodcentered', 'cedilla', 'onesuperior',
  18987. 'ordmasculine', 'guillemotright', 'onequarter', 'onehalf', 'threequarters',
  18988. 'questiondown', 'Agrave', 'Aacute', 'Acircumflex', 'Atilde', 'Adieresis',
  18989. 'Aring', 'AE', 'Ccedilla', 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis',
  18990. 'Igrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve',
  18991. 'Oacute', 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash',
  18992. 'Ugrave', 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn',
  18993. 'germandbls', 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis',
  18994. 'aring', 'ae', 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis',
  18995. 'igrave', 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve',
  18996. 'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash',
  18997. 'ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn',
  18998. 'ydieresis'],
  18999. SymbolSetEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19000. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19001. 'space', 'exclam', 'universal', 'numbersign', 'existential', 'percent',
  19002. 'ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus',
  19003. 'comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
  19004. 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  19005. 'equal', 'greater', 'question', 'congruent', 'Alpha', 'Beta', 'Chi',
  19006. 'Delta', 'Epsilon', 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa',
  19007. 'Lambda', 'Mu', 'Nu', 'Omicron', 'Pi', 'Theta', 'Rho', 'Sigma', 'Tau',
  19008. 'Upsilon', 'sigma1', 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft',
  19009. 'therefore', 'bracketright', 'perpendicular', 'underscore', 'radicalex',
  19010. 'alpha', 'beta', 'chi', 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota',
  19011. 'phi1', 'kappa', 'lambda', 'mu', 'nu', 'omicron', 'pi', 'theta', 'rho',
  19012. 'sigma', 'tau', 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta',
  19013. 'braceleft', 'bar', 'braceright', 'similar', '', '', '', '', '', '', '',
  19014. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19015. '', '', '', '', '', '', '', 'Euro', 'Upsilon1', 'minute', 'lessequal',
  19016. 'fraction', 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade',
  19017. 'arrowboth', 'arrowleft', 'arrowup', 'arrowright', 'arrowdown', 'degree',
  19018. 'plusminus', 'second', 'greaterequal', 'multiply', 'proportional',
  19019. 'partialdiff', 'bullet', 'divide', 'notequal', 'equivalence',
  19020. 'approxequal', 'ellipsis', 'arrowvertex', 'arrowhorizex', 'carriagereturn',
  19021. 'aleph', 'Ifraktur', 'Rfraktur', 'weierstrass', 'circlemultiply',
  19022. 'circleplus', 'emptyset', 'intersection', 'union', 'propersuperset',
  19023. 'reflexsuperset', 'notsubset', 'propersubset', 'reflexsubset', 'element',
  19024. 'notelement', 'angle', 'gradient', 'registerserif', 'copyrightserif',
  19025. 'trademarkserif', 'product', 'radical', 'dotmath', 'logicalnot',
  19026. 'logicaland', 'logicalor', 'arrowdblboth', 'arrowdblleft', 'arrowdblup',
  19027. 'arrowdblright', 'arrowdbldown', 'lozenge', 'angleleft', 'registersans',
  19028. 'copyrightsans', 'trademarksans', 'summation', 'parenlefttp',
  19029. 'parenleftex', 'parenleftbt', 'bracketlefttp', 'bracketleftex',
  19030. 'bracketleftbt', 'bracelefttp', 'braceleftmid', 'braceleftbt', 'braceex',
  19031. '', 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt',
  19032. 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp',
  19033. 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid',
  19034. 'bracerightbt'],
  19035. ZapfDingbatsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19036. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  19037. 'space', 'a1', 'a2', 'a202', 'a3', 'a4', 'a5', 'a119', 'a118', 'a117',
  19038. 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a105', 'a17', 'a18', 'a19',
  19039. 'a20', 'a21', 'a22', 'a23', 'a24', 'a25', 'a26', 'a27', 'a28', 'a6', 'a7',
  19040. 'a8', 'a9', 'a10', 'a29', 'a30', 'a31', 'a32', 'a33', 'a34', 'a35', 'a36',
  19041. 'a37', 'a38', 'a39', 'a40', 'a41', 'a42', 'a43', 'a44', 'a45', 'a46',
  19042. 'a47', 'a48', 'a49', 'a50', 'a51', 'a52', 'a53', 'a54', 'a55', 'a56',
  19043. 'a57', 'a58', 'a59', 'a60', 'a61', 'a62', 'a63', 'a64', 'a65', 'a66',
  19044. 'a67', 'a68', 'a69', 'a70', 'a71', 'a72', 'a73', 'a74', 'a203', 'a75',
  19045. 'a204', 'a76', 'a77', 'a78', 'a79', 'a81', 'a82', 'a83', 'a84', 'a97',
  19046. 'a98', 'a99', 'a100', '', 'a89', 'a90', 'a93', 'a94', 'a91', 'a92', 'a205',
  19047. 'a85', 'a206', 'a86', 'a87', 'a88', 'a95', 'a96', '', '', '', '', '', '',
  19048. '', '', '', '', '', '', '', '', '', '', '', '', '', 'a101', 'a102', 'a103',
  19049. 'a104', 'a106', 'a107', 'a108', 'a112', 'a111', 'a110', 'a109', 'a120',
  19050. 'a121', 'a122', 'a123', 'a124', 'a125', 'a126', 'a127', 'a128', 'a129',
  19051. 'a130', 'a131', 'a132', 'a133', 'a134', 'a135', 'a136', 'a137', 'a138',
  19052. 'a139', 'a140', 'a141', 'a142', 'a143', 'a144', 'a145', 'a146', 'a147',
  19053. 'a148', 'a149', 'a150', 'a151', 'a152', 'a153', 'a154', 'a155', 'a156',
  19054. 'a157', 'a158', 'a159', 'a160', 'a161', 'a163', 'a164', 'a196', 'a165',
  19055. 'a192', 'a166', 'a167', 'a168', 'a169', 'a170', 'a171', 'a172', 'a173',
  19056. 'a162', 'a174', 'a175', 'a176', 'a177', 'a178', 'a179', 'a193', 'a180',
  19057. 'a199', 'a181', 'a200', 'a182', '', 'a201', 'a183', 'a184', 'a197', 'a185',
  19058. 'a194', 'a198', 'a186', 'a195', 'a187', 'a188', 'a189', 'a190', 'a191']
  19059. };
  19060. /**
  19061. * Hold a map of decoded fonts and of the standard fourteen Type1
  19062. * fonts and their acronyms.
  19063. */
  19064. var stdFontMap = {
  19065. 'ArialNarrow': 'Helvetica',
  19066. 'ArialNarrow-Bold': 'Helvetica-Bold',
  19067. 'ArialNarrow-BoldItalic': 'Helvetica-BoldOblique',
  19068. 'ArialNarrow-Italic': 'Helvetica-Oblique',
  19069. 'ArialBlack': 'Helvetica',
  19070. 'ArialBlack-Bold': 'Helvetica-Bold',
  19071. 'ArialBlack-BoldItalic': 'Helvetica-BoldOblique',
  19072. 'ArialBlack-Italic': 'Helvetica-Oblique',
  19073. 'Arial': 'Helvetica',
  19074. 'Arial-Bold': 'Helvetica-Bold',
  19075. 'Arial-BoldItalic': 'Helvetica-BoldOblique',
  19076. 'Arial-Italic': 'Helvetica-Oblique',
  19077. 'Arial-BoldItalicMT': 'Helvetica-BoldOblique',
  19078. 'Arial-BoldMT': 'Helvetica-Bold',
  19079. 'Arial-ItalicMT': 'Helvetica-Oblique',
  19080. 'ArialMT': 'Helvetica',
  19081. 'Courier-Bold': 'Courier-Bold',
  19082. 'Courier-BoldItalic': 'Courier-BoldOblique',
  19083. 'Courier-Italic': 'Courier-Oblique',
  19084. 'CourierNew': 'Courier',
  19085. 'CourierNew-Bold': 'Courier-Bold',
  19086. 'CourierNew-BoldItalic': 'Courier-BoldOblique',
  19087. 'CourierNew-Italic': 'Courier-Oblique',
  19088. 'CourierNewPS-BoldItalicMT': 'Courier-BoldOblique',
  19089. 'CourierNewPS-BoldMT': 'Courier-Bold',
  19090. 'CourierNewPS-ItalicMT': 'Courier-Oblique',
  19091. 'CourierNewPSMT': 'Courier',
  19092. 'Helvetica': 'Helvetica',
  19093. 'Helvetica-Bold': 'Helvetica-Bold',
  19094. 'Helvetica-BoldItalic': 'Helvetica-BoldOblique',
  19095. 'Helvetica-BoldOblique': 'Helvetica-BoldOblique',
  19096. 'Helvetica-Italic': 'Helvetica-Oblique',
  19097. 'Helvetica-Oblique':'Helvetica-Oblique',
  19098. 'Symbol-Bold': 'Symbol',
  19099. 'Symbol-BoldItalic': 'Symbol',
  19100. 'Symbol-Italic': 'Symbol',
  19101. 'TimesNewRoman': 'Times-Roman',
  19102. 'TimesNewRoman-Bold': 'Times-Bold',
  19103. 'TimesNewRoman-BoldItalic': 'Times-BoldItalic',
  19104. 'TimesNewRoman-Italic': 'Times-Italic',
  19105. 'TimesNewRomanPS': 'Times-Roman',
  19106. 'TimesNewRomanPS-Bold': 'Times-Bold',
  19107. 'TimesNewRomanPS-BoldItalic': 'Times-BoldItalic',
  19108. 'TimesNewRomanPS-BoldItalicMT': 'Times-BoldItalic',
  19109. 'TimesNewRomanPS-BoldMT': 'Times-Bold',
  19110. 'TimesNewRomanPS-Italic': 'Times-Italic',
  19111. 'TimesNewRomanPS-ItalicMT': 'Times-Italic',
  19112. 'TimesNewRomanPSMT': 'Times-Roman',
  19113. 'TimesNewRomanPSMT-Bold': 'Times-Bold',
  19114. 'TimesNewRomanPSMT-BoldItalic': 'Times-BoldItalic',
  19115. 'TimesNewRomanPSMT-Italic': 'Times-Italic'
  19116. };
  19117. /**
  19118. * Holds the map of the non-standard fonts that might be included as a standard
  19119. * fonts without glyph data.
  19120. */
  19121. var nonStdFontMap = {
  19122. 'CenturyGothic': 'Helvetica',
  19123. 'CenturyGothic-Bold': 'Helvetica-Bold',
  19124. 'CenturyGothic-BoldItalic': 'Helvetica-BoldOblique',
  19125. 'CenturyGothic-Italic': 'Helvetica-Oblique',
  19126. 'ComicSansMS': 'Comic Sans MS',
  19127. 'ComicSansMS-Bold': 'Comic Sans MS-Bold',
  19128. 'ComicSansMS-BoldItalic': 'Comic Sans MS-BoldItalic',
  19129. 'ComicSansMS-Italic': 'Comic Sans MS-Italic',
  19130. 'LucidaConsole': 'Courier',
  19131. 'LucidaConsole-Bold': 'Courier-Bold',
  19132. 'LucidaConsole-BoldItalic': 'Courier-BoldOblique',
  19133. 'LucidaConsole-Italic': 'Courier-Oblique',
  19134. 'MS-Gothic': 'MS Gothic',
  19135. 'MS-Gothic-Bold': 'MS Gothic-Bold',
  19136. 'MS-Gothic-BoldItalic': 'MS Gothic-BoldItalic',
  19137. 'MS-Gothic-Italic': 'MS Gothic-Italic',
  19138. 'MS-Mincho': 'MS Mincho',
  19139. 'MS-Mincho-Bold': 'MS Mincho-Bold',
  19140. 'MS-Mincho-BoldItalic': 'MS Mincho-BoldItalic',
  19141. 'MS-Mincho-Italic': 'MS Mincho-Italic',
  19142. 'MS-PGothic': 'MS PGothic',
  19143. 'MS-PGothic-Bold': 'MS PGothic-Bold',
  19144. 'MS-PGothic-BoldItalic': 'MS PGothic-BoldItalic',
  19145. 'MS-PGothic-Italic': 'MS PGothic-Italic',
  19146. 'MS-PMincho': 'MS PMincho',
  19147. 'MS-PMincho-Bold': 'MS PMincho-Bold',
  19148. 'MS-PMincho-BoldItalic': 'MS PMincho-BoldItalic',
  19149. 'MS-PMincho-Italic': 'MS PMincho-Italic',
  19150. 'Wingdings': 'ZapfDingbats'
  19151. };
  19152. var serifFonts = {
  19153. 'Adobe Jenson': true, 'Adobe Text': true, 'Albertus': true,
  19154. 'Aldus': true, 'Alexandria': true, 'Algerian': true,
  19155. 'American Typewriter': true, 'Antiqua': true, 'Apex': true,
  19156. 'Arno': true, 'Aster': true, 'Aurora': true,
  19157. 'Baskerville': true, 'Bell': true, 'Bembo': true,
  19158. 'Bembo Schoolbook': true, 'Benguiat': true, 'Berkeley Old Style': true,
  19159. 'Bernhard Modern': true, 'Berthold City': true, 'Bodoni': true,
  19160. 'Bauer Bodoni': true, 'Book Antiqua': true, 'Bookman': true,
  19161. 'Bordeaux Roman': true, 'Californian FB': true, 'Calisto': true,
  19162. 'Calvert': true, 'Capitals': true, 'Cambria': true,
  19163. 'Cartier': true, 'Caslon': true, 'Catull': true,
  19164. 'Centaur': true, 'Century Old Style': true, 'Century Schoolbook': true,
  19165. 'Chaparral': true, 'Charis SIL': true, 'Cheltenham': true,
  19166. 'Cholla Slab': true, 'Clarendon': true, 'Clearface': true,
  19167. 'Cochin': true, 'Colonna': true, 'Computer Modern': true,
  19168. 'Concrete Roman': true, 'Constantia': true, 'Cooper Black': true,
  19169. 'Corona': true, 'Ecotype': true, 'Egyptienne': true,
  19170. 'Elephant': true, 'Excelsior': true, 'Fairfield': true,
  19171. 'FF Scala': true, 'Folkard': true, 'Footlight': true,
  19172. 'FreeSerif': true, 'Friz Quadrata': true, 'Garamond': true,
  19173. 'Gentium': true, 'Georgia': true, 'Gloucester': true,
  19174. 'Goudy Old Style': true, 'Goudy Schoolbook': true, 'Goudy Pro Font': true,
  19175. 'Granjon': true, 'Guardian Egyptian': true, 'Heather': true,
  19176. 'Hercules': true, 'High Tower Text': true, 'Hiroshige': true,
  19177. 'Hoefler Text': true, 'Humana Serif': true, 'Imprint': true,
  19178. 'Ionic No. 5': true, 'Janson': true, 'Joanna': true,
  19179. 'Korinna': true, 'Lexicon': true, 'Liberation Serif': true,
  19180. 'Linux Libertine': true, 'Literaturnaya': true, 'Lucida': true,
  19181. 'Lucida Bright': true, 'Melior': true, 'Memphis': true,
  19182. 'Miller': true, 'Minion': true, 'Modern': true,
  19183. 'Mona Lisa': true, 'Mrs Eaves': true, 'MS Serif': true,
  19184. 'Museo Slab': true, 'New York': true, 'Nimbus Roman': true,
  19185. 'NPS Rawlinson Roadway': true, 'Palatino': true, 'Perpetua': true,
  19186. 'Plantin': true, 'Plantin Schoolbook': true, 'Playbill': true,
  19187. 'Poor Richard': true, 'Rawlinson Roadway': true, 'Renault': true,
  19188. 'Requiem': true, 'Rockwell': true, 'Roman': true,
  19189. 'Rotis Serif': true, 'Sabon': true, 'Scala': true,
  19190. 'Seagull': true, 'Sistina': true, 'Souvenir': true,
  19191. 'STIX': true, 'Stone Informal': true, 'Stone Serif': true,
  19192. 'Sylfaen': true, 'Times': true, 'Trajan': true,
  19193. 'Trinité': true, 'Trump Mediaeval': true, 'Utopia': true,
  19194. 'Vale Type': true, 'Bitstream Vera': true, 'Vera Serif': true,
  19195. 'Versailles': true, 'Wanted': true, 'Weiss': true,
  19196. 'Wide Latin': true, 'Windsor': true, 'XITS': true
  19197. };
  19198. var symbolsFonts = {
  19199. 'Dingbats': true, 'Symbol': true, 'ZapfDingbats': true
  19200. };
  19201. // Glyph map for well-known standard fonts. Sometimes Ghostscript uses CID fonts
  19202. // but does not embed the CID to GID mapping. The mapping is incomplete for all
  19203. // glyphs, but common for some set of the standard fonts.
  19204. var GlyphMapForStandardFonts = {
  19205. '2': 10, '3': 32, '4': 33, '5': 34, '6': 35, '7': 36, '8': 37, '9': 38,
  19206. '10': 39, '11': 40, '12': 41, '13': 42, '14': 43, '15': 44, '16': 45,
  19207. '17': 46, '18': 47, '19': 48, '20': 49, '21': 50, '22': 51, '23': 52,
  19208. '24': 53, '25': 54, '26': 55, '27': 56, '28': 57, '29': 58, '30': 894,
  19209. '31': 60, '32': 61, '33': 62, '34': 63, '35': 64, '36': 65, '37': 66,
  19210. '38': 67, '39': 68, '40': 69, '41': 70, '42': 71, '43': 72, '44': 73,
  19211. '45': 74, '46': 75, '47': 76, '48': 77, '49': 78, '50': 79, '51': 80,
  19212. '52': 81, '53': 82, '54': 83, '55': 84, '56': 85, '57': 86, '58': 87,
  19213. '59': 88, '60': 89, '61': 90, '62': 91, '63': 92, '64': 93, '65': 94,
  19214. '66': 95, '67': 96, '68': 97, '69': 98, '70': 99, '71': 100, '72': 101,
  19215. '73': 102, '74': 103, '75': 104, '76': 105, '77': 106, '78': 107, '79': 108,
  19216. '80': 109, '81': 110, '82': 111, '83': 112, '84': 113, '85': 114, '86': 115,
  19217. '87': 116, '88': 117, '89': 118, '90': 119, '91': 120, '92': 121, '93': 122,
  19218. '94': 123, '95': 124, '96': 125, '97': 126, '98': 196, '99': 197, '100': 199,
  19219. '101': 201, '102': 209, '103': 214, '104': 220, '105': 225, '106': 224,
  19220. '107': 226, '108': 228, '109': 227, '110': 229, '111': 231, '112': 233,
  19221. '113': 232, '114': 234, '115': 235, '116': 237, '117': 236, '118': 238,
  19222. '119': 239, '120': 241, '121': 243, '122': 242, '123': 244, '124': 246,
  19223. '125': 245, '126': 250, '127': 249, '128': 251, '129': 252, '130': 8224,
  19224. '131': 176, '132': 162, '133': 163, '134': 167, '135': 8226, '136': 182,
  19225. '137': 223, '138': 174, '139': 169, '140': 8482, '141': 180, '142': 168,
  19226. '143': 8800, '144': 198, '145': 216, '146': 8734, '147': 177, '148': 8804,
  19227. '149': 8805, '150': 165, '151': 181, '152': 8706, '153': 8721, '154': 8719,
  19228. '156': 8747, '157': 170, '158': 186, '159': 8486, '160': 230, '161': 248,
  19229. '162': 191, '163': 161, '164': 172, '165': 8730, '166': 402, '167': 8776,
  19230. '168': 8710, '169': 171, '170': 187, '171': 8230, '210': 218, '223': 711,
  19231. '224': 321, '225': 322, '227': 353, '229': 382, '234': 253, '252': 263,
  19232. '253': 268, '254': 269, '258': 258, '260': 260, '261': 261, '265': 280,
  19233. '266': 281, '268': 283, '269': 313, '275': 323, '276': 324, '278': 328,
  19234. '284': 345, '285': 346, '286': 347, '292': 367, '295': 377, '296': 378,
  19235. '298': 380, '305': 963,
  19236. '306': 964, '307': 966, '308': 8215, '309': 8252, '310': 8319, '311': 8359,
  19237. '312': 8592, '313': 8593, '337': 9552, '493': 1039, '494': 1040, '705': 1524,
  19238. '706': 8362, '710': 64288, '711': 64298, '759': 1617, '761': 1776,
  19239. '763': 1778, '775': 1652, '777': 1764, '778': 1780, '779': 1781, '780': 1782,
  19240. '782': 771, '783': 64726, '786': 8363, '788': 8532, '790': 768, '791': 769,
  19241. '792': 768, '795': 803, '797': 64336, '798': 64337, '799': 64342,
  19242. '800': 64343, '801': 64344, '802': 64345, '803': 64362, '804': 64363,
  19243. '805': 64364, '2424': 7821, '2425': 7822, '2426': 7823, '2427': 7824,
  19244. '2428': 7825, '2429': 7826, '2430': 7827, '2433': 7682, '2678': 8045,
  19245. '2679': 8046, '2830': 1552, '2838': 686, '2840': 751, '2842': 753,
  19246. '2843': 754, '2844': 755, '2846': 757, '2856': 767, '2857': 848, '2858': 849,
  19247. '2862': 853, '2863': 854, '2864': 855, '2865': 861, '2866': 862, '2906': 7460,
  19248. '2908': 7462, '2909': 7463, '2910': 7464, '2912': 7466, '2913': 7467,
  19249. '2914': 7468, '2916': 7470, '2917': 7471, '2918': 7472, '2920': 7474,
  19250. '2921': 7475, '2922': 7476, '2924': 7478, '2925': 7479, '2926': 7480,
  19251. '2928': 7482, '2929': 7483, '2930': 7484, '2932': 7486, '2933': 7487,
  19252. '2934': 7488, '2936': 7490, '2937': 7491, '2938': 7492, '2940': 7494,
  19253. '2941': 7495, '2942': 7496, '2944': 7498, '2946': 7500, '2948': 7502,
  19254. '2950': 7504, '2951': 7505, '2952': 7506, '2954': 7508, '2955': 7509,
  19255. '2956': 7510, '2958': 7512, '2959': 7513, '2960': 7514, '2962': 7516,
  19256. '2963': 7517, '2964': 7518, '2966': 7520, '2967': 7521, '2968': 7522,
  19257. '2970': 7524, '2971': 7525, '2972': 7526, '2974': 7528, '2975': 7529,
  19258. '2976': 7530, '2978': 1537, '2979': 1538, '2980': 1539, '2982': 1549,
  19259. '2983': 1551, '2984': 1552, '2986': 1554, '2987': 1555, '2988': 1556,
  19260. '2990': 1623, '2991': 1624, '2995': 1775, '2999': 1791, '3002': 64290,
  19261. '3003': 64291, '3004': 64292, '3006': 64294, '3007': 64295, '3008': 64296,
  19262. '3011': 1900, '3014': 8223, '3015': 8244, '3017': 7532, '3018': 7533,
  19263. '3019': 7534, '3075': 7590, '3076': 7591, '3079': 7594, '3080': 7595,
  19264. '3083': 7598, '3084': 7599, '3087': 7602, '3088': 7603, '3091': 7606,
  19265. '3092': 7607, '3095': 7610, '3096': 7611, '3099': 7614, '3100': 7615,
  19266. '3103': 7618, '3104': 7619, '3107': 8337, '3108': 8338, '3116': 1884,
  19267. '3119': 1885, '3120': 1885, '3123': 1886, '3124': 1886, '3127': 1887,
  19268. '3128': 1887, '3131': 1888, '3132': 1888, '3135': 1889, '3136': 1889,
  19269. '3139': 1890, '3140': 1890, '3143': 1891, '3144': 1891, '3147': 1892,
  19270. '3148': 1892, '3153': 580, '3154': 581, '3157': 584, '3158': 585, '3161': 588,
  19271. '3162': 589, '3165': 891, '3166': 892, '3169': 1274, '3170': 1275,
  19272. '3173': 1278, '3174': 1279, '3181': 7622, '3182': 7623, '3282': 11799,
  19273. '3316': 578, '3379': 42785, '3393': 1159, '3416': 8377
  19274. };
  19275. // The glyph map for ArialBlack differs slightly from the glyph map used for
  19276. // other well-known standard fonts. Hence we use this (incomplete) CID to GID
  19277. // mapping to adjust the glyph map for non-embedded ArialBlack fonts.
  19278. var SupplementalGlyphMapForArialBlack = {
  19279. '227': 322, '264': 261, '291': 346,
  19280. };
  19281. // Some characters, e.g. copyrightserif, are mapped to the private use area and
  19282. // might not be displayed using standard fonts. Mapping/hacking well-known chars
  19283. // to the similar equivalents in the normal characters range.
  19284. var SpecialPUASymbols = {
  19285. '63721': 0x00A9, // copyrightsans (0xF8E9) => copyright
  19286. '63193': 0x00A9, // copyrightserif (0xF6D9) => copyright
  19287. '63720': 0x00AE, // registersans (0xF8E8) => registered
  19288. '63194': 0x00AE, // registerserif (0xF6DA) => registered
  19289. '63722': 0x2122, // trademarksans (0xF8EA) => trademark
  19290. '63195': 0x2122, // trademarkserif (0xF6DB) => trademark
  19291. '63729': 0x23A7, // bracelefttp (0xF8F1)
  19292. '63730': 0x23A8, // braceleftmid (0xF8F2)
  19293. '63731': 0x23A9, // braceleftbt (0xF8F3)
  19294. '63740': 0x23AB, // bracerighttp (0xF8FC)
  19295. '63741': 0x23AC, // bracerightmid (0xF8FD)
  19296. '63742': 0x23AD, // bracerightbt (0xF8FE)
  19297. '63726': 0x23A1, // bracketlefttp (0xF8EE)
  19298. '63727': 0x23A2, // bracketleftex (0xF8EF)
  19299. '63728': 0x23A3, // bracketleftbt (0xF8F0)
  19300. '63737': 0x23A4, // bracketrighttp (0xF8F9)
  19301. '63738': 0x23A5, // bracketrightex (0xF8FA)
  19302. '63739': 0x23A6, // bracketrightbt (0xF8FB)
  19303. '63723': 0x239B, // parenlefttp (0xF8EB)
  19304. '63724': 0x239C, // parenleftex (0xF8EC)
  19305. '63725': 0x239D, // parenleftbt (0xF8ED)
  19306. '63734': 0x239E, // parenrighttp (0xF8F6)
  19307. '63735': 0x239F, // parenrightex (0xF8F7)
  19308. '63736': 0x23A0, // parenrightbt (0xF8F8)
  19309. };
  19310. function mapSpecialUnicodeValues(code) {
  19311. if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials unicode block.
  19312. return 0;
  19313. } else if (code >= 0xF600 && code <= 0xF8FF) {
  19314. return (SpecialPUASymbols[code] || code);
  19315. }
  19316. return code;
  19317. }
  19318. var UnicodeRanges = [
  19319. { 'begin': 0x0000, 'end': 0x007F }, // Basic Latin
  19320. { 'begin': 0x0080, 'end': 0x00FF }, // Latin-1 Supplement
  19321. { 'begin': 0x0100, 'end': 0x017F }, // Latin Extended-A
  19322. { 'begin': 0x0180, 'end': 0x024F }, // Latin Extended-B
  19323. { 'begin': 0x0250, 'end': 0x02AF }, // IPA Extensions
  19324. { 'begin': 0x02B0, 'end': 0x02FF }, // Spacing Modifier Letters
  19325. { 'begin': 0x0300, 'end': 0x036F }, // Combining Diacritical Marks
  19326. { 'begin': 0x0370, 'end': 0x03FF }, // Greek and Coptic
  19327. { 'begin': 0x2C80, 'end': 0x2CFF }, // Coptic
  19328. { 'begin': 0x0400, 'end': 0x04FF }, // Cyrillic
  19329. { 'begin': 0x0530, 'end': 0x058F }, // Armenian
  19330. { 'begin': 0x0590, 'end': 0x05FF }, // Hebrew
  19331. { 'begin': 0xA500, 'end': 0xA63F }, // Vai
  19332. { 'begin': 0x0600, 'end': 0x06FF }, // Arabic
  19333. { 'begin': 0x07C0, 'end': 0x07FF }, // NKo
  19334. { 'begin': 0x0900, 'end': 0x097F }, // Devanagari
  19335. { 'begin': 0x0980, 'end': 0x09FF }, // Bengali
  19336. { 'begin': 0x0A00, 'end': 0x0A7F }, // Gurmukhi
  19337. { 'begin': 0x0A80, 'end': 0x0AFF }, // Gujarati
  19338. { 'begin': 0x0B00, 'end': 0x0B7F }, // Oriya
  19339. { 'begin': 0x0B80, 'end': 0x0BFF }, // Tamil
  19340. { 'begin': 0x0C00, 'end': 0x0C7F }, // Telugu
  19341. { 'begin': 0x0C80, 'end': 0x0CFF }, // Kannada
  19342. { 'begin': 0x0D00, 'end': 0x0D7F }, // Malayalam
  19343. { 'begin': 0x0E00, 'end': 0x0E7F }, // Thai
  19344. { 'begin': 0x0E80, 'end': 0x0EFF }, // Lao
  19345. { 'begin': 0x10A0, 'end': 0x10FF }, // Georgian
  19346. { 'begin': 0x1B00, 'end': 0x1B7F }, // Balinese
  19347. { 'begin': 0x1100, 'end': 0x11FF }, // Hangul Jamo
  19348. { 'begin': 0x1E00, 'end': 0x1EFF }, // Latin Extended Additional
  19349. { 'begin': 0x1F00, 'end': 0x1FFF }, // Greek Extended
  19350. { 'begin': 0x2000, 'end': 0x206F }, // General Punctuation
  19351. { 'begin': 0x2070, 'end': 0x209F }, // Superscripts And Subscripts
  19352. { 'begin': 0x20A0, 'end': 0x20CF }, // Currency Symbol
  19353. { 'begin': 0x20D0, 'end': 0x20FF }, // Combining Diacritical Marks For Symbols
  19354. { 'begin': 0x2100, 'end': 0x214F }, // Letterlike Symbols
  19355. { 'begin': 0x2150, 'end': 0x218F }, // Number Forms
  19356. { 'begin': 0x2190, 'end': 0x21FF }, // Arrows
  19357. { 'begin': 0x2200, 'end': 0x22FF }, // Mathematical Operators
  19358. { 'begin': 0x2300, 'end': 0x23FF }, // Miscellaneous Technical
  19359. { 'begin': 0x2400, 'end': 0x243F }, // Control Pictures
  19360. { 'begin': 0x2440, 'end': 0x245F }, // Optical Character Recognition
  19361. { 'begin': 0x2460, 'end': 0x24FF }, // Enclosed Alphanumerics
  19362. { 'begin': 0x2500, 'end': 0x257F }, // Box Drawing
  19363. { 'begin': 0x2580, 'end': 0x259F }, // Block Elements
  19364. { 'begin': 0x25A0, 'end': 0x25FF }, // Geometric Shapes
  19365. { 'begin': 0x2600, 'end': 0x26FF }, // Miscellaneous Symbols
  19366. { 'begin': 0x2700, 'end': 0x27BF }, // Dingbats
  19367. { 'begin': 0x3000, 'end': 0x303F }, // CJK Symbols And Punctuation
  19368. { 'begin': 0x3040, 'end': 0x309F }, // Hiragana
  19369. { 'begin': 0x30A0, 'end': 0x30FF }, // Katakana
  19370. { 'begin': 0x3100, 'end': 0x312F }, // Bopomofo
  19371. { 'begin': 0x3130, 'end': 0x318F }, // Hangul Compatibility Jamo
  19372. { 'begin': 0xA840, 'end': 0xA87F }, // Phags-pa
  19373. { 'begin': 0x3200, 'end': 0x32FF }, // Enclosed CJK Letters And Months
  19374. { 'begin': 0x3300, 'end': 0x33FF }, // CJK Compatibility
  19375. { 'begin': 0xAC00, 'end': 0xD7AF }, // Hangul Syllables
  19376. { 'begin': 0xD800, 'end': 0xDFFF }, // Non-Plane 0 *
  19377. { 'begin': 0x10900, 'end': 0x1091F }, // Phoenicia
  19378. { 'begin': 0x4E00, 'end': 0x9FFF }, // CJK Unified Ideographs
  19379. { 'begin': 0xE000, 'end': 0xF8FF }, // Private Use Area (plane 0)
  19380. { 'begin': 0x31C0, 'end': 0x31EF }, // CJK Strokes
  19381. { 'begin': 0xFB00, 'end': 0xFB4F }, // Alphabetic Presentation Forms
  19382. { 'begin': 0xFB50, 'end': 0xFDFF }, // Arabic Presentation Forms-A
  19383. { 'begin': 0xFE20, 'end': 0xFE2F }, // Combining Half Marks
  19384. { 'begin': 0xFE10, 'end': 0xFE1F }, // Vertical Forms
  19385. { 'begin': 0xFE50, 'end': 0xFE6F }, // Small Form Variants
  19386. { 'begin': 0xFE70, 'end': 0xFEFF }, // Arabic Presentation Forms-B
  19387. { 'begin': 0xFF00, 'end': 0xFFEF }, // Halfwidth And Fullwidth Forms
  19388. { 'begin': 0xFFF0, 'end': 0xFFFF }, // Specials
  19389. { 'begin': 0x0F00, 'end': 0x0FFF }, // Tibetan
  19390. { 'begin': 0x0700, 'end': 0x074F }, // Syriac
  19391. { 'begin': 0x0780, 'end': 0x07BF }, // Thaana
  19392. { 'begin': 0x0D80, 'end': 0x0DFF }, // Sinhala
  19393. { 'begin': 0x1000, 'end': 0x109F }, // Myanmar
  19394. { 'begin': 0x1200, 'end': 0x137F }, // Ethiopic
  19395. { 'begin': 0x13A0, 'end': 0x13FF }, // Cherokee
  19396. { 'begin': 0x1400, 'end': 0x167F }, // Unified Canadian Aboriginal Syllabics
  19397. { 'begin': 0x1680, 'end': 0x169F }, // Ogham
  19398. { 'begin': 0x16A0, 'end': 0x16FF }, // Runic
  19399. { 'begin': 0x1780, 'end': 0x17FF }, // Khmer
  19400. { 'begin': 0x1800, 'end': 0x18AF }, // Mongolian
  19401. { 'begin': 0x2800, 'end': 0x28FF }, // Braille Patterns
  19402. { 'begin': 0xA000, 'end': 0xA48F }, // Yi Syllables
  19403. { 'begin': 0x1700, 'end': 0x171F }, // Tagalog
  19404. { 'begin': 0x10300, 'end': 0x1032F }, // Old Italic
  19405. { 'begin': 0x10330, 'end': 0x1034F }, // Gothic
  19406. { 'begin': 0x10400, 'end': 0x1044F }, // Deseret
  19407. { 'begin': 0x1D000, 'end': 0x1D0FF }, // Byzantine Musical Symbols
  19408. { 'begin': 0x1D400, 'end': 0x1D7FF }, // Mathematical Alphanumeric Symbols
  19409. { 'begin': 0xFF000, 'end': 0xFFFFD }, // Private Use (plane 15)
  19410. { 'begin': 0xFE00, 'end': 0xFE0F }, // Variation Selectors
  19411. { 'begin': 0xE0000, 'end': 0xE007F }, // Tags
  19412. { 'begin': 0x1900, 'end': 0x194F }, // Limbu
  19413. { 'begin': 0x1950, 'end': 0x197F }, // Tai Le
  19414. { 'begin': 0x1980, 'end': 0x19DF }, // New Tai Lue
  19415. { 'begin': 0x1A00, 'end': 0x1A1F }, // Buginese
  19416. { 'begin': 0x2C00, 'end': 0x2C5F }, // Glagolitic
  19417. { 'begin': 0x2D30, 'end': 0x2D7F }, // Tifinagh
  19418. { 'begin': 0x4DC0, 'end': 0x4DFF }, // Yijing Hexagram Symbols
  19419. { 'begin': 0xA800, 'end': 0xA82F }, // Syloti Nagri
  19420. { 'begin': 0x10000, 'end': 0x1007F }, // Linear B Syllabary
  19421. { 'begin': 0x10140, 'end': 0x1018F }, // Ancient Greek Numbers
  19422. { 'begin': 0x10380, 'end': 0x1039F }, // Ugaritic
  19423. { 'begin': 0x103A0, 'end': 0x103DF }, // Old Persian
  19424. { 'begin': 0x10450, 'end': 0x1047F }, // Shavian
  19425. { 'begin': 0x10480, 'end': 0x104AF }, // Osmanya
  19426. { 'begin': 0x10800, 'end': 0x1083F }, // Cypriot Syllabary
  19427. { 'begin': 0x10A00, 'end': 0x10A5F }, // Kharoshthi
  19428. { 'begin': 0x1D300, 'end': 0x1D35F }, // Tai Xuan Jing Symbols
  19429. { 'begin': 0x12000, 'end': 0x123FF }, // Cuneiform
  19430. { 'begin': 0x1D360, 'end': 0x1D37F }, // Counting Rod Numerals
  19431. { 'begin': 0x1B80, 'end': 0x1BBF }, // Sundanese
  19432. { 'begin': 0x1C00, 'end': 0x1C4F }, // Lepcha
  19433. { 'begin': 0x1C50, 'end': 0x1C7F }, // Ol Chiki
  19434. { 'begin': 0xA880, 'end': 0xA8DF }, // Saurashtra
  19435. { 'begin': 0xA900, 'end': 0xA92F }, // Kayah Li
  19436. { 'begin': 0xA930, 'end': 0xA95F }, // Rejang
  19437. { 'begin': 0xAA00, 'end': 0xAA5F }, // Cham
  19438. { 'begin': 0x10190, 'end': 0x101CF }, // Ancient Symbols
  19439. { 'begin': 0x101D0, 'end': 0x101FF }, // Phaistos Disc
  19440. { 'begin': 0x102A0, 'end': 0x102DF }, // Carian
  19441. { 'begin': 0x1F030, 'end': 0x1F09F } // Domino Tiles
  19442. ];
  19443. var MacStandardGlyphOrdering = [
  19444. '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl',
  19445. 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft',
  19446. 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash',
  19447. 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
  19448. 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at',
  19449. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  19450. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft',
  19451. 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b',
  19452. 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
  19453. 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright',
  19454. 'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde',
  19455. 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis',
  19456. 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  19457. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve',
  19458. 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex',
  19459. 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet',
  19460. 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute',
  19461. 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal',
  19462. 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi',
  19463. 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash',
  19464. 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin',
  19465. 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis',
  19466. 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash',
  19467. 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright',
  19468. 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency',
  19469. 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered',
  19470. 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex',
  19471. 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex',
  19472. 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute',
  19473. 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron',
  19474. 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron',
  19475. 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar',
  19476. 'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply',
  19477. 'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter',
  19478. 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla',
  19479. 'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
  19480. function getUnicodeRangeFor(value) {
  19481. for (var i = 0, ii = UnicodeRanges.length; i < ii; i++) {
  19482. var range = UnicodeRanges[i];
  19483. if (value >= range.begin && value < range.end) {
  19484. return i;
  19485. }
  19486. }
  19487. return -1;
  19488. }
  19489. function isRTLRangeFor(value) {
  19490. var range = UnicodeRanges[13];
  19491. if (value >= range.begin && value < range.end) {
  19492. return true;
  19493. }
  19494. range = UnicodeRanges[11];
  19495. if (value >= range.begin && value < range.end) {
  19496. return true;
  19497. }
  19498. return false;
  19499. }
  19500. // The normalization table is obtained by filtering the Unicode characters
  19501. // database with <compat> entries.
  19502. var NormalizedUnicodes = {
  19503. '\u00A8': '\u0020\u0308',
  19504. '\u00AF': '\u0020\u0304',
  19505. '\u00B4': '\u0020\u0301',
  19506. '\u00B5': '\u03BC',
  19507. '\u00B8': '\u0020\u0327',
  19508. '\u0132': '\u0049\u004A',
  19509. '\u0133': '\u0069\u006A',
  19510. '\u013F': '\u004C\u00B7',
  19511. '\u0140': '\u006C\u00B7',
  19512. '\u0149': '\u02BC\u006E',
  19513. '\u017F': '\u0073',
  19514. '\u01C4': '\u0044\u017D',
  19515. '\u01C5': '\u0044\u017E',
  19516. '\u01C6': '\u0064\u017E',
  19517. '\u01C7': '\u004C\u004A',
  19518. '\u01C8': '\u004C\u006A',
  19519. '\u01C9': '\u006C\u006A',
  19520. '\u01CA': '\u004E\u004A',
  19521. '\u01CB': '\u004E\u006A',
  19522. '\u01CC': '\u006E\u006A',
  19523. '\u01F1': '\u0044\u005A',
  19524. '\u01F2': '\u0044\u007A',
  19525. '\u01F3': '\u0064\u007A',
  19526. '\u02D8': '\u0020\u0306',
  19527. '\u02D9': '\u0020\u0307',
  19528. '\u02DA': '\u0020\u030A',
  19529. '\u02DB': '\u0020\u0328',
  19530. '\u02DC': '\u0020\u0303',
  19531. '\u02DD': '\u0020\u030B',
  19532. '\u037A': '\u0020\u0345',
  19533. '\u0384': '\u0020\u0301',
  19534. '\u03D0': '\u03B2',
  19535. '\u03D1': '\u03B8',
  19536. '\u03D2': '\u03A5',
  19537. '\u03D5': '\u03C6',
  19538. '\u03D6': '\u03C0',
  19539. '\u03F0': '\u03BA',
  19540. '\u03F1': '\u03C1',
  19541. '\u03F2': '\u03C2',
  19542. '\u03F4': '\u0398',
  19543. '\u03F5': '\u03B5',
  19544. '\u03F9': '\u03A3',
  19545. '\u0587': '\u0565\u0582',
  19546. '\u0675': '\u0627\u0674',
  19547. '\u0676': '\u0648\u0674',
  19548. '\u0677': '\u06C7\u0674',
  19549. '\u0678': '\u064A\u0674',
  19550. '\u0E33': '\u0E4D\u0E32',
  19551. '\u0EB3': '\u0ECD\u0EB2',
  19552. '\u0EDC': '\u0EAB\u0E99',
  19553. '\u0EDD': '\u0EAB\u0EA1',
  19554. '\u0F77': '\u0FB2\u0F81',
  19555. '\u0F79': '\u0FB3\u0F81',
  19556. '\u1E9A': '\u0061\u02BE',
  19557. '\u1FBD': '\u0020\u0313',
  19558. '\u1FBF': '\u0020\u0313',
  19559. '\u1FC0': '\u0020\u0342',
  19560. '\u1FFE': '\u0020\u0314',
  19561. '\u2002': '\u0020',
  19562. '\u2003': '\u0020',
  19563. '\u2004': '\u0020',
  19564. '\u2005': '\u0020',
  19565. '\u2006': '\u0020',
  19566. '\u2008': '\u0020',
  19567. '\u2009': '\u0020',
  19568. '\u200A': '\u0020',
  19569. '\u2017': '\u0020\u0333',
  19570. '\u2024': '\u002E',
  19571. '\u2025': '\u002E\u002E',
  19572. '\u2026': '\u002E\u002E\u002E',
  19573. '\u2033': '\u2032\u2032',
  19574. '\u2034': '\u2032\u2032\u2032',
  19575. '\u2036': '\u2035\u2035',
  19576. '\u2037': '\u2035\u2035\u2035',
  19577. '\u203C': '\u0021\u0021',
  19578. '\u203E': '\u0020\u0305',
  19579. '\u2047': '\u003F\u003F',
  19580. '\u2048': '\u003F\u0021',
  19581. '\u2049': '\u0021\u003F',
  19582. '\u2057': '\u2032\u2032\u2032\u2032',
  19583. '\u205F': '\u0020',
  19584. '\u20A8': '\u0052\u0073',
  19585. '\u2100': '\u0061\u002F\u0063',
  19586. '\u2101': '\u0061\u002F\u0073',
  19587. '\u2103': '\u00B0\u0043',
  19588. '\u2105': '\u0063\u002F\u006F',
  19589. '\u2106': '\u0063\u002F\u0075',
  19590. '\u2107': '\u0190',
  19591. '\u2109': '\u00B0\u0046',
  19592. '\u2116': '\u004E\u006F',
  19593. '\u2121': '\u0054\u0045\u004C',
  19594. '\u2135': '\u05D0',
  19595. '\u2136': '\u05D1',
  19596. '\u2137': '\u05D2',
  19597. '\u2138': '\u05D3',
  19598. '\u213B': '\u0046\u0041\u0058',
  19599. '\u2160': '\u0049',
  19600. '\u2161': '\u0049\u0049',
  19601. '\u2162': '\u0049\u0049\u0049',
  19602. '\u2163': '\u0049\u0056',
  19603. '\u2164': '\u0056',
  19604. '\u2165': '\u0056\u0049',
  19605. '\u2166': '\u0056\u0049\u0049',
  19606. '\u2167': '\u0056\u0049\u0049\u0049',
  19607. '\u2168': '\u0049\u0058',
  19608. '\u2169': '\u0058',
  19609. '\u216A': '\u0058\u0049',
  19610. '\u216B': '\u0058\u0049\u0049',
  19611. '\u216C': '\u004C',
  19612. '\u216D': '\u0043',
  19613. '\u216E': '\u0044',
  19614. '\u216F': '\u004D',
  19615. '\u2170': '\u0069',
  19616. '\u2171': '\u0069\u0069',
  19617. '\u2172': '\u0069\u0069\u0069',
  19618. '\u2173': '\u0069\u0076',
  19619. '\u2174': '\u0076',
  19620. '\u2175': '\u0076\u0069',
  19621. '\u2176': '\u0076\u0069\u0069',
  19622. '\u2177': '\u0076\u0069\u0069\u0069',
  19623. '\u2178': '\u0069\u0078',
  19624. '\u2179': '\u0078',
  19625. '\u217A': '\u0078\u0069',
  19626. '\u217B': '\u0078\u0069\u0069',
  19627. '\u217C': '\u006C',
  19628. '\u217D': '\u0063',
  19629. '\u217E': '\u0064',
  19630. '\u217F': '\u006D',
  19631. '\u222C': '\u222B\u222B',
  19632. '\u222D': '\u222B\u222B\u222B',
  19633. '\u222F': '\u222E\u222E',
  19634. '\u2230': '\u222E\u222E\u222E',
  19635. '\u2474': '\u0028\u0031\u0029',
  19636. '\u2475': '\u0028\u0032\u0029',
  19637. '\u2476': '\u0028\u0033\u0029',
  19638. '\u2477': '\u0028\u0034\u0029',
  19639. '\u2478': '\u0028\u0035\u0029',
  19640. '\u2479': '\u0028\u0036\u0029',
  19641. '\u247A': '\u0028\u0037\u0029',
  19642. '\u247B': '\u0028\u0038\u0029',
  19643. '\u247C': '\u0028\u0039\u0029',
  19644. '\u247D': '\u0028\u0031\u0030\u0029',
  19645. '\u247E': '\u0028\u0031\u0031\u0029',
  19646. '\u247F': '\u0028\u0031\u0032\u0029',
  19647. '\u2480': '\u0028\u0031\u0033\u0029',
  19648. '\u2481': '\u0028\u0031\u0034\u0029',
  19649. '\u2482': '\u0028\u0031\u0035\u0029',
  19650. '\u2483': '\u0028\u0031\u0036\u0029',
  19651. '\u2484': '\u0028\u0031\u0037\u0029',
  19652. '\u2485': '\u0028\u0031\u0038\u0029',
  19653. '\u2486': '\u0028\u0031\u0039\u0029',
  19654. '\u2487': '\u0028\u0032\u0030\u0029',
  19655. '\u2488': '\u0031\u002E',
  19656. '\u2489': '\u0032\u002E',
  19657. '\u248A': '\u0033\u002E',
  19658. '\u248B': '\u0034\u002E',
  19659. '\u248C': '\u0035\u002E',
  19660. '\u248D': '\u0036\u002E',
  19661. '\u248E': '\u0037\u002E',
  19662. '\u248F': '\u0038\u002E',
  19663. '\u2490': '\u0039\u002E',
  19664. '\u2491': '\u0031\u0030\u002E',
  19665. '\u2492': '\u0031\u0031\u002E',
  19666. '\u2493': '\u0031\u0032\u002E',
  19667. '\u2494': '\u0031\u0033\u002E',
  19668. '\u2495': '\u0031\u0034\u002E',
  19669. '\u2496': '\u0031\u0035\u002E',
  19670. '\u2497': '\u0031\u0036\u002E',
  19671. '\u2498': '\u0031\u0037\u002E',
  19672. '\u2499': '\u0031\u0038\u002E',
  19673. '\u249A': '\u0031\u0039\u002E',
  19674. '\u249B': '\u0032\u0030\u002E',
  19675. '\u249C': '\u0028\u0061\u0029',
  19676. '\u249D': '\u0028\u0062\u0029',
  19677. '\u249E': '\u0028\u0063\u0029',
  19678. '\u249F': '\u0028\u0064\u0029',
  19679. '\u24A0': '\u0028\u0065\u0029',
  19680. '\u24A1': '\u0028\u0066\u0029',
  19681. '\u24A2': '\u0028\u0067\u0029',
  19682. '\u24A3': '\u0028\u0068\u0029',
  19683. '\u24A4': '\u0028\u0069\u0029',
  19684. '\u24A5': '\u0028\u006A\u0029',
  19685. '\u24A6': '\u0028\u006B\u0029',
  19686. '\u24A7': '\u0028\u006C\u0029',
  19687. '\u24A8': '\u0028\u006D\u0029',
  19688. '\u24A9': '\u0028\u006E\u0029',
  19689. '\u24AA': '\u0028\u006F\u0029',
  19690. '\u24AB': '\u0028\u0070\u0029',
  19691. '\u24AC': '\u0028\u0071\u0029',
  19692. '\u24AD': '\u0028\u0072\u0029',
  19693. '\u24AE': '\u0028\u0073\u0029',
  19694. '\u24AF': '\u0028\u0074\u0029',
  19695. '\u24B0': '\u0028\u0075\u0029',
  19696. '\u24B1': '\u0028\u0076\u0029',
  19697. '\u24B2': '\u0028\u0077\u0029',
  19698. '\u24B3': '\u0028\u0078\u0029',
  19699. '\u24B4': '\u0028\u0079\u0029',
  19700. '\u24B5': '\u0028\u007A\u0029',
  19701. '\u2A0C': '\u222B\u222B\u222B\u222B',
  19702. '\u2A74': '\u003A\u003A\u003D',
  19703. '\u2A75': '\u003D\u003D',
  19704. '\u2A76': '\u003D\u003D\u003D',
  19705. '\u2E9F': '\u6BCD',
  19706. '\u2EF3': '\u9F9F',
  19707. '\u2F00': '\u4E00',
  19708. '\u2F01': '\u4E28',
  19709. '\u2F02': '\u4E36',
  19710. '\u2F03': '\u4E3F',
  19711. '\u2F04': '\u4E59',
  19712. '\u2F05': '\u4E85',
  19713. '\u2F06': '\u4E8C',
  19714. '\u2F07': '\u4EA0',
  19715. '\u2F08': '\u4EBA',
  19716. '\u2F09': '\u513F',
  19717. '\u2F0A': '\u5165',
  19718. '\u2F0B': '\u516B',
  19719. '\u2F0C': '\u5182',
  19720. '\u2F0D': '\u5196',
  19721. '\u2F0E': '\u51AB',
  19722. '\u2F0F': '\u51E0',
  19723. '\u2F10': '\u51F5',
  19724. '\u2F11': '\u5200',
  19725. '\u2F12': '\u529B',
  19726. '\u2F13': '\u52F9',
  19727. '\u2F14': '\u5315',
  19728. '\u2F15': '\u531A',
  19729. '\u2F16': '\u5338',
  19730. '\u2F17': '\u5341',
  19731. '\u2F18': '\u535C',
  19732. '\u2F19': '\u5369',
  19733. '\u2F1A': '\u5382',
  19734. '\u2F1B': '\u53B6',
  19735. '\u2F1C': '\u53C8',
  19736. '\u2F1D': '\u53E3',
  19737. '\u2F1E': '\u56D7',
  19738. '\u2F1F': '\u571F',
  19739. '\u2F20': '\u58EB',
  19740. '\u2F21': '\u5902',
  19741. '\u2F22': '\u590A',
  19742. '\u2F23': '\u5915',
  19743. '\u2F24': '\u5927',
  19744. '\u2F25': '\u5973',
  19745. '\u2F26': '\u5B50',
  19746. '\u2F27': '\u5B80',
  19747. '\u2F28': '\u5BF8',
  19748. '\u2F29': '\u5C0F',
  19749. '\u2F2A': '\u5C22',
  19750. '\u2F2B': '\u5C38',
  19751. '\u2F2C': '\u5C6E',
  19752. '\u2F2D': '\u5C71',
  19753. '\u2F2E': '\u5DDB',
  19754. '\u2F2F': '\u5DE5',
  19755. '\u2F30': '\u5DF1',
  19756. '\u2F31': '\u5DFE',
  19757. '\u2F32': '\u5E72',
  19758. '\u2F33': '\u5E7A',
  19759. '\u2F34': '\u5E7F',
  19760. '\u2F35': '\u5EF4',
  19761. '\u2F36': '\u5EFE',
  19762. '\u2F37': '\u5F0B',
  19763. '\u2F38': '\u5F13',
  19764. '\u2F39': '\u5F50',
  19765. '\u2F3A': '\u5F61',
  19766. '\u2F3B': '\u5F73',
  19767. '\u2F3C': '\u5FC3',
  19768. '\u2F3D': '\u6208',
  19769. '\u2F3E': '\u6236',
  19770. '\u2F3F': '\u624B',
  19771. '\u2F40': '\u652F',
  19772. '\u2F41': '\u6534',
  19773. '\u2F42': '\u6587',
  19774. '\u2F43': '\u6597',
  19775. '\u2F44': '\u65A4',
  19776. '\u2F45': '\u65B9',
  19777. '\u2F46': '\u65E0',
  19778. '\u2F47': '\u65E5',
  19779. '\u2F48': '\u66F0',
  19780. '\u2F49': '\u6708',
  19781. '\u2F4A': '\u6728',
  19782. '\u2F4B': '\u6B20',
  19783. '\u2F4C': '\u6B62',
  19784. '\u2F4D': '\u6B79',
  19785. '\u2F4E': '\u6BB3',
  19786. '\u2F4F': '\u6BCB',
  19787. '\u2F50': '\u6BD4',
  19788. '\u2F51': '\u6BDB',
  19789. '\u2F52': '\u6C0F',
  19790. '\u2F53': '\u6C14',
  19791. '\u2F54': '\u6C34',
  19792. '\u2F55': '\u706B',
  19793. '\u2F56': '\u722A',
  19794. '\u2F57': '\u7236',
  19795. '\u2F58': '\u723B',
  19796. '\u2F59': '\u723F',
  19797. '\u2F5A': '\u7247',
  19798. '\u2F5B': '\u7259',
  19799. '\u2F5C': '\u725B',
  19800. '\u2F5D': '\u72AC',
  19801. '\u2F5E': '\u7384',
  19802. '\u2F5F': '\u7389',
  19803. '\u2F60': '\u74DC',
  19804. '\u2F61': '\u74E6',
  19805. '\u2F62': '\u7518',
  19806. '\u2F63': '\u751F',
  19807. '\u2F64': '\u7528',
  19808. '\u2F65': '\u7530',
  19809. '\u2F66': '\u758B',
  19810. '\u2F67': '\u7592',
  19811. '\u2F68': '\u7676',
  19812. '\u2F69': '\u767D',
  19813. '\u2F6A': '\u76AE',
  19814. '\u2F6B': '\u76BF',
  19815. '\u2F6C': '\u76EE',
  19816. '\u2F6D': '\u77DB',
  19817. '\u2F6E': '\u77E2',
  19818. '\u2F6F': '\u77F3',
  19819. '\u2F70': '\u793A',
  19820. '\u2F71': '\u79B8',
  19821. '\u2F72': '\u79BE',
  19822. '\u2F73': '\u7A74',
  19823. '\u2F74': '\u7ACB',
  19824. '\u2F75': '\u7AF9',
  19825. '\u2F76': '\u7C73',
  19826. '\u2F77': '\u7CF8',
  19827. '\u2F78': '\u7F36',
  19828. '\u2F79': '\u7F51',
  19829. '\u2F7A': '\u7F8A',
  19830. '\u2F7B': '\u7FBD',
  19831. '\u2F7C': '\u8001',
  19832. '\u2F7D': '\u800C',
  19833. '\u2F7E': '\u8012',
  19834. '\u2F7F': '\u8033',
  19835. '\u2F80': '\u807F',
  19836. '\u2F81': '\u8089',
  19837. '\u2F82': '\u81E3',
  19838. '\u2F83': '\u81EA',
  19839. '\u2F84': '\u81F3',
  19840. '\u2F85': '\u81FC',
  19841. '\u2F86': '\u820C',
  19842. '\u2F87': '\u821B',
  19843. '\u2F88': '\u821F',
  19844. '\u2F89': '\u826E',
  19845. '\u2F8A': '\u8272',
  19846. '\u2F8B': '\u8278',
  19847. '\u2F8C': '\u864D',
  19848. '\u2F8D': '\u866B',
  19849. '\u2F8E': '\u8840',
  19850. '\u2F8F': '\u884C',
  19851. '\u2F90': '\u8863',
  19852. '\u2F91': '\u897E',
  19853. '\u2F92': '\u898B',
  19854. '\u2F93': '\u89D2',
  19855. '\u2F94': '\u8A00',
  19856. '\u2F95': '\u8C37',
  19857. '\u2F96': '\u8C46',
  19858. '\u2F97': '\u8C55',
  19859. '\u2F98': '\u8C78',
  19860. '\u2F99': '\u8C9D',
  19861. '\u2F9A': '\u8D64',
  19862. '\u2F9B': '\u8D70',
  19863. '\u2F9C': '\u8DB3',
  19864. '\u2F9D': '\u8EAB',
  19865. '\u2F9E': '\u8ECA',
  19866. '\u2F9F': '\u8F9B',
  19867. '\u2FA0': '\u8FB0',
  19868. '\u2FA1': '\u8FB5',
  19869. '\u2FA2': '\u9091',
  19870. '\u2FA3': '\u9149',
  19871. '\u2FA4': '\u91C6',
  19872. '\u2FA5': '\u91CC',
  19873. '\u2FA6': '\u91D1',
  19874. '\u2FA7': '\u9577',
  19875. '\u2FA8': '\u9580',
  19876. '\u2FA9': '\u961C',
  19877. '\u2FAA': '\u96B6',
  19878. '\u2FAB': '\u96B9',
  19879. '\u2FAC': '\u96E8',
  19880. '\u2FAD': '\u9751',
  19881. '\u2FAE': '\u975E',
  19882. '\u2FAF': '\u9762',
  19883. '\u2FB0': '\u9769',
  19884. '\u2FB1': '\u97CB',
  19885. '\u2FB2': '\u97ED',
  19886. '\u2FB3': '\u97F3',
  19887. '\u2FB4': '\u9801',
  19888. '\u2FB5': '\u98A8',
  19889. '\u2FB6': '\u98DB',
  19890. '\u2FB7': '\u98DF',
  19891. '\u2FB8': '\u9996',
  19892. '\u2FB9': '\u9999',
  19893. '\u2FBA': '\u99AC',
  19894. '\u2FBB': '\u9AA8',
  19895. '\u2FBC': '\u9AD8',
  19896. '\u2FBD': '\u9ADF',
  19897. '\u2FBE': '\u9B25',
  19898. '\u2FBF': '\u9B2F',
  19899. '\u2FC0': '\u9B32',
  19900. '\u2FC1': '\u9B3C',
  19901. '\u2FC2': '\u9B5A',
  19902. '\u2FC3': '\u9CE5',
  19903. '\u2FC4': '\u9E75',
  19904. '\u2FC5': '\u9E7F',
  19905. '\u2FC6': '\u9EA5',
  19906. '\u2FC7': '\u9EBB',
  19907. '\u2FC8': '\u9EC3',
  19908. '\u2FC9': '\u9ECD',
  19909. '\u2FCA': '\u9ED1',
  19910. '\u2FCB': '\u9EF9',
  19911. '\u2FCC': '\u9EFD',
  19912. '\u2FCD': '\u9F0E',
  19913. '\u2FCE': '\u9F13',
  19914. '\u2FCF': '\u9F20',
  19915. '\u2FD0': '\u9F3B',
  19916. '\u2FD1': '\u9F4A',
  19917. '\u2FD2': '\u9F52',
  19918. '\u2FD3': '\u9F8D',
  19919. '\u2FD4': '\u9F9C',
  19920. '\u2FD5': '\u9FA0',
  19921. '\u3036': '\u3012',
  19922. '\u3038': '\u5341',
  19923. '\u3039': '\u5344',
  19924. '\u303A': '\u5345',
  19925. '\u309B': '\u0020\u3099',
  19926. '\u309C': '\u0020\u309A',
  19927. '\u3131': '\u1100',
  19928. '\u3132': '\u1101',
  19929. '\u3133': '\u11AA',
  19930. '\u3134': '\u1102',
  19931. '\u3135': '\u11AC',
  19932. '\u3136': '\u11AD',
  19933. '\u3137': '\u1103',
  19934. '\u3138': '\u1104',
  19935. '\u3139': '\u1105',
  19936. '\u313A': '\u11B0',
  19937. '\u313B': '\u11B1',
  19938. '\u313C': '\u11B2',
  19939. '\u313D': '\u11B3',
  19940. '\u313E': '\u11B4',
  19941. '\u313F': '\u11B5',
  19942. '\u3140': '\u111A',
  19943. '\u3141': '\u1106',
  19944. '\u3142': '\u1107',
  19945. '\u3143': '\u1108',
  19946. '\u3144': '\u1121',
  19947. '\u3145': '\u1109',
  19948. '\u3146': '\u110A',
  19949. '\u3147': '\u110B',
  19950. '\u3148': '\u110C',
  19951. '\u3149': '\u110D',
  19952. '\u314A': '\u110E',
  19953. '\u314B': '\u110F',
  19954. '\u314C': '\u1110',
  19955. '\u314D': '\u1111',
  19956. '\u314E': '\u1112',
  19957. '\u314F': '\u1161',
  19958. '\u3150': '\u1162',
  19959. '\u3151': '\u1163',
  19960. '\u3152': '\u1164',
  19961. '\u3153': '\u1165',
  19962. '\u3154': '\u1166',
  19963. '\u3155': '\u1167',
  19964. '\u3156': '\u1168',
  19965. '\u3157': '\u1169',
  19966. '\u3158': '\u116A',
  19967. '\u3159': '\u116B',
  19968. '\u315A': '\u116C',
  19969. '\u315B': '\u116D',
  19970. '\u315C': '\u116E',
  19971. '\u315D': '\u116F',
  19972. '\u315E': '\u1170',
  19973. '\u315F': '\u1171',
  19974. '\u3160': '\u1172',
  19975. '\u3161': '\u1173',
  19976. '\u3162': '\u1174',
  19977. '\u3163': '\u1175',
  19978. '\u3164': '\u1160',
  19979. '\u3165': '\u1114',
  19980. '\u3166': '\u1115',
  19981. '\u3167': '\u11C7',
  19982. '\u3168': '\u11C8',
  19983. '\u3169': '\u11CC',
  19984. '\u316A': '\u11CE',
  19985. '\u316B': '\u11D3',
  19986. '\u316C': '\u11D7',
  19987. '\u316D': '\u11D9',
  19988. '\u316E': '\u111C',
  19989. '\u316F': '\u11DD',
  19990. '\u3170': '\u11DF',
  19991. '\u3171': '\u111D',
  19992. '\u3172': '\u111E',
  19993. '\u3173': '\u1120',
  19994. '\u3174': '\u1122',
  19995. '\u3175': '\u1123',
  19996. '\u3176': '\u1127',
  19997. '\u3177': '\u1129',
  19998. '\u3178': '\u112B',
  19999. '\u3179': '\u112C',
  20000. '\u317A': '\u112D',
  20001. '\u317B': '\u112E',
  20002. '\u317C': '\u112F',
  20003. '\u317D': '\u1132',
  20004. '\u317E': '\u1136',
  20005. '\u317F': '\u1140',
  20006. '\u3180': '\u1147',
  20007. '\u3181': '\u114C',
  20008. '\u3182': '\u11F1',
  20009. '\u3183': '\u11F2',
  20010. '\u3184': '\u1157',
  20011. '\u3185': '\u1158',
  20012. '\u3186': '\u1159',
  20013. '\u3187': '\u1184',
  20014. '\u3188': '\u1185',
  20015. '\u3189': '\u1188',
  20016. '\u318A': '\u1191',
  20017. '\u318B': '\u1192',
  20018. '\u318C': '\u1194',
  20019. '\u318D': '\u119E',
  20020. '\u318E': '\u11A1',
  20021. '\u3200': '\u0028\u1100\u0029',
  20022. '\u3201': '\u0028\u1102\u0029',
  20023. '\u3202': '\u0028\u1103\u0029',
  20024. '\u3203': '\u0028\u1105\u0029',
  20025. '\u3204': '\u0028\u1106\u0029',
  20026. '\u3205': '\u0028\u1107\u0029',
  20027. '\u3206': '\u0028\u1109\u0029',
  20028. '\u3207': '\u0028\u110B\u0029',
  20029. '\u3208': '\u0028\u110C\u0029',
  20030. '\u3209': '\u0028\u110E\u0029',
  20031. '\u320A': '\u0028\u110F\u0029',
  20032. '\u320B': '\u0028\u1110\u0029',
  20033. '\u320C': '\u0028\u1111\u0029',
  20034. '\u320D': '\u0028\u1112\u0029',
  20035. '\u320E': '\u0028\u1100\u1161\u0029',
  20036. '\u320F': '\u0028\u1102\u1161\u0029',
  20037. '\u3210': '\u0028\u1103\u1161\u0029',
  20038. '\u3211': '\u0028\u1105\u1161\u0029',
  20039. '\u3212': '\u0028\u1106\u1161\u0029',
  20040. '\u3213': '\u0028\u1107\u1161\u0029',
  20041. '\u3214': '\u0028\u1109\u1161\u0029',
  20042. '\u3215': '\u0028\u110B\u1161\u0029',
  20043. '\u3216': '\u0028\u110C\u1161\u0029',
  20044. '\u3217': '\u0028\u110E\u1161\u0029',
  20045. '\u3218': '\u0028\u110F\u1161\u0029',
  20046. '\u3219': '\u0028\u1110\u1161\u0029',
  20047. '\u321A': '\u0028\u1111\u1161\u0029',
  20048. '\u321B': '\u0028\u1112\u1161\u0029',
  20049. '\u321C': '\u0028\u110C\u116E\u0029',
  20050. '\u321D': '\u0028\u110B\u1169\u110C\u1165\u11AB\u0029',
  20051. '\u321E': '\u0028\u110B\u1169\u1112\u116E\u0029',
  20052. '\u3220': '\u0028\u4E00\u0029',
  20053. '\u3221': '\u0028\u4E8C\u0029',
  20054. '\u3222': '\u0028\u4E09\u0029',
  20055. '\u3223': '\u0028\u56DB\u0029',
  20056. '\u3224': '\u0028\u4E94\u0029',
  20057. '\u3225': '\u0028\u516D\u0029',
  20058. '\u3226': '\u0028\u4E03\u0029',
  20059. '\u3227': '\u0028\u516B\u0029',
  20060. '\u3228': '\u0028\u4E5D\u0029',
  20061. '\u3229': '\u0028\u5341\u0029',
  20062. '\u322A': '\u0028\u6708\u0029',
  20063. '\u322B': '\u0028\u706B\u0029',
  20064. '\u322C': '\u0028\u6C34\u0029',
  20065. '\u322D': '\u0028\u6728\u0029',
  20066. '\u322E': '\u0028\u91D1\u0029',
  20067. '\u322F': '\u0028\u571F\u0029',
  20068. '\u3230': '\u0028\u65E5\u0029',
  20069. '\u3231': '\u0028\u682A\u0029',
  20070. '\u3232': '\u0028\u6709\u0029',
  20071. '\u3233': '\u0028\u793E\u0029',
  20072. '\u3234': '\u0028\u540D\u0029',
  20073. '\u3235': '\u0028\u7279\u0029',
  20074. '\u3236': '\u0028\u8CA1\u0029',
  20075. '\u3237': '\u0028\u795D\u0029',
  20076. '\u3238': '\u0028\u52B4\u0029',
  20077. '\u3239': '\u0028\u4EE3\u0029',
  20078. '\u323A': '\u0028\u547C\u0029',
  20079. '\u323B': '\u0028\u5B66\u0029',
  20080. '\u323C': '\u0028\u76E3\u0029',
  20081. '\u323D': '\u0028\u4F01\u0029',
  20082. '\u323E': '\u0028\u8CC7\u0029',
  20083. '\u323F': '\u0028\u5354\u0029',
  20084. '\u3240': '\u0028\u796D\u0029',
  20085. '\u3241': '\u0028\u4F11\u0029',
  20086. '\u3242': '\u0028\u81EA\u0029',
  20087. '\u3243': '\u0028\u81F3\u0029',
  20088. '\u32C0': '\u0031\u6708',
  20089. '\u32C1': '\u0032\u6708',
  20090. '\u32C2': '\u0033\u6708',
  20091. '\u32C3': '\u0034\u6708',
  20092. '\u32C4': '\u0035\u6708',
  20093. '\u32C5': '\u0036\u6708',
  20094. '\u32C6': '\u0037\u6708',
  20095. '\u32C7': '\u0038\u6708',
  20096. '\u32C8': '\u0039\u6708',
  20097. '\u32C9': '\u0031\u0030\u6708',
  20098. '\u32CA': '\u0031\u0031\u6708',
  20099. '\u32CB': '\u0031\u0032\u6708',
  20100. '\u3358': '\u0030\u70B9',
  20101. '\u3359': '\u0031\u70B9',
  20102. '\u335A': '\u0032\u70B9',
  20103. '\u335B': '\u0033\u70B9',
  20104. '\u335C': '\u0034\u70B9',
  20105. '\u335D': '\u0035\u70B9',
  20106. '\u335E': '\u0036\u70B9',
  20107. '\u335F': '\u0037\u70B9',
  20108. '\u3360': '\u0038\u70B9',
  20109. '\u3361': '\u0039\u70B9',
  20110. '\u3362': '\u0031\u0030\u70B9',
  20111. '\u3363': '\u0031\u0031\u70B9',
  20112. '\u3364': '\u0031\u0032\u70B9',
  20113. '\u3365': '\u0031\u0033\u70B9',
  20114. '\u3366': '\u0031\u0034\u70B9',
  20115. '\u3367': '\u0031\u0035\u70B9',
  20116. '\u3368': '\u0031\u0036\u70B9',
  20117. '\u3369': '\u0031\u0037\u70B9',
  20118. '\u336A': '\u0031\u0038\u70B9',
  20119. '\u336B': '\u0031\u0039\u70B9',
  20120. '\u336C': '\u0032\u0030\u70B9',
  20121. '\u336D': '\u0032\u0031\u70B9',
  20122. '\u336E': '\u0032\u0032\u70B9',
  20123. '\u336F': '\u0032\u0033\u70B9',
  20124. '\u3370': '\u0032\u0034\u70B9',
  20125. '\u33E0': '\u0031\u65E5',
  20126. '\u33E1': '\u0032\u65E5',
  20127. '\u33E2': '\u0033\u65E5',
  20128. '\u33E3': '\u0034\u65E5',
  20129. '\u33E4': '\u0035\u65E5',
  20130. '\u33E5': '\u0036\u65E5',
  20131. '\u33E6': '\u0037\u65E5',
  20132. '\u33E7': '\u0038\u65E5',
  20133. '\u33E8': '\u0039\u65E5',
  20134. '\u33E9': '\u0031\u0030\u65E5',
  20135. '\u33EA': '\u0031\u0031\u65E5',
  20136. '\u33EB': '\u0031\u0032\u65E5',
  20137. '\u33EC': '\u0031\u0033\u65E5',
  20138. '\u33ED': '\u0031\u0034\u65E5',
  20139. '\u33EE': '\u0031\u0035\u65E5',
  20140. '\u33EF': '\u0031\u0036\u65E5',
  20141. '\u33F0': '\u0031\u0037\u65E5',
  20142. '\u33F1': '\u0031\u0038\u65E5',
  20143. '\u33F2': '\u0031\u0039\u65E5',
  20144. '\u33F3': '\u0032\u0030\u65E5',
  20145. '\u33F4': '\u0032\u0031\u65E5',
  20146. '\u33F5': '\u0032\u0032\u65E5',
  20147. '\u33F6': '\u0032\u0033\u65E5',
  20148. '\u33F7': '\u0032\u0034\u65E5',
  20149. '\u33F8': '\u0032\u0035\u65E5',
  20150. '\u33F9': '\u0032\u0036\u65E5',
  20151. '\u33FA': '\u0032\u0037\u65E5',
  20152. '\u33FB': '\u0032\u0038\u65E5',
  20153. '\u33FC': '\u0032\u0039\u65E5',
  20154. '\u33FD': '\u0033\u0030\u65E5',
  20155. '\u33FE': '\u0033\u0031\u65E5',
  20156. '\uFB00': '\u0066\u0066',
  20157. '\uFB01': '\u0066\u0069',
  20158. '\uFB02': '\u0066\u006C',
  20159. '\uFB03': '\u0066\u0066\u0069',
  20160. '\uFB04': '\u0066\u0066\u006C',
  20161. '\uFB05': '\u017F\u0074',
  20162. '\uFB06': '\u0073\u0074',
  20163. '\uFB13': '\u0574\u0576',
  20164. '\uFB14': '\u0574\u0565',
  20165. '\uFB15': '\u0574\u056B',
  20166. '\uFB16': '\u057E\u0576',
  20167. '\uFB17': '\u0574\u056D',
  20168. '\uFB4F': '\u05D0\u05DC',
  20169. '\uFB50': '\u0671',
  20170. '\uFB51': '\u0671',
  20171. '\uFB52': '\u067B',
  20172. '\uFB53': '\u067B',
  20173. '\uFB54': '\u067B',
  20174. '\uFB55': '\u067B',
  20175. '\uFB56': '\u067E',
  20176. '\uFB57': '\u067E',
  20177. '\uFB58': '\u067E',
  20178. '\uFB59': '\u067E',
  20179. '\uFB5A': '\u0680',
  20180. '\uFB5B': '\u0680',
  20181. '\uFB5C': '\u0680',
  20182. '\uFB5D': '\u0680',
  20183. '\uFB5E': '\u067A',
  20184. '\uFB5F': '\u067A',
  20185. '\uFB60': '\u067A',
  20186. '\uFB61': '\u067A',
  20187. '\uFB62': '\u067F',
  20188. '\uFB63': '\u067F',
  20189. '\uFB64': '\u067F',
  20190. '\uFB65': '\u067F',
  20191. '\uFB66': '\u0679',
  20192. '\uFB67': '\u0679',
  20193. '\uFB68': '\u0679',
  20194. '\uFB69': '\u0679',
  20195. '\uFB6A': '\u06A4',
  20196. '\uFB6B': '\u06A4',
  20197. '\uFB6C': '\u06A4',
  20198. '\uFB6D': '\u06A4',
  20199. '\uFB6E': '\u06A6',
  20200. '\uFB6F': '\u06A6',
  20201. '\uFB70': '\u06A6',
  20202. '\uFB71': '\u06A6',
  20203. '\uFB72': '\u0684',
  20204. '\uFB73': '\u0684',
  20205. '\uFB74': '\u0684',
  20206. '\uFB75': '\u0684',
  20207. '\uFB76': '\u0683',
  20208. '\uFB77': '\u0683',
  20209. '\uFB78': '\u0683',
  20210. '\uFB79': '\u0683',
  20211. '\uFB7A': '\u0686',
  20212. '\uFB7B': '\u0686',
  20213. '\uFB7C': '\u0686',
  20214. '\uFB7D': '\u0686',
  20215. '\uFB7E': '\u0687',
  20216. '\uFB7F': '\u0687',
  20217. '\uFB80': '\u0687',
  20218. '\uFB81': '\u0687',
  20219. '\uFB82': '\u068D',
  20220. '\uFB83': '\u068D',
  20221. '\uFB84': '\u068C',
  20222. '\uFB85': '\u068C',
  20223. '\uFB86': '\u068E',
  20224. '\uFB87': '\u068E',
  20225. '\uFB88': '\u0688',
  20226. '\uFB89': '\u0688',
  20227. '\uFB8A': '\u0698',
  20228. '\uFB8B': '\u0698',
  20229. '\uFB8C': '\u0691',
  20230. '\uFB8D': '\u0691',
  20231. '\uFB8E': '\u06A9',
  20232. '\uFB8F': '\u06A9',
  20233. '\uFB90': '\u06A9',
  20234. '\uFB91': '\u06A9',
  20235. '\uFB92': '\u06AF',
  20236. '\uFB93': '\u06AF',
  20237. '\uFB94': '\u06AF',
  20238. '\uFB95': '\u06AF',
  20239. '\uFB96': '\u06B3',
  20240. '\uFB97': '\u06B3',
  20241. '\uFB98': '\u06B3',
  20242. '\uFB99': '\u06B3',
  20243. '\uFB9A': '\u06B1',
  20244. '\uFB9B': '\u06B1',
  20245. '\uFB9C': '\u06B1',
  20246. '\uFB9D': '\u06B1',
  20247. '\uFB9E': '\u06BA',
  20248. '\uFB9F': '\u06BA',
  20249. '\uFBA0': '\u06BB',
  20250. '\uFBA1': '\u06BB',
  20251. '\uFBA2': '\u06BB',
  20252. '\uFBA3': '\u06BB',
  20253. '\uFBA4': '\u06C0',
  20254. '\uFBA5': '\u06C0',
  20255. '\uFBA6': '\u06C1',
  20256. '\uFBA7': '\u06C1',
  20257. '\uFBA8': '\u06C1',
  20258. '\uFBA9': '\u06C1',
  20259. '\uFBAA': '\u06BE',
  20260. '\uFBAB': '\u06BE',
  20261. '\uFBAC': '\u06BE',
  20262. '\uFBAD': '\u06BE',
  20263. '\uFBAE': '\u06D2',
  20264. '\uFBAF': '\u06D2',
  20265. '\uFBB0': '\u06D3',
  20266. '\uFBB1': '\u06D3',
  20267. '\uFBD3': '\u06AD',
  20268. '\uFBD4': '\u06AD',
  20269. '\uFBD5': '\u06AD',
  20270. '\uFBD6': '\u06AD',
  20271. '\uFBD7': '\u06C7',
  20272. '\uFBD8': '\u06C7',
  20273. '\uFBD9': '\u06C6',
  20274. '\uFBDA': '\u06C6',
  20275. '\uFBDB': '\u06C8',
  20276. '\uFBDC': '\u06C8',
  20277. '\uFBDD': '\u0677',
  20278. '\uFBDE': '\u06CB',
  20279. '\uFBDF': '\u06CB',
  20280. '\uFBE0': '\u06C5',
  20281. '\uFBE1': '\u06C5',
  20282. '\uFBE2': '\u06C9',
  20283. '\uFBE3': '\u06C9',
  20284. '\uFBE4': '\u06D0',
  20285. '\uFBE5': '\u06D0',
  20286. '\uFBE6': '\u06D0',
  20287. '\uFBE7': '\u06D0',
  20288. '\uFBE8': '\u0649',
  20289. '\uFBE9': '\u0649',
  20290. '\uFBEA': '\u0626\u0627',
  20291. '\uFBEB': '\u0626\u0627',
  20292. '\uFBEC': '\u0626\u06D5',
  20293. '\uFBED': '\u0626\u06D5',
  20294. '\uFBEE': '\u0626\u0648',
  20295. '\uFBEF': '\u0626\u0648',
  20296. '\uFBF0': '\u0626\u06C7',
  20297. '\uFBF1': '\u0626\u06C7',
  20298. '\uFBF2': '\u0626\u06C6',
  20299. '\uFBF3': '\u0626\u06C6',
  20300. '\uFBF4': '\u0626\u06C8',
  20301. '\uFBF5': '\u0626\u06C8',
  20302. '\uFBF6': '\u0626\u06D0',
  20303. '\uFBF7': '\u0626\u06D0',
  20304. '\uFBF8': '\u0626\u06D0',
  20305. '\uFBF9': '\u0626\u0649',
  20306. '\uFBFA': '\u0626\u0649',
  20307. '\uFBFB': '\u0626\u0649',
  20308. '\uFBFC': '\u06CC',
  20309. '\uFBFD': '\u06CC',
  20310. '\uFBFE': '\u06CC',
  20311. '\uFBFF': '\u06CC',
  20312. '\uFC00': '\u0626\u062C',
  20313. '\uFC01': '\u0626\u062D',
  20314. '\uFC02': '\u0626\u0645',
  20315. '\uFC03': '\u0626\u0649',
  20316. '\uFC04': '\u0626\u064A',
  20317. '\uFC05': '\u0628\u062C',
  20318. '\uFC06': '\u0628\u062D',
  20319. '\uFC07': '\u0628\u062E',
  20320. '\uFC08': '\u0628\u0645',
  20321. '\uFC09': '\u0628\u0649',
  20322. '\uFC0A': '\u0628\u064A',
  20323. '\uFC0B': '\u062A\u062C',
  20324. '\uFC0C': '\u062A\u062D',
  20325. '\uFC0D': '\u062A\u062E',
  20326. '\uFC0E': '\u062A\u0645',
  20327. '\uFC0F': '\u062A\u0649',
  20328. '\uFC10': '\u062A\u064A',
  20329. '\uFC11': '\u062B\u062C',
  20330. '\uFC12': '\u062B\u0645',
  20331. '\uFC13': '\u062B\u0649',
  20332. '\uFC14': '\u062B\u064A',
  20333. '\uFC15': '\u062C\u062D',
  20334. '\uFC16': '\u062C\u0645',
  20335. '\uFC17': '\u062D\u062C',
  20336. '\uFC18': '\u062D\u0645',
  20337. '\uFC19': '\u062E\u062C',
  20338. '\uFC1A': '\u062E\u062D',
  20339. '\uFC1B': '\u062E\u0645',
  20340. '\uFC1C': '\u0633\u062C',
  20341. '\uFC1D': '\u0633\u062D',
  20342. '\uFC1E': '\u0633\u062E',
  20343. '\uFC1F': '\u0633\u0645',
  20344. '\uFC20': '\u0635\u062D',
  20345. '\uFC21': '\u0635\u0645',
  20346. '\uFC22': '\u0636\u062C',
  20347. '\uFC23': '\u0636\u062D',
  20348. '\uFC24': '\u0636\u062E',
  20349. '\uFC25': '\u0636\u0645',
  20350. '\uFC26': '\u0637\u062D',
  20351. '\uFC27': '\u0637\u0645',
  20352. '\uFC28': '\u0638\u0645',
  20353. '\uFC29': '\u0639\u062C',
  20354. '\uFC2A': '\u0639\u0645',
  20355. '\uFC2B': '\u063A\u062C',
  20356. '\uFC2C': '\u063A\u0645',
  20357. '\uFC2D': '\u0641\u062C',
  20358. '\uFC2E': '\u0641\u062D',
  20359. '\uFC2F': '\u0641\u062E',
  20360. '\uFC30': '\u0641\u0645',
  20361. '\uFC31': '\u0641\u0649',
  20362. '\uFC32': '\u0641\u064A',
  20363. '\uFC33': '\u0642\u062D',
  20364. '\uFC34': '\u0642\u0645',
  20365. '\uFC35': '\u0642\u0649',
  20366. '\uFC36': '\u0642\u064A',
  20367. '\uFC37': '\u0643\u0627',
  20368. '\uFC38': '\u0643\u062C',
  20369. '\uFC39': '\u0643\u062D',
  20370. '\uFC3A': '\u0643\u062E',
  20371. '\uFC3B': '\u0643\u0644',
  20372. '\uFC3C': '\u0643\u0645',
  20373. '\uFC3D': '\u0643\u0649',
  20374. '\uFC3E': '\u0643\u064A',
  20375. '\uFC3F': '\u0644\u062C',
  20376. '\uFC40': '\u0644\u062D',
  20377. '\uFC41': '\u0644\u062E',
  20378. '\uFC42': '\u0644\u0645',
  20379. '\uFC43': '\u0644\u0649',
  20380. '\uFC44': '\u0644\u064A',
  20381. '\uFC45': '\u0645\u062C',
  20382. '\uFC46': '\u0645\u062D',
  20383. '\uFC47': '\u0645\u062E',
  20384. '\uFC48': '\u0645\u0645',
  20385. '\uFC49': '\u0645\u0649',
  20386. '\uFC4A': '\u0645\u064A',
  20387. '\uFC4B': '\u0646\u062C',
  20388. '\uFC4C': '\u0646\u062D',
  20389. '\uFC4D': '\u0646\u062E',
  20390. '\uFC4E': '\u0646\u0645',
  20391. '\uFC4F': '\u0646\u0649',
  20392. '\uFC50': '\u0646\u064A',
  20393. '\uFC51': '\u0647\u062C',
  20394. '\uFC52': '\u0647\u0645',
  20395. '\uFC53': '\u0647\u0649',
  20396. '\uFC54': '\u0647\u064A',
  20397. '\uFC55': '\u064A\u062C',
  20398. '\uFC56': '\u064A\u062D',
  20399. '\uFC57': '\u064A\u062E',
  20400. '\uFC58': '\u064A\u0645',
  20401. '\uFC59': '\u064A\u0649',
  20402. '\uFC5A': '\u064A\u064A',
  20403. '\uFC5B': '\u0630\u0670',
  20404. '\uFC5C': '\u0631\u0670',
  20405. '\uFC5D': '\u0649\u0670',
  20406. '\uFC5E': '\u0020\u064C\u0651',
  20407. '\uFC5F': '\u0020\u064D\u0651',
  20408. '\uFC60': '\u0020\u064E\u0651',
  20409. '\uFC61': '\u0020\u064F\u0651',
  20410. '\uFC62': '\u0020\u0650\u0651',
  20411. '\uFC63': '\u0020\u0651\u0670',
  20412. '\uFC64': '\u0626\u0631',
  20413. '\uFC65': '\u0626\u0632',
  20414. '\uFC66': '\u0626\u0645',
  20415. '\uFC67': '\u0626\u0646',
  20416. '\uFC68': '\u0626\u0649',
  20417. '\uFC69': '\u0626\u064A',
  20418. '\uFC6A': '\u0628\u0631',
  20419. '\uFC6B': '\u0628\u0632',
  20420. '\uFC6C': '\u0628\u0645',
  20421. '\uFC6D': '\u0628\u0646',
  20422. '\uFC6E': '\u0628\u0649',
  20423. '\uFC6F': '\u0628\u064A',
  20424. '\uFC70': '\u062A\u0631',
  20425. '\uFC71': '\u062A\u0632',
  20426. '\uFC72': '\u062A\u0645',
  20427. '\uFC73': '\u062A\u0646',
  20428. '\uFC74': '\u062A\u0649',
  20429. '\uFC75': '\u062A\u064A',
  20430. '\uFC76': '\u062B\u0631',
  20431. '\uFC77': '\u062B\u0632',
  20432. '\uFC78': '\u062B\u0645',
  20433. '\uFC79': '\u062B\u0646',
  20434. '\uFC7A': '\u062B\u0649',
  20435. '\uFC7B': '\u062B\u064A',
  20436. '\uFC7C': '\u0641\u0649',
  20437. '\uFC7D': '\u0641\u064A',
  20438. '\uFC7E': '\u0642\u0649',
  20439. '\uFC7F': '\u0642\u064A',
  20440. '\uFC80': '\u0643\u0627',
  20441. '\uFC81': '\u0643\u0644',
  20442. '\uFC82': '\u0643\u0645',
  20443. '\uFC83': '\u0643\u0649',
  20444. '\uFC84': '\u0643\u064A',
  20445. '\uFC85': '\u0644\u0645',
  20446. '\uFC86': '\u0644\u0649',
  20447. '\uFC87': '\u0644\u064A',
  20448. '\uFC88': '\u0645\u0627',
  20449. '\uFC89': '\u0645\u0645',
  20450. '\uFC8A': '\u0646\u0631',
  20451. '\uFC8B': '\u0646\u0632',
  20452. '\uFC8C': '\u0646\u0645',
  20453. '\uFC8D': '\u0646\u0646',
  20454. '\uFC8E': '\u0646\u0649',
  20455. '\uFC8F': '\u0646\u064A',
  20456. '\uFC90': '\u0649\u0670',
  20457. '\uFC91': '\u064A\u0631',
  20458. '\uFC92': '\u064A\u0632',
  20459. '\uFC93': '\u064A\u0645',
  20460. '\uFC94': '\u064A\u0646',
  20461. '\uFC95': '\u064A\u0649',
  20462. '\uFC96': '\u064A\u064A',
  20463. '\uFC97': '\u0626\u062C',
  20464. '\uFC98': '\u0626\u062D',
  20465. '\uFC99': '\u0626\u062E',
  20466. '\uFC9A': '\u0626\u0645',
  20467. '\uFC9B': '\u0626\u0647',
  20468. '\uFC9C': '\u0628\u062C',
  20469. '\uFC9D': '\u0628\u062D',
  20470. '\uFC9E': '\u0628\u062E',
  20471. '\uFC9F': '\u0628\u0645',
  20472. '\uFCA0': '\u0628\u0647',
  20473. '\uFCA1': '\u062A\u062C',
  20474. '\uFCA2': '\u062A\u062D',
  20475. '\uFCA3': '\u062A\u062E',
  20476. '\uFCA4': '\u062A\u0645',
  20477. '\uFCA5': '\u062A\u0647',
  20478. '\uFCA6': '\u062B\u0645',
  20479. '\uFCA7': '\u062C\u062D',
  20480. '\uFCA8': '\u062C\u0645',
  20481. '\uFCA9': '\u062D\u062C',
  20482. '\uFCAA': '\u062D\u0645',
  20483. '\uFCAB': '\u062E\u062C',
  20484. '\uFCAC': '\u062E\u0645',
  20485. '\uFCAD': '\u0633\u062C',
  20486. '\uFCAE': '\u0633\u062D',
  20487. '\uFCAF': '\u0633\u062E',
  20488. '\uFCB0': '\u0633\u0645',
  20489. '\uFCB1': '\u0635\u062D',
  20490. '\uFCB2': '\u0635\u062E',
  20491. '\uFCB3': '\u0635\u0645',
  20492. '\uFCB4': '\u0636\u062C',
  20493. '\uFCB5': '\u0636\u062D',
  20494. '\uFCB6': '\u0636\u062E',
  20495. '\uFCB7': '\u0636\u0645',
  20496. '\uFCB8': '\u0637\u062D',
  20497. '\uFCB9': '\u0638\u0645',
  20498. '\uFCBA': '\u0639\u062C',
  20499. '\uFCBB': '\u0639\u0645',
  20500. '\uFCBC': '\u063A\u062C',
  20501. '\uFCBD': '\u063A\u0645',
  20502. '\uFCBE': '\u0641\u062C',
  20503. '\uFCBF': '\u0641\u062D',
  20504. '\uFCC0': '\u0641\u062E',
  20505. '\uFCC1': '\u0641\u0645',
  20506. '\uFCC2': '\u0642\u062D',
  20507. '\uFCC3': '\u0642\u0645',
  20508. '\uFCC4': '\u0643\u062C',
  20509. '\uFCC5': '\u0643\u062D',
  20510. '\uFCC6': '\u0643\u062E',
  20511. '\uFCC7': '\u0643\u0644',
  20512. '\uFCC8': '\u0643\u0645',
  20513. '\uFCC9': '\u0644\u062C',
  20514. '\uFCCA': '\u0644\u062D',
  20515. '\uFCCB': '\u0644\u062E',
  20516. '\uFCCC': '\u0644\u0645',
  20517. '\uFCCD': '\u0644\u0647',
  20518. '\uFCCE': '\u0645\u062C',
  20519. '\uFCCF': '\u0645\u062D',
  20520. '\uFCD0': '\u0645\u062E',
  20521. '\uFCD1': '\u0645\u0645',
  20522. '\uFCD2': '\u0646\u062C',
  20523. '\uFCD3': '\u0646\u062D',
  20524. '\uFCD4': '\u0646\u062E',
  20525. '\uFCD5': '\u0646\u0645',
  20526. '\uFCD6': '\u0646\u0647',
  20527. '\uFCD7': '\u0647\u062C',
  20528. '\uFCD8': '\u0647\u0645',
  20529. '\uFCD9': '\u0647\u0670',
  20530. '\uFCDA': '\u064A\u062C',
  20531. '\uFCDB': '\u064A\u062D',
  20532. '\uFCDC': '\u064A\u062E',
  20533. '\uFCDD': '\u064A\u0645',
  20534. '\uFCDE': '\u064A\u0647',
  20535. '\uFCDF': '\u0626\u0645',
  20536. '\uFCE0': '\u0626\u0647',
  20537. '\uFCE1': '\u0628\u0645',
  20538. '\uFCE2': '\u0628\u0647',
  20539. '\uFCE3': '\u062A\u0645',
  20540. '\uFCE4': '\u062A\u0647',
  20541. '\uFCE5': '\u062B\u0645',
  20542. '\uFCE6': '\u062B\u0647',
  20543. '\uFCE7': '\u0633\u0645',
  20544. '\uFCE8': '\u0633\u0647',
  20545. '\uFCE9': '\u0634\u0645',
  20546. '\uFCEA': '\u0634\u0647',
  20547. '\uFCEB': '\u0643\u0644',
  20548. '\uFCEC': '\u0643\u0645',
  20549. '\uFCED': '\u0644\u0645',
  20550. '\uFCEE': '\u0646\u0645',
  20551. '\uFCEF': '\u0646\u0647',
  20552. '\uFCF0': '\u064A\u0645',
  20553. '\uFCF1': '\u064A\u0647',
  20554. '\uFCF2': '\u0640\u064E\u0651',
  20555. '\uFCF3': '\u0640\u064F\u0651',
  20556. '\uFCF4': '\u0640\u0650\u0651',
  20557. '\uFCF5': '\u0637\u0649',
  20558. '\uFCF6': '\u0637\u064A',
  20559. '\uFCF7': '\u0639\u0649',
  20560. '\uFCF8': '\u0639\u064A',
  20561. '\uFCF9': '\u063A\u0649',
  20562. '\uFCFA': '\u063A\u064A',
  20563. '\uFCFB': '\u0633\u0649',
  20564. '\uFCFC': '\u0633\u064A',
  20565. '\uFCFD': '\u0634\u0649',
  20566. '\uFCFE': '\u0634\u064A',
  20567. '\uFCFF': '\u062D\u0649',
  20568. '\uFD00': '\u062D\u064A',
  20569. '\uFD01': '\u062C\u0649',
  20570. '\uFD02': '\u062C\u064A',
  20571. '\uFD03': '\u062E\u0649',
  20572. '\uFD04': '\u062E\u064A',
  20573. '\uFD05': '\u0635\u0649',
  20574. '\uFD06': '\u0635\u064A',
  20575. '\uFD07': '\u0636\u0649',
  20576. '\uFD08': '\u0636\u064A',
  20577. '\uFD09': '\u0634\u062C',
  20578. '\uFD0A': '\u0634\u062D',
  20579. '\uFD0B': '\u0634\u062E',
  20580. '\uFD0C': '\u0634\u0645',
  20581. '\uFD0D': '\u0634\u0631',
  20582. '\uFD0E': '\u0633\u0631',
  20583. '\uFD0F': '\u0635\u0631',
  20584. '\uFD10': '\u0636\u0631',
  20585. '\uFD11': '\u0637\u0649',
  20586. '\uFD12': '\u0637\u064A',
  20587. '\uFD13': '\u0639\u0649',
  20588. '\uFD14': '\u0639\u064A',
  20589. '\uFD15': '\u063A\u0649',
  20590. '\uFD16': '\u063A\u064A',
  20591. '\uFD17': '\u0633\u0649',
  20592. '\uFD18': '\u0633\u064A',
  20593. '\uFD19': '\u0634\u0649',
  20594. '\uFD1A': '\u0634\u064A',
  20595. '\uFD1B': '\u062D\u0649',
  20596. '\uFD1C': '\u062D\u064A',
  20597. '\uFD1D': '\u062C\u0649',
  20598. '\uFD1E': '\u062C\u064A',
  20599. '\uFD1F': '\u062E\u0649',
  20600. '\uFD20': '\u062E\u064A',
  20601. '\uFD21': '\u0635\u0649',
  20602. '\uFD22': '\u0635\u064A',
  20603. '\uFD23': '\u0636\u0649',
  20604. '\uFD24': '\u0636\u064A',
  20605. '\uFD25': '\u0634\u062C',
  20606. '\uFD26': '\u0634\u062D',
  20607. '\uFD27': '\u0634\u062E',
  20608. '\uFD28': '\u0634\u0645',
  20609. '\uFD29': '\u0634\u0631',
  20610. '\uFD2A': '\u0633\u0631',
  20611. '\uFD2B': '\u0635\u0631',
  20612. '\uFD2C': '\u0636\u0631',
  20613. '\uFD2D': '\u0634\u062C',
  20614. '\uFD2E': '\u0634\u062D',
  20615. '\uFD2F': '\u0634\u062E',
  20616. '\uFD30': '\u0634\u0645',
  20617. '\uFD31': '\u0633\u0647',
  20618. '\uFD32': '\u0634\u0647',
  20619. '\uFD33': '\u0637\u0645',
  20620. '\uFD34': '\u0633\u062C',
  20621. '\uFD35': '\u0633\u062D',
  20622. '\uFD36': '\u0633\u062E',
  20623. '\uFD37': '\u0634\u062C',
  20624. '\uFD38': '\u0634\u062D',
  20625. '\uFD39': '\u0634\u062E',
  20626. '\uFD3A': '\u0637\u0645',
  20627. '\uFD3B': '\u0638\u0645',
  20628. '\uFD3C': '\u0627\u064B',
  20629. '\uFD3D': '\u0627\u064B',
  20630. '\uFD50': '\u062A\u062C\u0645',
  20631. '\uFD51': '\u062A\u062D\u062C',
  20632. '\uFD52': '\u062A\u062D\u062C',
  20633. '\uFD53': '\u062A\u062D\u0645',
  20634. '\uFD54': '\u062A\u062E\u0645',
  20635. '\uFD55': '\u062A\u0645\u062C',
  20636. '\uFD56': '\u062A\u0645\u062D',
  20637. '\uFD57': '\u062A\u0645\u062E',
  20638. '\uFD58': '\u062C\u0645\u062D',
  20639. '\uFD59': '\u062C\u0645\u062D',
  20640. '\uFD5A': '\u062D\u0645\u064A',
  20641. '\uFD5B': '\u062D\u0645\u0649',
  20642. '\uFD5C': '\u0633\u062D\u062C',
  20643. '\uFD5D': '\u0633\u062C\u062D',
  20644. '\uFD5E': '\u0633\u062C\u0649',
  20645. '\uFD5F': '\u0633\u0645\u062D',
  20646. '\uFD60': '\u0633\u0645\u062D',
  20647. '\uFD61': '\u0633\u0645\u062C',
  20648. '\uFD62': '\u0633\u0645\u0645',
  20649. '\uFD63': '\u0633\u0645\u0645',
  20650. '\uFD64': '\u0635\u062D\u062D',
  20651. '\uFD65': '\u0635\u062D\u062D',
  20652. '\uFD66': '\u0635\u0645\u0645',
  20653. '\uFD67': '\u0634\u062D\u0645',
  20654. '\uFD68': '\u0634\u062D\u0645',
  20655. '\uFD69': '\u0634\u062C\u064A',
  20656. '\uFD6A': '\u0634\u0645\u062E',
  20657. '\uFD6B': '\u0634\u0645\u062E',
  20658. '\uFD6C': '\u0634\u0645\u0645',
  20659. '\uFD6D': '\u0634\u0645\u0645',
  20660. '\uFD6E': '\u0636\u062D\u0649',
  20661. '\uFD6F': '\u0636\u062E\u0645',
  20662. '\uFD70': '\u0636\u062E\u0645',
  20663. '\uFD71': '\u0637\u0645\u062D',
  20664. '\uFD72': '\u0637\u0645\u062D',
  20665. '\uFD73': '\u0637\u0645\u0645',
  20666. '\uFD74': '\u0637\u0645\u064A',
  20667. '\uFD75': '\u0639\u062C\u0645',
  20668. '\uFD76': '\u0639\u0645\u0645',
  20669. '\uFD77': '\u0639\u0645\u0645',
  20670. '\uFD78': '\u0639\u0645\u0649',
  20671. '\uFD79': '\u063A\u0645\u0645',
  20672. '\uFD7A': '\u063A\u0645\u064A',
  20673. '\uFD7B': '\u063A\u0645\u0649',
  20674. '\uFD7C': '\u0641\u062E\u0645',
  20675. '\uFD7D': '\u0641\u062E\u0645',
  20676. '\uFD7E': '\u0642\u0645\u062D',
  20677. '\uFD7F': '\u0642\u0645\u0645',
  20678. '\uFD80': '\u0644\u062D\u0645',
  20679. '\uFD81': '\u0644\u062D\u064A',
  20680. '\uFD82': '\u0644\u062D\u0649',
  20681. '\uFD83': '\u0644\u062C\u062C',
  20682. '\uFD84': '\u0644\u062C\u062C',
  20683. '\uFD85': '\u0644\u062E\u0645',
  20684. '\uFD86': '\u0644\u062E\u0645',
  20685. '\uFD87': '\u0644\u0645\u062D',
  20686. '\uFD88': '\u0644\u0645\u062D',
  20687. '\uFD89': '\u0645\u062D\u062C',
  20688. '\uFD8A': '\u0645\u062D\u0645',
  20689. '\uFD8B': '\u0645\u062D\u064A',
  20690. '\uFD8C': '\u0645\u062C\u062D',
  20691. '\uFD8D': '\u0645\u062C\u0645',
  20692. '\uFD8E': '\u0645\u062E\u062C',
  20693. '\uFD8F': '\u0645\u062E\u0645',
  20694. '\uFD92': '\u0645\u062C\u062E',
  20695. '\uFD93': '\u0647\u0645\u062C',
  20696. '\uFD94': '\u0647\u0645\u0645',
  20697. '\uFD95': '\u0646\u062D\u0645',
  20698. '\uFD96': '\u0646\u062D\u0649',
  20699. '\uFD97': '\u0646\u062C\u0645',
  20700. '\uFD98': '\u0646\u062C\u0645',
  20701. '\uFD99': '\u0646\u062C\u0649',
  20702. '\uFD9A': '\u0646\u0645\u064A',
  20703. '\uFD9B': '\u0646\u0645\u0649',
  20704. '\uFD9C': '\u064A\u0645\u0645',
  20705. '\uFD9D': '\u064A\u0645\u0645',
  20706. '\uFD9E': '\u0628\u062E\u064A',
  20707. '\uFD9F': '\u062A\u062C\u064A',
  20708. '\uFDA0': '\u062A\u062C\u0649',
  20709. '\uFDA1': '\u062A\u062E\u064A',
  20710. '\uFDA2': '\u062A\u062E\u0649',
  20711. '\uFDA3': '\u062A\u0645\u064A',
  20712. '\uFDA4': '\u062A\u0645\u0649',
  20713. '\uFDA5': '\u062C\u0645\u064A',
  20714. '\uFDA6': '\u062C\u062D\u0649',
  20715. '\uFDA7': '\u062C\u0645\u0649',
  20716. '\uFDA8': '\u0633\u062E\u0649',
  20717. '\uFDA9': '\u0635\u062D\u064A',
  20718. '\uFDAA': '\u0634\u062D\u064A',
  20719. '\uFDAB': '\u0636\u062D\u064A',
  20720. '\uFDAC': '\u0644\u062C\u064A',
  20721. '\uFDAD': '\u0644\u0645\u064A',
  20722. '\uFDAE': '\u064A\u062D\u064A',
  20723. '\uFDAF': '\u064A\u062C\u064A',
  20724. '\uFDB0': '\u064A\u0645\u064A',
  20725. '\uFDB1': '\u0645\u0645\u064A',
  20726. '\uFDB2': '\u0642\u0645\u064A',
  20727. '\uFDB3': '\u0646\u062D\u064A',
  20728. '\uFDB4': '\u0642\u0645\u062D',
  20729. '\uFDB5': '\u0644\u062D\u0645',
  20730. '\uFDB6': '\u0639\u0645\u064A',
  20731. '\uFDB7': '\u0643\u0645\u064A',
  20732. '\uFDB8': '\u0646\u062C\u062D',
  20733. '\uFDB9': '\u0645\u062E\u064A',
  20734. '\uFDBA': '\u0644\u062C\u0645',
  20735. '\uFDBB': '\u0643\u0645\u0645',
  20736. '\uFDBC': '\u0644\u062C\u0645',
  20737. '\uFDBD': '\u0646\u062C\u062D',
  20738. '\uFDBE': '\u062C\u062D\u064A',
  20739. '\uFDBF': '\u062D\u062C\u064A',
  20740. '\uFDC0': '\u0645\u062C\u064A',
  20741. '\uFDC1': '\u0641\u0645\u064A',
  20742. '\uFDC2': '\u0628\u062D\u064A',
  20743. '\uFDC3': '\u0643\u0645\u0645',
  20744. '\uFDC4': '\u0639\u062C\u0645',
  20745. '\uFDC5': '\u0635\u0645\u0645',
  20746. '\uFDC6': '\u0633\u062E\u064A',
  20747. '\uFDC7': '\u0646\u062C\u064A',
  20748. '\uFE49': '\u203E',
  20749. '\uFE4A': '\u203E',
  20750. '\uFE4B': '\u203E',
  20751. '\uFE4C': '\u203E',
  20752. '\uFE4D': '\u005F',
  20753. '\uFE4E': '\u005F',
  20754. '\uFE4F': '\u005F',
  20755. '\uFE80': '\u0621',
  20756. '\uFE81': '\u0622',
  20757. '\uFE82': '\u0622',
  20758. '\uFE83': '\u0623',
  20759. '\uFE84': '\u0623',
  20760. '\uFE85': '\u0624',
  20761. '\uFE86': '\u0624',
  20762. '\uFE87': '\u0625',
  20763. '\uFE88': '\u0625',
  20764. '\uFE89': '\u0626',
  20765. '\uFE8A': '\u0626',
  20766. '\uFE8B': '\u0626',
  20767. '\uFE8C': '\u0626',
  20768. '\uFE8D': '\u0627',
  20769. '\uFE8E': '\u0627',
  20770. '\uFE8F': '\u0628',
  20771. '\uFE90': '\u0628',
  20772. '\uFE91': '\u0628',
  20773. '\uFE92': '\u0628',
  20774. '\uFE93': '\u0629',
  20775. '\uFE94': '\u0629',
  20776. '\uFE95': '\u062A',
  20777. '\uFE96': '\u062A',
  20778. '\uFE97': '\u062A',
  20779. '\uFE98': '\u062A',
  20780. '\uFE99': '\u062B',
  20781. '\uFE9A': '\u062B',
  20782. '\uFE9B': '\u062B',
  20783. '\uFE9C': '\u062B',
  20784. '\uFE9D': '\u062C',
  20785. '\uFE9E': '\u062C',
  20786. '\uFE9F': '\u062C',
  20787. '\uFEA0': '\u062C',
  20788. '\uFEA1': '\u062D',
  20789. '\uFEA2': '\u062D',
  20790. '\uFEA3': '\u062D',
  20791. '\uFEA4': '\u062D',
  20792. '\uFEA5': '\u062E',
  20793. '\uFEA6': '\u062E',
  20794. '\uFEA7': '\u062E',
  20795. '\uFEA8': '\u062E',
  20796. '\uFEA9': '\u062F',
  20797. '\uFEAA': '\u062F',
  20798. '\uFEAB': '\u0630',
  20799. '\uFEAC': '\u0630',
  20800. '\uFEAD': '\u0631',
  20801. '\uFEAE': '\u0631',
  20802. '\uFEAF': '\u0632',
  20803. '\uFEB0': '\u0632',
  20804. '\uFEB1': '\u0633',
  20805. '\uFEB2': '\u0633',
  20806. '\uFEB3': '\u0633',
  20807. '\uFEB4': '\u0633',
  20808. '\uFEB5': '\u0634',
  20809. '\uFEB6': '\u0634',
  20810. '\uFEB7': '\u0634',
  20811. '\uFEB8': '\u0634',
  20812. '\uFEB9': '\u0635',
  20813. '\uFEBA': '\u0635',
  20814. '\uFEBB': '\u0635',
  20815. '\uFEBC': '\u0635',
  20816. '\uFEBD': '\u0636',
  20817. '\uFEBE': '\u0636',
  20818. '\uFEBF': '\u0636',
  20819. '\uFEC0': '\u0636',
  20820. '\uFEC1': '\u0637',
  20821. '\uFEC2': '\u0637',
  20822. '\uFEC3': '\u0637',
  20823. '\uFEC4': '\u0637',
  20824. '\uFEC5': '\u0638',
  20825. '\uFEC6': '\u0638',
  20826. '\uFEC7': '\u0638',
  20827. '\uFEC8': '\u0638',
  20828. '\uFEC9': '\u0639',
  20829. '\uFECA': '\u0639',
  20830. '\uFECB': '\u0639',
  20831. '\uFECC': '\u0639',
  20832. '\uFECD': '\u063A',
  20833. '\uFECE': '\u063A',
  20834. '\uFECF': '\u063A',
  20835. '\uFED0': '\u063A',
  20836. '\uFED1': '\u0641',
  20837. '\uFED2': '\u0641',
  20838. '\uFED3': '\u0641',
  20839. '\uFED4': '\u0641',
  20840. '\uFED5': '\u0642',
  20841. '\uFED6': '\u0642',
  20842. '\uFED7': '\u0642',
  20843. '\uFED8': '\u0642',
  20844. '\uFED9': '\u0643',
  20845. '\uFEDA': '\u0643',
  20846. '\uFEDB': '\u0643',
  20847. '\uFEDC': '\u0643',
  20848. '\uFEDD': '\u0644',
  20849. '\uFEDE': '\u0644',
  20850. '\uFEDF': '\u0644',
  20851. '\uFEE0': '\u0644',
  20852. '\uFEE1': '\u0645',
  20853. '\uFEE2': '\u0645',
  20854. '\uFEE3': '\u0645',
  20855. '\uFEE4': '\u0645',
  20856. '\uFEE5': '\u0646',
  20857. '\uFEE6': '\u0646',
  20858. '\uFEE7': '\u0646',
  20859. '\uFEE8': '\u0646',
  20860. '\uFEE9': '\u0647',
  20861. '\uFEEA': '\u0647',
  20862. '\uFEEB': '\u0647',
  20863. '\uFEEC': '\u0647',
  20864. '\uFEED': '\u0648',
  20865. '\uFEEE': '\u0648',
  20866. '\uFEEF': '\u0649',
  20867. '\uFEF0': '\u0649',
  20868. '\uFEF1': '\u064A',
  20869. '\uFEF2': '\u064A',
  20870. '\uFEF3': '\u064A',
  20871. '\uFEF4': '\u064A',
  20872. '\uFEF5': '\u0644\u0622',
  20873. '\uFEF6': '\u0644\u0622',
  20874. '\uFEF7': '\u0644\u0623',
  20875. '\uFEF8': '\u0644\u0623',
  20876. '\uFEF9': '\u0644\u0625',
  20877. '\uFEFA': '\u0644\u0625',
  20878. '\uFEFB': '\u0644\u0627',
  20879. '\uFEFC': '\u0644\u0627'
  20880. };
  20881. function reverseIfRtl(chars) {
  20882. var charsLength = chars.length;
  20883. //reverse an arabic ligature
  20884. if (charsLength <= 1 || !isRTLRangeFor(chars.charCodeAt(0))) {
  20885. return chars;
  20886. }
  20887. var s = '';
  20888. for (var ii = charsLength - 1; ii >= 0; ii--) {
  20889. s += chars[ii];
  20890. }
  20891. return s;
  20892. }
  20893. function adjustWidths(properties) {
  20894. if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
  20895. return;
  20896. }
  20897. // adjusting width to fontMatrix scale
  20898. var scale = 0.001 / properties.fontMatrix[0];
  20899. var glyphsWidths = properties.widths;
  20900. for (var glyph in glyphsWidths) {
  20901. glyphsWidths[glyph] *= scale;
  20902. }
  20903. properties.defaultWidth *= scale;
  20904. }
  20905. function getFontType(type, subtype) {
  20906. switch (type) {
  20907. case 'Type1':
  20908. return subtype === 'Type1C' ? FontType.TYPE1C : FontType.TYPE1;
  20909. case 'CIDFontType0':
  20910. return subtype === 'CIDFontType0C' ? FontType.CIDFONTTYPE0C :
  20911. FontType.CIDFONTTYPE0;
  20912. case 'OpenType':
  20913. return FontType.OPENTYPE;
  20914. case 'TrueType':
  20915. return FontType.TRUETYPE;
  20916. case 'CIDFontType2':
  20917. return FontType.CIDFONTTYPE2;
  20918. case 'MMType1':
  20919. return FontType.MMTYPE1;
  20920. case 'Type0':
  20921. return FontType.TYPE0;
  20922. default:
  20923. return FontType.UNKNOWN;
  20924. }
  20925. }
  20926. var Glyph = (function GlyphClosure() {
  20927. function Glyph(fontChar, unicode, accent, width, vmetric, operatorListId) {
  20928. this.fontChar = fontChar;
  20929. this.unicode = unicode;
  20930. this.accent = accent;
  20931. this.width = width;
  20932. this.vmetric = vmetric;
  20933. this.operatorListId = operatorListId;
  20934. }
  20935. Glyph.prototype.matchesForCache =
  20936. function(fontChar, unicode, accent, width, vmetric, operatorListId) {
  20937. return this.fontChar === fontChar &&
  20938. this.unicode === unicode &&
  20939. this.accent === accent &&
  20940. this.width === width &&
  20941. this.vmetric === vmetric &&
  20942. this.operatorListId === operatorListId;
  20943. };
  20944. return Glyph;
  20945. })();
  20946. var ToUnicodeMap = (function ToUnicodeMapClosure() {
  20947. function ToUnicodeMap(cmap) {
  20948. // The elements of this._map can be integers or strings, depending on how
  20949. // |cmap| was created.
  20950. this._map = cmap;
  20951. }
  20952. ToUnicodeMap.prototype = {
  20953. get length() {
  20954. return this._map.length;
  20955. },
  20956. forEach: function(callback) {
  20957. for (var charCode in this._map) {
  20958. callback(charCode, this._map[charCode].charCodeAt(0));
  20959. }
  20960. },
  20961. has: function(i) {
  20962. return this._map[i] !== undefined;
  20963. },
  20964. get: function(i) {
  20965. return this._map[i];
  20966. },
  20967. charCodeOf: function(v) {
  20968. return this._map.indexOf(v);
  20969. }
  20970. };
  20971. return ToUnicodeMap;
  20972. })();
  20973. var IdentityToUnicodeMap = (function IdentityToUnicodeMapClosure() {
  20974. function IdentityToUnicodeMap(firstChar, lastChar) {
  20975. this.firstChar = firstChar;
  20976. this.lastChar = lastChar;
  20977. }
  20978. IdentityToUnicodeMap.prototype = {
  20979. get length() {
  20980. return (this.lastChar + 1) - this.firstChar;
  20981. },
  20982. forEach: function (callback) {
  20983. for (var i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
  20984. callback(i, i);
  20985. }
  20986. },
  20987. has: function (i) {
  20988. return this.firstChar <= i && i <= this.lastChar;
  20989. },
  20990. get: function (i) {
  20991. if (this.firstChar <= i && i <= this.lastChar) {
  20992. return String.fromCharCode(i);
  20993. }
  20994. return undefined;
  20995. },
  20996. charCodeOf: function (v) {
  20997. error('should not call .charCodeOf');
  20998. }
  20999. };
  21000. return IdentityToUnicodeMap;
  21001. })();
  21002. var OpenTypeFileBuilder = (function OpenTypeFileBuilderClosure() {
  21003. function writeInt16(dest, offset, num) {
  21004. dest[offset] = (num >> 8) & 0xFF;
  21005. dest[offset + 1] = num & 0xFF;
  21006. }
  21007. function writeInt32(dest, offset, num) {
  21008. dest[offset] = (num >> 24) & 0xFF;
  21009. dest[offset + 1] = (num >> 16) & 0xFF;
  21010. dest[offset + 2] = (num >> 8) & 0xFF;
  21011. dest[offset + 3] = num & 0xFF;
  21012. }
  21013. function writeData(dest, offset, data) {
  21014. var i, ii;
  21015. if (data instanceof Uint8Array) {
  21016. dest.set(data, offset);
  21017. } else if (typeof data === 'string') {
  21018. for (i = 0, ii = data.length; i < ii; i++) {
  21019. dest[offset++] = data.charCodeAt(i) & 0xFF;
  21020. }
  21021. } else {
  21022. // treating everything else as array
  21023. for (i = 0, ii = data.length; i < ii; i++) {
  21024. dest[offset++] = data[i] & 0xFF;
  21025. }
  21026. }
  21027. }
  21028. function OpenTypeFileBuilder(sfnt) {
  21029. this.sfnt = sfnt;
  21030. this.tables = Object.create(null);
  21031. }
  21032. OpenTypeFileBuilder.getSearchParams =
  21033. function OpenTypeFileBuilder_getSearchParams(entriesCount, entrySize) {
  21034. var maxPower2 = 1, log2 = 0;
  21035. while ((maxPower2 ^ entriesCount) > maxPower2) {
  21036. maxPower2 <<= 1;
  21037. log2++;
  21038. }
  21039. var searchRange = maxPower2 * entrySize;
  21040. return {
  21041. range: searchRange,
  21042. entry: log2,
  21043. rangeShift: entrySize * entriesCount - searchRange
  21044. };
  21045. };
  21046. var OTF_HEADER_SIZE = 12;
  21047. var OTF_TABLE_ENTRY_SIZE = 16;
  21048. OpenTypeFileBuilder.prototype = {
  21049. toArray: function OpenTypeFileBuilder_toArray() {
  21050. var sfnt = this.sfnt;
  21051. // Tables needs to be written by ascendant alphabetic order
  21052. var tables = this.tables;
  21053. var tablesNames = Object.keys(tables);
  21054. tablesNames.sort();
  21055. var numTables = tablesNames.length;
  21056. var i, j, jj, table, tableName;
  21057. // layout the tables data
  21058. var offset = OTF_HEADER_SIZE + numTables * OTF_TABLE_ENTRY_SIZE;
  21059. var tableOffsets = [offset];
  21060. for (i = 0; i < numTables; i++) {
  21061. table = tables[tablesNames[i]];
  21062. var paddedLength = ((table.length + 3) & ~3) >>> 0;
  21063. offset += paddedLength;
  21064. tableOffsets.push(offset);
  21065. }
  21066. var file = new Uint8Array(offset);
  21067. // write the table data first (mostly for checksum)
  21068. for (i = 0; i < numTables; i++) {
  21069. table = tables[tablesNames[i]];
  21070. writeData(file, tableOffsets[i], table);
  21071. }
  21072. // sfnt version (4 bytes)
  21073. if (sfnt === 'true') {
  21074. // Windows hates the Mac TrueType sfnt version number
  21075. sfnt = string32(0x00010000);
  21076. }
  21077. file[0] = sfnt.charCodeAt(0) & 0xFF;
  21078. file[1] = sfnt.charCodeAt(1) & 0xFF;
  21079. file[2] = sfnt.charCodeAt(2) & 0xFF;
  21080. file[3] = sfnt.charCodeAt(3) & 0xFF;
  21081. // numTables (2 bytes)
  21082. writeInt16(file, 4, numTables);
  21083. var searchParams = OpenTypeFileBuilder.getSearchParams(numTables, 16);
  21084. // searchRange (2 bytes)
  21085. writeInt16(file, 6, searchParams.range);
  21086. // entrySelector (2 bytes)
  21087. writeInt16(file, 8, searchParams.entry);
  21088. // rangeShift (2 bytes)
  21089. writeInt16(file, 10, searchParams.rangeShift);
  21090. offset = OTF_HEADER_SIZE;
  21091. // writing table entries
  21092. for (i = 0; i < numTables; i++) {
  21093. tableName = tablesNames[i];
  21094. file[offset] = tableName.charCodeAt(0) & 0xFF;
  21095. file[offset + 1] = tableName.charCodeAt(1) & 0xFF;
  21096. file[offset + 2] = tableName.charCodeAt(2) & 0xFF;
  21097. file[offset + 3] = tableName.charCodeAt(3) & 0xFF;
  21098. // checksum
  21099. var checksum = 0;
  21100. for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
  21101. var quad = (file[j] << 24) + (file[j + 1] << 16) +
  21102. (file[j + 2] << 8) + file[j + 3];
  21103. checksum = (checksum + quad) | 0;
  21104. }
  21105. writeInt32(file, offset + 4, checksum);
  21106. // offset
  21107. writeInt32(file, offset + 8, tableOffsets[i]);
  21108. // length
  21109. writeInt32(file, offset + 12, tables[tableName].length);
  21110. offset += OTF_TABLE_ENTRY_SIZE;
  21111. }
  21112. return file;
  21113. },
  21114. addTable: function OpenTypeFileBuilder_addTable(tag, data) {
  21115. if (tag in this.tables) {
  21116. throw new Error('Table ' + tag + ' already exists');
  21117. }
  21118. this.tables[tag] = data;
  21119. }
  21120. };
  21121. return OpenTypeFileBuilder;
  21122. })();
  21123. // Problematic Unicode characters in the fonts that needs to be moved to avoid
  21124. // issues when they are painted on the canvas, e.g. complex-script shaping or
  21125. // control/whitespace characters. The ranges are listed in pairs: the first item
  21126. // is a code of the first problematic code, the second one is the next
  21127. // non-problematic code. The ranges must be in sorted order.
  21128. var ProblematicCharRanges = new Int32Array([
  21129. // Control characters.
  21130. 0x0000, 0x0020,
  21131. 0x007F, 0x00A1,
  21132. 0x00AD, 0x00AE,
  21133. // Chars that is used in complex-script shaping.
  21134. 0x0600, 0x0780,
  21135. 0x08A0, 0x10A0,
  21136. 0x1780, 0x1800,
  21137. // General punctuation chars.
  21138. 0x2000, 0x2010,
  21139. 0x2011, 0x2012,
  21140. 0x2028, 0x2030,
  21141. 0x205F, 0x2070,
  21142. 0x25CC, 0x25CD,
  21143. // Chars that is used in complex-script shaping.
  21144. 0xAA60, 0xAA80,
  21145. // Specials Unicode block.
  21146. 0xFFF0, 0x10000
  21147. ]);
  21148. /**
  21149. * 'Font' is the class the outside world should use, it encapsulate all the font
  21150. * decoding logics whatever type it is (assuming the font type is supported).
  21151. *
  21152. * For example to read a Type1 font and to attach it to the document:
  21153. * var type1Font = new Font("MyFontName", binaryFile, propertiesObject);
  21154. * type1Font.bind();
  21155. */
  21156. var Font = (function FontClosure() {
  21157. function Font(name, file, properties) {
  21158. var charCode, glyphName, fontChar;
  21159. this.name = name;
  21160. this.loadedName = properties.loadedName;
  21161. this.isType3Font = properties.isType3Font;
  21162. this.sizes = [];
  21163. this.glyphCache = {};
  21164. var names = name.split('+');
  21165. names = names.length > 1 ? names[1] : names[0];
  21166. names = names.split(/[-,_]/g)[0];
  21167. this.isSerifFont = !!(properties.flags & FontFlags.Serif);
  21168. this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  21169. this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);
  21170. var type = properties.type;
  21171. var subtype = properties.subtype;
  21172. this.type = type;
  21173. this.fallbackName = (this.isMonospace ? 'monospace' :
  21174. (this.isSerifFont ? 'serif' : 'sans-serif'));
  21175. this.differences = properties.differences;
  21176. this.widths = properties.widths;
  21177. this.defaultWidth = properties.defaultWidth;
  21178. this.composite = properties.composite;
  21179. this.wideChars = properties.wideChars;
  21180. this.cMap = properties.cMap;
  21181. this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
  21182. this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
  21183. this.fontMatrix = properties.fontMatrix;
  21184. this.bbox = properties.bbox;
  21185. this.toUnicode = properties.toUnicode = this.buildToUnicode(properties);
  21186. this.toFontChar = [];
  21187. if (properties.type === 'Type3') {
  21188. for (charCode = 0; charCode < 256; charCode++) {
  21189. this.toFontChar[charCode] = (this.differences[charCode] ||
  21190. properties.defaultEncoding[charCode]);
  21191. }
  21192. this.fontType = FontType.TYPE3;
  21193. return;
  21194. }
  21195. this.cidEncoding = properties.cidEncoding;
  21196. this.vertical = properties.vertical;
  21197. if (this.vertical) {
  21198. this.vmetrics = properties.vmetrics;
  21199. this.defaultVMetrics = properties.defaultVMetrics;
  21200. }
  21201. if (!file || file.isEmpty) {
  21202. if (file) {
  21203. // Some bad PDF generators will include empty font files,
  21204. // attempting to recover by assuming that no file exists.
  21205. warn('Font file is empty in "' + name + '" (' + this.loadedName + ')');
  21206. }
  21207. this.missingFile = true;
  21208. // The file data is not specified. Trying to fix the font name
  21209. // to be used with the canvas.font.
  21210. var fontName = name.replace(/[,_]/g, '-');
  21211. var isStandardFont = !!stdFontMap[fontName] ||
  21212. !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]);
  21213. fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
  21214. this.bold = (fontName.search(/bold/gi) !== -1);
  21215. this.italic = ((fontName.search(/oblique/gi) !== -1) ||
  21216. (fontName.search(/italic/gi) !== -1));
  21217. // Use 'name' instead of 'fontName' here because the original
  21218. // name ArialBlack for example will be replaced by Helvetica.
  21219. this.black = (name.search(/Black/g) !== -1);
  21220. // if at least one width is present, remeasure all chars when exists
  21221. this.remeasure = Object.keys(this.widths).length > 0;
  21222. if (isStandardFont && type === 'CIDFontType2' &&
  21223. properties.cidEncoding.indexOf('Identity-') === 0) {
  21224. // Standard fonts might be embedded as CID font without glyph mapping.
  21225. // Building one based on GlyphMapForStandardFonts.
  21226. var map = [];
  21227. for (charCode in GlyphMapForStandardFonts) {
  21228. map[+charCode] = GlyphMapForStandardFonts[charCode];
  21229. }
  21230. if (/ArialBlack/i.test(name)) {
  21231. for (charCode in SupplementalGlyphMapForArialBlack) {
  21232. map[+charCode] = SupplementalGlyphMapForArialBlack[charCode];
  21233. }
  21234. }
  21235. var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
  21236. if (!isIdentityUnicode) {
  21237. this.toUnicode.forEach(function(charCode, unicodeCharCode) {
  21238. map[+charCode] = unicodeCharCode;
  21239. });
  21240. }
  21241. this.toFontChar = map;
  21242. this.toUnicode = new ToUnicodeMap(map);
  21243. } else if (/Symbol/i.test(fontName)) {
  21244. var symbols = Encodings.SymbolSetEncoding;
  21245. for (charCode in symbols) {
  21246. fontChar = GlyphsUnicode[symbols[charCode]];
  21247. if (!fontChar) {
  21248. continue;
  21249. }
  21250. this.toFontChar[charCode] = fontChar;
  21251. }
  21252. for (charCode in properties.differences) {
  21253. fontChar = GlyphsUnicode[properties.differences[charCode]];
  21254. if (!fontChar) {
  21255. continue;
  21256. }
  21257. this.toFontChar[charCode] = fontChar;
  21258. }
  21259. } else if (/Dingbats/i.test(fontName)) {
  21260. if (/Wingdings/i.test(name)) {
  21261. warn('Wingdings font without embedded font file, ' +
  21262. 'falling back to the ZapfDingbats encoding.');
  21263. }
  21264. var dingbats = Encodings.ZapfDingbatsEncoding;
  21265. for (charCode in dingbats) {
  21266. fontChar = DingbatsGlyphsUnicode[dingbats[charCode]];
  21267. if (!fontChar) {
  21268. continue;
  21269. }
  21270. this.toFontChar[charCode] = fontChar;
  21271. }
  21272. for (charCode in properties.differences) {
  21273. fontChar = DingbatsGlyphsUnicode[properties.differences[charCode]];
  21274. if (!fontChar) {
  21275. continue;
  21276. }
  21277. this.toFontChar[charCode] = fontChar;
  21278. }
  21279. } else if (isStandardFont) {
  21280. this.toFontChar = [];
  21281. for (charCode in properties.defaultEncoding) {
  21282. glyphName = (properties.differences[charCode] ||
  21283. properties.defaultEncoding[charCode]);
  21284. this.toFontChar[charCode] = GlyphsUnicode[glyphName];
  21285. }
  21286. } else {
  21287. var unicodeCharCode, notCidFont = (type.indexOf('CIDFontType') === -1);
  21288. this.toUnicode.forEach(function(charCode, unicodeCharCode) {
  21289. if (notCidFont) {
  21290. glyphName = (properties.differences[charCode] ||
  21291. properties.defaultEncoding[charCode]);
  21292. unicodeCharCode = (GlyphsUnicode[glyphName] || unicodeCharCode);
  21293. }
  21294. this.toFontChar[charCode] = unicodeCharCode;
  21295. }.bind(this));
  21296. }
  21297. this.loadedName = fontName.split('-')[0];
  21298. this.loading = false;
  21299. this.fontType = getFontType(type, subtype);
  21300. return;
  21301. }
  21302. // Some fonts might use wrong font types for Type1C or CIDFontType0C
  21303. if (subtype === 'Type1C' && (type !== 'Type1' && type !== 'MMType1')) {
  21304. // Some TrueType fonts by mistake claim Type1C
  21305. if (isTrueTypeFile(file)) {
  21306. subtype = 'TrueType';
  21307. } else {
  21308. type = 'Type1';
  21309. }
  21310. }
  21311. if (subtype === 'CIDFontType0C' && type !== 'CIDFontType0') {
  21312. type = 'CIDFontType0';
  21313. }
  21314. if (subtype === 'OpenType') {
  21315. type = 'OpenType';
  21316. }
  21317. // Some CIDFontType0C fonts by mistake claim CIDFontType0.
  21318. if (type === 'CIDFontType0') {
  21319. subtype = isType1File(file) ? 'CIDFontType0' : 'CIDFontType0C';
  21320. }
  21321. var data;
  21322. switch (type) {
  21323. case 'MMType1':
  21324. info('MMType1 font (' + name + '), falling back to Type1.');
  21325. /* falls through */
  21326. case 'Type1':
  21327. case 'CIDFontType0':
  21328. this.mimetype = 'font/opentype';
  21329. var cff = (subtype === 'Type1C' || subtype === 'CIDFontType0C') ?
  21330. new CFFFont(file, properties) : new Type1Font(name, file, properties);
  21331. adjustWidths(properties);
  21332. // Wrap the CFF data inside an OTF font file
  21333. data = this.convert(name, cff, properties);
  21334. break;
  21335. case 'OpenType':
  21336. case 'TrueType':
  21337. case 'CIDFontType2':
  21338. this.mimetype = 'font/opentype';
  21339. // Repair the TrueType file. It is can be damaged in the point of
  21340. // view of the sanitizer
  21341. data = this.checkAndRepair(name, file, properties);
  21342. if (this.isOpenType) {
  21343. type = 'OpenType';
  21344. }
  21345. break;
  21346. default:
  21347. error('Font ' + type + ' is not supported');
  21348. break;
  21349. }
  21350. this.data = data;
  21351. this.fontType = getFontType(type, subtype);
  21352. // Transfer some properties again that could change during font conversion
  21353. this.fontMatrix = properties.fontMatrix;
  21354. this.widths = properties.widths;
  21355. this.defaultWidth = properties.defaultWidth;
  21356. this.encoding = properties.baseEncoding;
  21357. this.seacMap = properties.seacMap;
  21358. this.loading = true;
  21359. }
  21360. Font.getFontID = (function () {
  21361. var ID = 1;
  21362. return function Font_getFontID() {
  21363. return String(ID++);
  21364. };
  21365. })();
  21366. function int16(b0, b1) {
  21367. return (b0 << 8) + b1;
  21368. }
  21369. function int32(b0, b1, b2, b3) {
  21370. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  21371. }
  21372. function string16(value) {
  21373. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  21374. }
  21375. function safeString16(value) {
  21376. // clamp value to the 16-bit int range
  21377. value = (value > 0x7FFF ? 0x7FFF : (value < -0x8000 ? -0x8000 : value));
  21378. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  21379. }
  21380. function isTrueTypeFile(file) {
  21381. var header = file.peekBytes(4);
  21382. return readUint32(header, 0) === 0x00010000;
  21383. }
  21384. function isType1File(file) {
  21385. var header = file.peekBytes(2);
  21386. // All Type1 font programs must begin with the comment '%!' (0x25 + 0x21).
  21387. if (header[0] === 0x25 && header[1] === 0x21) {
  21388. return true;
  21389. }
  21390. // ... obviously some fonts violate that part of the specification,
  21391. // please refer to the comment in |Type1Font| below.
  21392. if (header[0] === 0x80 && header[1] === 0x01) { // pfb file header.
  21393. return true;
  21394. }
  21395. return false;
  21396. }
  21397. /**
  21398. * Helper function for |adjustMapping|.
  21399. * @return {boolean}
  21400. */
  21401. function isProblematicUnicodeLocation(code) {
  21402. // Using binary search to find a range start.
  21403. var i = 0, j = ProblematicCharRanges.length - 1;
  21404. while (i < j) {
  21405. var c = (i + j + 1) >> 1;
  21406. if (code < ProblematicCharRanges[c]) {
  21407. j = c - 1;
  21408. } else {
  21409. i = c;
  21410. }
  21411. }
  21412. // Even index means code in problematic range.
  21413. return !(i & 1);
  21414. }
  21415. /**
  21416. * Rebuilds the char code to glyph ID map by trying to replace the char codes
  21417. * with their unicode value. It also moves char codes that are in known
  21418. * problematic locations.
  21419. * @return {Object} Two properties:
  21420. * 'toFontChar' - maps original char codes(the value that will be read
  21421. * from commands such as show text) to the char codes that will be used in the
  21422. * font that we build
  21423. * 'charCodeToGlyphId' - maps the new font char codes to glyph ids
  21424. */
  21425. function adjustMapping(charCodeToGlyphId, properties) {
  21426. var toUnicode = properties.toUnicode;
  21427. var isSymbolic = !!(properties.flags & FontFlags.Symbolic);
  21428. var isIdentityUnicode =
  21429. properties.toUnicode instanceof IdentityToUnicodeMap;
  21430. var newMap = Object.create(null);
  21431. var toFontChar = [];
  21432. var usedFontCharCodes = [];
  21433. var nextAvailableFontCharCode = PRIVATE_USE_OFFSET_START;
  21434. for (var originalCharCode in charCodeToGlyphId) {
  21435. originalCharCode |= 0;
  21436. var glyphId = charCodeToGlyphId[originalCharCode];
  21437. var fontCharCode = originalCharCode;
  21438. // First try to map the value to a unicode position if a non identity map
  21439. // was created.
  21440. if (!isIdentityUnicode && toUnicode.has(originalCharCode)) {
  21441. var unicode = toUnicode.get(fontCharCode);
  21442. // TODO: Try to map ligatures to the correct spot.
  21443. if (unicode.length === 1) {
  21444. fontCharCode = unicode.charCodeAt(0);
  21445. }
  21446. }
  21447. // Try to move control characters, special characters and already mapped
  21448. // characters to the private use area since they will not be drawn by
  21449. // canvas if left in their current position. Also, move characters if the
  21450. // font was symbolic and there is only an identity unicode map since the
  21451. // characters probably aren't in the correct position (fixes an issue
  21452. // with firefox and thuluthfont).
  21453. if ((usedFontCharCodes[fontCharCode] !== undefined ||
  21454. isProblematicUnicodeLocation(fontCharCode) ||
  21455. (isSymbolic && isIdentityUnicode)) &&
  21456. nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END) { // Room left.
  21457. // Loop to try and find a free spot in the private use area.
  21458. do {
  21459. fontCharCode = nextAvailableFontCharCode++;
  21460. if (SKIP_PRIVATE_USE_RANGE_F000_TO_F01F && fontCharCode === 0xF000) {
  21461. fontCharCode = 0xF020;
  21462. nextAvailableFontCharCode = fontCharCode + 1;
  21463. }
  21464. } while (usedFontCharCodes[fontCharCode] !== undefined &&
  21465. nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END);
  21466. }
  21467. newMap[fontCharCode] = glyphId;
  21468. toFontChar[originalCharCode] = fontCharCode;
  21469. usedFontCharCodes[fontCharCode] = true;
  21470. }
  21471. return {
  21472. toFontChar: toFontChar,
  21473. charCodeToGlyphId: newMap,
  21474. nextAvailableFontCharCode: nextAvailableFontCharCode
  21475. };
  21476. }
  21477. function getRanges(glyphs) {
  21478. // Array.sort() sorts by characters, not numerically, so convert to an
  21479. // array of characters.
  21480. var codes = [];
  21481. for (var charCode in glyphs) {
  21482. codes.push({ fontCharCode: charCode | 0, glyphId: glyphs[charCode] });
  21483. }
  21484. codes.sort(function fontGetRangesSort(a, b) {
  21485. return a.fontCharCode - b.fontCharCode;
  21486. });
  21487. // Split the sorted codes into ranges.
  21488. var ranges = [];
  21489. var length = codes.length;
  21490. for (var n = 0; n < length; ) {
  21491. var start = codes[n].fontCharCode;
  21492. var codeIndices = [codes[n].glyphId];
  21493. ++n;
  21494. var end = start;
  21495. while (n < length && end + 1 === codes[n].fontCharCode) {
  21496. codeIndices.push(codes[n].glyphId);
  21497. ++end;
  21498. ++n;
  21499. if (end === 0xFFFF) {
  21500. break;
  21501. }
  21502. }
  21503. ranges.push([start, end, codeIndices]);
  21504. }
  21505. return ranges;
  21506. }
  21507. function createCmapTable(glyphs) {
  21508. var ranges = getRanges(glyphs);
  21509. var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1;
  21510. var cmap = '\x00\x00' + // version
  21511. string16(numTables) + // numTables
  21512. '\x00\x03' + // platformID
  21513. '\x00\x01' + // encodingID
  21514. string32(4 + numTables * 8); // start of the table record
  21515. var i, ii, j, jj;
  21516. for (i = ranges.length - 1; i >= 0; --i) {
  21517. if (ranges[i][0] <= 0xFFFF) { break; }
  21518. }
  21519. var bmpLength = i + 1;
  21520. if (ranges[i][0] < 0xFFFF && ranges[i][1] === 0xFFFF) {
  21521. ranges[i][1] = 0xFFFE;
  21522. }
  21523. var trailingRangesCount = ranges[i][1] < 0xFFFF ? 1 : 0;
  21524. var segCount = bmpLength + trailingRangesCount;
  21525. var searchParams = OpenTypeFileBuilder.getSearchParams(segCount, 2);
  21526. // Fill up the 4 parallel arrays describing the segments.
  21527. var startCount = '';
  21528. var endCount = '';
  21529. var idDeltas = '';
  21530. var idRangeOffsets = '';
  21531. var glyphsIds = '';
  21532. var bias = 0;
  21533. var range, start, end, codes;
  21534. for (i = 0, ii = bmpLength; i < ii; i++) {
  21535. range = ranges[i];
  21536. start = range[0];
  21537. end = range[1];
  21538. startCount += string16(start);
  21539. endCount += string16(end);
  21540. codes = range[2];
  21541. var contiguous = true;
  21542. for (j = 1, jj = codes.length; j < jj; ++j) {
  21543. if (codes[j] !== codes[j - 1] + 1) {
  21544. contiguous = false;
  21545. break;
  21546. }
  21547. }
  21548. if (!contiguous) {
  21549. var offset = (segCount - i) * 2 + bias * 2;
  21550. bias += (end - start + 1);
  21551. idDeltas += string16(0);
  21552. idRangeOffsets += string16(offset);
  21553. for (j = 0, jj = codes.length; j < jj; ++j) {
  21554. glyphsIds += string16(codes[j]);
  21555. }
  21556. } else {
  21557. var startCode = codes[0];
  21558. idDeltas += string16((startCode - start) & 0xFFFF);
  21559. idRangeOffsets += string16(0);
  21560. }
  21561. }
  21562. if (trailingRangesCount > 0) {
  21563. endCount += '\xFF\xFF';
  21564. startCount += '\xFF\xFF';
  21565. idDeltas += '\x00\x01';
  21566. idRangeOffsets += '\x00\x00';
  21567. }
  21568. var format314 = '\x00\x00' + // language
  21569. string16(2 * segCount) +
  21570. string16(searchParams.range) +
  21571. string16(searchParams.entry) +
  21572. string16(searchParams.rangeShift) +
  21573. endCount + '\x00\x00' + startCount +
  21574. idDeltas + idRangeOffsets + glyphsIds;
  21575. var format31012 = '';
  21576. var header31012 = '';
  21577. if (numTables > 1) {
  21578. cmap += '\x00\x03' + // platformID
  21579. '\x00\x0A' + // encodingID
  21580. string32(4 + numTables * 8 +
  21581. 4 + format314.length); // start of the table record
  21582. format31012 = '';
  21583. for (i = 0, ii = ranges.length; i < ii; i++) {
  21584. range = ranges[i];
  21585. start = range[0];
  21586. codes = range[2];
  21587. var code = codes[0];
  21588. for (j = 1, jj = codes.length; j < jj; ++j) {
  21589. if (codes[j] !== codes[j - 1] + 1) {
  21590. end = range[0] + j - 1;
  21591. format31012 += string32(start) + // startCharCode
  21592. string32(end) + // endCharCode
  21593. string32(code); // startGlyphID
  21594. start = end + 1;
  21595. code = codes[j];
  21596. }
  21597. }
  21598. format31012 += string32(start) + // startCharCode
  21599. string32(range[1]) + // endCharCode
  21600. string32(code); // startGlyphID
  21601. }
  21602. header31012 = '\x00\x0C' + // format
  21603. '\x00\x00' + // reserved
  21604. string32(format31012.length + 16) + // length
  21605. '\x00\x00\x00\x00' + // language
  21606. string32(format31012.length / 12); // nGroups
  21607. }
  21608. return cmap + '\x00\x04' + // format
  21609. string16(format314.length + 4) + // length
  21610. format314 + header31012 + format31012;
  21611. }
  21612. function validateOS2Table(os2) {
  21613. var stream = new Stream(os2.data);
  21614. var version = stream.getUint16();
  21615. // TODO verify all OS/2 tables fields, but currently we validate only those
  21616. // that give us issues
  21617. stream.getBytes(60); // skipping type, misc sizes, panose, unicode ranges
  21618. var selection = stream.getUint16();
  21619. if (version < 4 && (selection & 0x0300)) {
  21620. return false;
  21621. }
  21622. var firstChar = stream.getUint16();
  21623. var lastChar = stream.getUint16();
  21624. if (firstChar > lastChar) {
  21625. return false;
  21626. }
  21627. stream.getBytes(6); // skipping sTypoAscender/Descender/LineGap
  21628. var usWinAscent = stream.getUint16();
  21629. if (usWinAscent === 0) { // makes font unreadable by windows
  21630. return false;
  21631. }
  21632. // OS/2 appears to be valid, resetting some fields
  21633. os2.data[8] = os2.data[9] = 0; // IE rejects fonts if fsType != 0
  21634. return true;
  21635. }
  21636. function createOS2Table(properties, charstrings, override) {
  21637. override = override || {
  21638. unitsPerEm: 0,
  21639. yMax: 0,
  21640. yMin: 0,
  21641. ascent: 0,
  21642. descent: 0
  21643. };
  21644. var ulUnicodeRange1 = 0;
  21645. var ulUnicodeRange2 = 0;
  21646. var ulUnicodeRange3 = 0;
  21647. var ulUnicodeRange4 = 0;
  21648. var firstCharIndex = null;
  21649. var lastCharIndex = 0;
  21650. if (charstrings) {
  21651. for (var code in charstrings) {
  21652. code |= 0;
  21653. if (firstCharIndex > code || !firstCharIndex) {
  21654. firstCharIndex = code;
  21655. }
  21656. if (lastCharIndex < code) {
  21657. lastCharIndex = code;
  21658. }
  21659. var position = getUnicodeRangeFor(code);
  21660. if (position < 32) {
  21661. ulUnicodeRange1 |= 1 << position;
  21662. } else if (position < 64) {
  21663. ulUnicodeRange2 |= 1 << position - 32;
  21664. } else if (position < 96) {
  21665. ulUnicodeRange3 |= 1 << position - 64;
  21666. } else if (position < 123) {
  21667. ulUnicodeRange4 |= 1 << position - 96;
  21668. } else {
  21669. error('Unicode ranges Bits > 123 are reserved for internal usage');
  21670. }
  21671. }
  21672. } else {
  21673. // TODO
  21674. firstCharIndex = 0;
  21675. lastCharIndex = 255;
  21676. }
  21677. var bbox = properties.bbox || [0, 0, 0, 0];
  21678. var unitsPerEm = (override.unitsPerEm ||
  21679. 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0]);
  21680. // if the font units differ to the PDF glyph space units
  21681. // then scale up the values
  21682. var scale = (properties.ascentScaled ? 1.0 :
  21683. unitsPerEm / PDF_GLYPH_SPACE_UNITS);
  21684. var typoAscent = (override.ascent ||
  21685. Math.round(scale * (properties.ascent || bbox[3])));
  21686. var typoDescent = (override.descent ||
  21687. Math.round(scale * (properties.descent || bbox[1])));
  21688. if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
  21689. typoDescent = -typoDescent; // fixing incorrect descent
  21690. }
  21691. var winAscent = override.yMax || typoAscent;
  21692. var winDescent = -override.yMin || -typoDescent;
  21693. return '\x00\x03' + // version
  21694. '\x02\x24' + // xAvgCharWidth
  21695. '\x01\xF4' + // usWeightClass
  21696. '\x00\x05' + // usWidthClass
  21697. '\x00\x00' + // fstype (0 to let the font loads via font-face on IE)
  21698. '\x02\x8A' + // ySubscriptXSize
  21699. '\x02\xBB' + // ySubscriptYSize
  21700. '\x00\x00' + // ySubscriptXOffset
  21701. '\x00\x8C' + // ySubscriptYOffset
  21702. '\x02\x8A' + // ySuperScriptXSize
  21703. '\x02\xBB' + // ySuperScriptYSize
  21704. '\x00\x00' + // ySuperScriptXOffset
  21705. '\x01\xDF' + // ySuperScriptYOffset
  21706. '\x00\x31' + // yStrikeOutSize
  21707. '\x01\x02' + // yStrikeOutPosition
  21708. '\x00\x00' + // sFamilyClass
  21709. '\x00\x00\x06' +
  21710. String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) +
  21711. '\x00\x00\x00\x00\x00\x00' + // Panose
  21712. string32(ulUnicodeRange1) + // ulUnicodeRange1 (Bits 0-31)
  21713. string32(ulUnicodeRange2) + // ulUnicodeRange2 (Bits 32-63)
  21714. string32(ulUnicodeRange3) + // ulUnicodeRange3 (Bits 64-95)
  21715. string32(ulUnicodeRange4) + // ulUnicodeRange4 (Bits 96-127)
  21716. '\x2A\x32\x31\x2A' + // achVendID
  21717. string16(properties.italicAngle ? 1 : 0) + // fsSelection
  21718. string16(firstCharIndex ||
  21719. properties.firstChar) + // usFirstCharIndex
  21720. string16(lastCharIndex || properties.lastChar) + // usLastCharIndex
  21721. string16(typoAscent) + // sTypoAscender
  21722. string16(typoDescent) + // sTypoDescender
  21723. '\x00\x64' + // sTypoLineGap (7%-10% of the unitsPerEM value)
  21724. string16(winAscent) + // usWinAscent
  21725. string16(winDescent) + // usWinDescent
  21726. '\x00\x00\x00\x00' + // ulCodePageRange1 (Bits 0-31)
  21727. '\x00\x00\x00\x00' + // ulCodePageRange2 (Bits 32-63)
  21728. string16(properties.xHeight) + // sxHeight
  21729. string16(properties.capHeight) + // sCapHeight
  21730. string16(0) + // usDefaultChar
  21731. string16(firstCharIndex || properties.firstChar) + // usBreakChar
  21732. '\x00\x03'; // usMaxContext
  21733. }
  21734. function createPostTable(properties) {
  21735. var angle = Math.floor(properties.italicAngle * (Math.pow(2, 16)));
  21736. return ('\x00\x03\x00\x00' + // Version number
  21737. string32(angle) + // italicAngle
  21738. '\x00\x00' + // underlinePosition
  21739. '\x00\x00' + // underlineThickness
  21740. string32(properties.fixedPitch) + // isFixedPitch
  21741. '\x00\x00\x00\x00' + // minMemType42
  21742. '\x00\x00\x00\x00' + // maxMemType42
  21743. '\x00\x00\x00\x00' + // minMemType1
  21744. '\x00\x00\x00\x00'); // maxMemType1
  21745. }
  21746. function createNameTable(name, proto) {
  21747. if (!proto) {
  21748. proto = [[], []]; // no strings and unicode strings
  21749. }
  21750. var strings = [
  21751. proto[0][0] || 'Original licence', // 0.Copyright
  21752. proto[0][1] || name, // 1.Font family
  21753. proto[0][2] || 'Unknown', // 2.Font subfamily (font weight)
  21754. proto[0][3] || 'uniqueID', // 3.Unique ID
  21755. proto[0][4] || name, // 4.Full font name
  21756. proto[0][5] || 'Version 0.11', // 5.Version
  21757. proto[0][6] || '', // 6.Postscript name
  21758. proto[0][7] || 'Unknown', // 7.Trademark
  21759. proto[0][8] || 'Unknown', // 8.Manufacturer
  21760. proto[0][9] || 'Unknown' // 9.Designer
  21761. ];
  21762. // Mac want 1-byte per character strings while Windows want
  21763. // 2-bytes per character, so duplicate the names table
  21764. var stringsUnicode = [];
  21765. var i, ii, j, jj, str;
  21766. for (i = 0, ii = strings.length; i < ii; i++) {
  21767. str = proto[1][i] || strings[i];
  21768. var strBufUnicode = [];
  21769. for (j = 0, jj = str.length; j < jj; j++) {
  21770. strBufUnicode.push(string16(str.charCodeAt(j)));
  21771. }
  21772. stringsUnicode.push(strBufUnicode.join(''));
  21773. }
  21774. var names = [strings, stringsUnicode];
  21775. var platforms = ['\x00\x01', '\x00\x03'];
  21776. var encodings = ['\x00\x00', '\x00\x01'];
  21777. var languages = ['\x00\x00', '\x04\x09'];
  21778. var namesRecordCount = strings.length * platforms.length;
  21779. var nameTable =
  21780. '\x00\x00' + // format
  21781. string16(namesRecordCount) + // Number of names Record
  21782. string16(namesRecordCount * 12 + 6); // Storage
  21783. // Build the name records field
  21784. var strOffset = 0;
  21785. for (i = 0, ii = platforms.length; i < ii; i++) {
  21786. var strs = names[i];
  21787. for (j = 0, jj = strs.length; j < jj; j++) {
  21788. str = strs[j];
  21789. var nameRecord =
  21790. platforms[i] + // platform ID
  21791. encodings[i] + // encoding ID
  21792. languages[i] + // language ID
  21793. string16(j) + // name ID
  21794. string16(str.length) +
  21795. string16(strOffset);
  21796. nameTable += nameRecord;
  21797. strOffset += str.length;
  21798. }
  21799. }
  21800. nameTable += strings.join('') + stringsUnicode.join('');
  21801. return nameTable;
  21802. }
  21803. Font.prototype = {
  21804. name: null,
  21805. font: null,
  21806. mimetype: null,
  21807. encoding: null,
  21808. get renderer() {
  21809. var renderer = FontRendererFactory.create(this);
  21810. return shadow(this, 'renderer', renderer);
  21811. },
  21812. exportData: function Font_exportData() {
  21813. var data = {};
  21814. for (var i in this) {
  21815. if (this.hasOwnProperty(i)) {
  21816. data[i] = this[i];
  21817. }
  21818. }
  21819. return data;
  21820. },
  21821. checkAndRepair: function Font_checkAndRepair(name, font, properties) {
  21822. function readTableEntry(file) {
  21823. var tag = bytesToString(file.getBytes(4));
  21824. var checksum = file.getInt32();
  21825. var offset = file.getInt32() >>> 0;
  21826. var length = file.getInt32() >>> 0;
  21827. // Read the table associated data
  21828. var previousPosition = file.pos;
  21829. file.pos = file.start ? file.start : 0;
  21830. file.skip(offset);
  21831. var data = file.getBytes(length);
  21832. file.pos = previousPosition;
  21833. if (tag === 'head') {
  21834. // clearing checksum adjustment
  21835. data[8] = data[9] = data[10] = data[11] = 0;
  21836. data[17] |= 0x20; //Set font optimized for cleartype flag
  21837. }
  21838. return {
  21839. tag: tag,
  21840. checksum: checksum,
  21841. length: length,
  21842. offset: offset,
  21843. data: data
  21844. };
  21845. }
  21846. function readOpenTypeHeader(ttf) {
  21847. return {
  21848. version: bytesToString(ttf.getBytes(4)),
  21849. numTables: ttf.getUint16(),
  21850. searchRange: ttf.getUint16(),
  21851. entrySelector: ttf.getUint16(),
  21852. rangeShift: ttf.getUint16()
  21853. };
  21854. }
  21855. /**
  21856. * Read the appropriate subtable from the cmap according to 9.6.6.4 from
  21857. * PDF spec
  21858. */
  21859. function readCmapTable(cmap, font, isSymbolicFont) {
  21860. var segment;
  21861. var start = (font.start ? font.start : 0) + cmap.offset;
  21862. font.pos = start;
  21863. var version = font.getUint16();
  21864. var numTables = font.getUint16();
  21865. var potentialTable;
  21866. var canBreak = false;
  21867. // There's an order of preference in terms of which cmap subtable to
  21868. // use:
  21869. // - non-symbolic fonts the preference is a 3,1 table then a 1,0 table
  21870. // - symbolic fonts the preference is a 3,0 table then a 1,0 table
  21871. // The following takes advantage of the fact that the tables are sorted
  21872. // to work.
  21873. for (var i = 0; i < numTables; i++) {
  21874. var platformId = font.getUint16();
  21875. var encodingId = font.getUint16();
  21876. var offset = font.getInt32() >>> 0;
  21877. var useTable = false;
  21878. if (platformId === 0 && encodingId === 0) {
  21879. useTable = true;
  21880. // Continue the loop since there still may be a higher priority
  21881. // table.
  21882. } else if (platformId === 1 && encodingId === 0) {
  21883. useTable = true;
  21884. // Continue the loop since there still may be a higher priority
  21885. // table.
  21886. } else if (platformId === 3 && encodingId === 1 &&
  21887. (!isSymbolicFont || !potentialTable)) {
  21888. useTable = true;
  21889. if (!isSymbolicFont) {
  21890. canBreak = true;
  21891. }
  21892. } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
  21893. useTable = true;
  21894. canBreak = true;
  21895. }
  21896. if (useTable) {
  21897. potentialTable = {
  21898. platformId: platformId,
  21899. encodingId: encodingId,
  21900. offset: offset
  21901. };
  21902. }
  21903. if (canBreak) {
  21904. break;
  21905. }
  21906. }
  21907. if (potentialTable) {
  21908. font.pos = start + potentialTable.offset;
  21909. }
  21910. if (!potentialTable || font.peekByte() === -1) {
  21911. warn('Could not find a preferred cmap table.');
  21912. return {
  21913. platformId: -1,
  21914. encodingId: -1,
  21915. mappings: [],
  21916. hasShortCmap: false
  21917. };
  21918. }
  21919. var format = font.getUint16();
  21920. var length = font.getUint16();
  21921. var language = font.getUint16();
  21922. var hasShortCmap = false;
  21923. var mappings = [];
  21924. var j, glyphId;
  21925. // TODO(mack): refactor this cmap subtable reading logic out
  21926. if (format === 0) {
  21927. for (j = 0; j < 256; j++) {
  21928. var index = font.getByte();
  21929. if (!index) {
  21930. continue;
  21931. }
  21932. mappings.push({
  21933. charCode: j,
  21934. glyphId: index
  21935. });
  21936. }
  21937. hasShortCmap = true;
  21938. } else if (format === 4) {
  21939. // re-creating the table in format 4 since the encoding
  21940. // might be changed
  21941. var segCount = (font.getUint16() >> 1);
  21942. font.getBytes(6); // skipping range fields
  21943. var segIndex, segments = [];
  21944. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21945. segments.push({ end: font.getUint16() });
  21946. }
  21947. font.getUint16();
  21948. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21949. segments[segIndex].start = font.getUint16();
  21950. }
  21951. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21952. segments[segIndex].delta = font.getUint16();
  21953. }
  21954. var offsetsCount = 0;
  21955. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21956. segment = segments[segIndex];
  21957. var rangeOffset = font.getUint16();
  21958. if (!rangeOffset) {
  21959. segment.offsetIndex = -1;
  21960. continue;
  21961. }
  21962. var offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
  21963. segment.offsetIndex = offsetIndex;
  21964. offsetsCount = Math.max(offsetsCount, offsetIndex +
  21965. segment.end - segment.start + 1);
  21966. }
  21967. var offsets = [];
  21968. for (j = 0; j < offsetsCount; j++) {
  21969. offsets.push(font.getUint16());
  21970. }
  21971. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21972. segment = segments[segIndex];
  21973. start = segment.start;
  21974. var end = segment.end;
  21975. var delta = segment.delta;
  21976. offsetIndex = segment.offsetIndex;
  21977. for (j = start; j <= end; j++) {
  21978. if (j === 0xFFFF) {
  21979. continue;
  21980. }
  21981. glyphId = (offsetIndex < 0 ?
  21982. j : offsets[offsetIndex + j - start]);
  21983. glyphId = (glyphId + delta) & 0xFFFF;
  21984. if (glyphId === 0) {
  21985. continue;
  21986. }
  21987. mappings.push({
  21988. charCode: j,
  21989. glyphId: glyphId
  21990. });
  21991. }
  21992. }
  21993. } else if (format === 6) {
  21994. // Format 6 is a 2-bytes dense mapping, which means the font data
  21995. // lives glue together even if they are pretty far in the unicode
  21996. // table. (This looks weird, so I can have missed something), this
  21997. // works on Linux but seems to fails on Mac so let's rewrite the
  21998. // cmap table to a 3-1-4 style
  21999. var firstCode = font.getUint16();
  22000. var entryCount = font.getUint16();
  22001. for (j = 0; j < entryCount; j++) {
  22002. glyphId = font.getUint16();
  22003. var charCode = firstCode + j;
  22004. mappings.push({
  22005. charCode: charCode,
  22006. glyphId: glyphId
  22007. });
  22008. }
  22009. } else {
  22010. error('cmap table has unsupported format: ' + format);
  22011. }
  22012. // removing duplicate entries
  22013. mappings.sort(function (a, b) {
  22014. return a.charCode - b.charCode;
  22015. });
  22016. for (i = 1; i < mappings.length; i++) {
  22017. if (mappings[i - 1].charCode === mappings[i].charCode) {
  22018. mappings.splice(i, 1);
  22019. i--;
  22020. }
  22021. }
  22022. return {
  22023. platformId: potentialTable.platformId,
  22024. encodingId: potentialTable.encodingId,
  22025. mappings: mappings,
  22026. hasShortCmap: hasShortCmap
  22027. };
  22028. }
  22029. function sanitizeMetrics(font, header, metrics, numGlyphs) {
  22030. if (!header) {
  22031. if (metrics) {
  22032. metrics.data = null;
  22033. }
  22034. return;
  22035. }
  22036. font.pos = (font.start ? font.start : 0) + header.offset;
  22037. font.pos += header.length - 2;
  22038. var numOfMetrics = font.getUint16();
  22039. if (numOfMetrics > numGlyphs) {
  22040. info('The numOfMetrics (' + numOfMetrics + ') should not be ' +
  22041. 'greater than the numGlyphs (' + numGlyphs + ')');
  22042. // Reduce numOfMetrics if it is greater than numGlyphs
  22043. numOfMetrics = numGlyphs;
  22044. header.data[34] = (numOfMetrics & 0xff00) >> 8;
  22045. header.data[35] = numOfMetrics & 0x00ff;
  22046. }
  22047. var numOfSidebearings = numGlyphs - numOfMetrics;
  22048. var numMissing = numOfSidebearings -
  22049. ((metrics.length - numOfMetrics * 4) >> 1);
  22050. if (numMissing > 0) {
  22051. // For each missing glyph, we set both the width and lsb to 0 (zero).
  22052. // Since we need to add two properties for each glyph, this explains
  22053. // the use of |numMissing * 2| when initializing the typed array.
  22054. var entries = new Uint8Array(metrics.length + numMissing * 2);
  22055. entries.set(metrics.data);
  22056. metrics.data = entries;
  22057. }
  22058. }
  22059. function sanitizeGlyph(source, sourceStart, sourceEnd, dest, destStart,
  22060. hintsValid) {
  22061. if (sourceEnd - sourceStart <= 12) {
  22062. // glyph with data less than 12 is invalid one
  22063. return 0;
  22064. }
  22065. var glyf = source.subarray(sourceStart, sourceEnd);
  22066. var contoursCount = (glyf[0] << 8) | glyf[1];
  22067. if (contoursCount & 0x8000) {
  22068. // complex glyph, writing as is
  22069. dest.set(glyf, destStart);
  22070. return glyf.length;
  22071. }
  22072. var i, j = 10, flagsCount = 0;
  22073. for (i = 0; i < contoursCount; i++) {
  22074. var endPoint = (glyf[j] << 8) | glyf[j + 1];
  22075. flagsCount = endPoint + 1;
  22076. j += 2;
  22077. }
  22078. // skipping instructions
  22079. var instructionsStart = j;
  22080. var instructionsLength = (glyf[j] << 8) | glyf[j + 1];
  22081. j += 2 + instructionsLength;
  22082. var instructionsEnd = j;
  22083. // validating flags
  22084. var coordinatesLength = 0;
  22085. for (i = 0; i < flagsCount; i++) {
  22086. var flag = glyf[j++];
  22087. if (flag & 0xC0) {
  22088. // reserved flags must be zero, cleaning up
  22089. glyf[j - 1] = flag & 0x3F;
  22090. }
  22091. var xyLength = ((flag & 2) ? 1 : (flag & 16) ? 0 : 2) +
  22092. ((flag & 4) ? 1 : (flag & 32) ? 0 : 2);
  22093. coordinatesLength += xyLength;
  22094. if (flag & 8) {
  22095. var repeat = glyf[j++];
  22096. i += repeat;
  22097. coordinatesLength += repeat * xyLength;
  22098. }
  22099. }
  22100. // glyph without coordinates will be rejected
  22101. if (coordinatesLength === 0) {
  22102. return 0;
  22103. }
  22104. var glyphDataLength = j + coordinatesLength;
  22105. if (glyphDataLength > glyf.length) {
  22106. // not enough data for coordinates
  22107. return 0;
  22108. }
  22109. if (!hintsValid && instructionsLength > 0) {
  22110. dest.set(glyf.subarray(0, instructionsStart), destStart);
  22111. dest.set([0, 0], destStart + instructionsStart);
  22112. dest.set(glyf.subarray(instructionsEnd, glyphDataLength),
  22113. destStart + instructionsStart + 2);
  22114. glyphDataLength -= instructionsLength;
  22115. if (glyf.length - glyphDataLength > 3) {
  22116. glyphDataLength = (glyphDataLength + 3) & ~3;
  22117. }
  22118. return glyphDataLength;
  22119. }
  22120. if (glyf.length - glyphDataLength > 3) {
  22121. // truncating and aligning to 4 bytes the long glyph data
  22122. glyphDataLength = (glyphDataLength + 3) & ~3;
  22123. dest.set(glyf.subarray(0, glyphDataLength), destStart);
  22124. return glyphDataLength;
  22125. }
  22126. // glyph data is fine
  22127. dest.set(glyf, destStart);
  22128. return glyf.length;
  22129. }
  22130. function sanitizeHead(head, numGlyphs, locaLength) {
  22131. var data = head.data;
  22132. // Validate version:
  22133. // Should always be 0x00010000
  22134. var version = int32(data[0], data[1], data[2], data[3]);
  22135. if (version >> 16 !== 1) {
  22136. info('Attempting to fix invalid version in head table: ' + version);
  22137. data[0] = 0;
  22138. data[1] = 1;
  22139. data[2] = 0;
  22140. data[3] = 0;
  22141. }
  22142. var indexToLocFormat = int16(data[50], data[51]);
  22143. if (indexToLocFormat < 0 || indexToLocFormat > 1) {
  22144. info('Attempting to fix invalid indexToLocFormat in head table: ' +
  22145. indexToLocFormat);
  22146. // The value of indexToLocFormat should be 0 if the loca table
  22147. // consists of short offsets, and should be 1 if the loca table
  22148. // consists of long offsets.
  22149. //
  22150. // The number of entries in the loca table should be numGlyphs + 1.
  22151. //
  22152. // Using this information, we can work backwards to deduce if the
  22153. // size of each offset in the loca table, and thus figure out the
  22154. // appropriate value for indexToLocFormat.
  22155. var numGlyphsPlusOne = numGlyphs + 1;
  22156. if (locaLength === numGlyphsPlusOne << 1) {
  22157. // 0x0000 indicates the loca table consists of short offsets
  22158. data[50] = 0;
  22159. data[51] = 0;
  22160. } else if (locaLength === numGlyphsPlusOne << 2) {
  22161. // 0x0001 indicates the loca table consists of long offsets
  22162. data[50] = 0;
  22163. data[51] = 1;
  22164. } else {
  22165. warn('Could not fix indexToLocFormat: ' + indexToLocFormat);
  22166. }
  22167. }
  22168. }
  22169. function sanitizeGlyphLocations(loca, glyf, numGlyphs,
  22170. isGlyphLocationsLong, hintsValid,
  22171. dupFirstEntry) {
  22172. var itemSize, itemDecode, itemEncode;
  22173. if (isGlyphLocationsLong) {
  22174. itemSize = 4;
  22175. itemDecode = function fontItemDecodeLong(data, offset) {
  22176. return (data[offset] << 24) | (data[offset + 1] << 16) |
  22177. (data[offset + 2] << 8) | data[offset + 3];
  22178. };
  22179. itemEncode = function fontItemEncodeLong(data, offset, value) {
  22180. data[offset] = (value >>> 24) & 0xFF;
  22181. data[offset + 1] = (value >> 16) & 0xFF;
  22182. data[offset + 2] = (value >> 8) & 0xFF;
  22183. data[offset + 3] = value & 0xFF;
  22184. };
  22185. } else {
  22186. itemSize = 2;
  22187. itemDecode = function fontItemDecode(data, offset) {
  22188. return (data[offset] << 9) | (data[offset + 1] << 1);
  22189. };
  22190. itemEncode = function fontItemEncode(data, offset, value) {
  22191. data[offset] = (value >> 9) & 0xFF;
  22192. data[offset + 1] = (value >> 1) & 0xFF;
  22193. };
  22194. }
  22195. var locaData = loca.data;
  22196. var locaDataSize = itemSize * (1 + numGlyphs);
  22197. // is loca.data too short or long?
  22198. if (locaData.length !== locaDataSize) {
  22199. locaData = new Uint8Array(locaDataSize);
  22200. locaData.set(loca.data.subarray(0, locaDataSize));
  22201. loca.data = locaData;
  22202. }
  22203. // removing the invalid glyphs
  22204. var oldGlyfData = glyf.data;
  22205. var oldGlyfDataLength = oldGlyfData.length;
  22206. var newGlyfData = new Uint8Array(oldGlyfDataLength);
  22207. var startOffset = itemDecode(locaData, 0);
  22208. var writeOffset = 0;
  22209. var missingGlyphData = {};
  22210. itemEncode(locaData, 0, writeOffset);
  22211. var i, j;
  22212. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  22213. var endOffset = itemDecode(locaData, j);
  22214. if (endOffset > oldGlyfDataLength &&
  22215. ((oldGlyfDataLength + 3) & ~3) === endOffset) {
  22216. // Aspose breaks fonts by aligning the glyphs to the qword, but not
  22217. // the glyf table size, which makes last glyph out of range.
  22218. endOffset = oldGlyfDataLength;
  22219. }
  22220. if (endOffset > oldGlyfDataLength) {
  22221. // glyph end offset points outside glyf data, rejecting the glyph
  22222. itemEncode(locaData, j, writeOffset);
  22223. startOffset = endOffset;
  22224. continue;
  22225. }
  22226. if (startOffset === endOffset) {
  22227. missingGlyphData[i] = true;
  22228. }
  22229. var newLength = sanitizeGlyph(oldGlyfData, startOffset, endOffset,
  22230. newGlyfData, writeOffset, hintsValid);
  22231. writeOffset += newLength;
  22232. itemEncode(locaData, j, writeOffset);
  22233. startOffset = endOffset;
  22234. }
  22235. if (writeOffset === 0) {
  22236. // glyf table cannot be empty -- redoing the glyf and loca tables
  22237. // to have single glyph with one point
  22238. var simpleGlyph = new Uint8Array(
  22239. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);
  22240. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  22241. itemEncode(locaData, j, simpleGlyph.length);
  22242. }
  22243. glyf.data = simpleGlyph;
  22244. return missingGlyphData;
  22245. }
  22246. if (dupFirstEntry) {
  22247. var firstEntryLength = itemDecode(locaData, itemSize);
  22248. if (newGlyfData.length > firstEntryLength + writeOffset) {
  22249. glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);
  22250. } else {
  22251. glyf.data = new Uint8Array(firstEntryLength + writeOffset);
  22252. glyf.data.set(newGlyfData.subarray(0, writeOffset));
  22253. }
  22254. glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);
  22255. itemEncode(loca.data, locaData.length - itemSize,
  22256. writeOffset + firstEntryLength);
  22257. } else {
  22258. glyf.data = newGlyfData.subarray(0, writeOffset);
  22259. }
  22260. return missingGlyphData;
  22261. }
  22262. function readPostScriptTable(post, properties, maxpNumGlyphs) {
  22263. var start = (font.start ? font.start : 0) + post.offset;
  22264. font.pos = start;
  22265. var length = post.length, end = start + length;
  22266. var version = font.getInt32();
  22267. // skip rest to the tables
  22268. font.getBytes(28);
  22269. var glyphNames;
  22270. var valid = true;
  22271. var i;
  22272. switch (version) {
  22273. case 0x00010000:
  22274. glyphNames = MacStandardGlyphOrdering;
  22275. break;
  22276. case 0x00020000:
  22277. var numGlyphs = font.getUint16();
  22278. if (numGlyphs !== maxpNumGlyphs) {
  22279. valid = false;
  22280. break;
  22281. }
  22282. var glyphNameIndexes = [];
  22283. for (i = 0; i < numGlyphs; ++i) {
  22284. var index = font.getUint16();
  22285. if (index >= 32768) {
  22286. valid = false;
  22287. break;
  22288. }
  22289. glyphNameIndexes.push(index);
  22290. }
  22291. if (!valid) {
  22292. break;
  22293. }
  22294. var customNames = [];
  22295. var strBuf = [];
  22296. while (font.pos < end) {
  22297. var stringLength = font.getByte();
  22298. strBuf.length = stringLength;
  22299. for (i = 0; i < stringLength; ++i) {
  22300. strBuf[i] = String.fromCharCode(font.getByte());
  22301. }
  22302. customNames.push(strBuf.join(''));
  22303. }
  22304. glyphNames = [];
  22305. for (i = 0; i < numGlyphs; ++i) {
  22306. var j = glyphNameIndexes[i];
  22307. if (j < 258) {
  22308. glyphNames.push(MacStandardGlyphOrdering[j]);
  22309. continue;
  22310. }
  22311. glyphNames.push(customNames[j - 258]);
  22312. }
  22313. break;
  22314. case 0x00030000:
  22315. break;
  22316. default:
  22317. warn('Unknown/unsupported post table version ' + version);
  22318. valid = false;
  22319. if (properties.defaultEncoding) {
  22320. glyphNames = properties.defaultEncoding;
  22321. }
  22322. break;
  22323. }
  22324. properties.glyphNames = glyphNames;
  22325. return valid;
  22326. }
  22327. function readNameTable(nameTable) {
  22328. var start = (font.start ? font.start : 0) + nameTable.offset;
  22329. font.pos = start;
  22330. var names = [[], []];
  22331. var length = nameTable.length, end = start + length;
  22332. var format = font.getUint16();
  22333. var FORMAT_0_HEADER_LENGTH = 6;
  22334. if (format !== 0 || length < FORMAT_0_HEADER_LENGTH) {
  22335. // unsupported name table format or table "too" small
  22336. return names;
  22337. }
  22338. var numRecords = font.getUint16();
  22339. var stringsStart = font.getUint16();
  22340. var records = [];
  22341. var NAME_RECORD_LENGTH = 12;
  22342. var i, ii;
  22343. for (i = 0; i < numRecords &&
  22344. font.pos + NAME_RECORD_LENGTH <= end; i++) {
  22345. var r = {
  22346. platform: font.getUint16(),
  22347. encoding: font.getUint16(),
  22348. language: font.getUint16(),
  22349. name: font.getUint16(),
  22350. length: font.getUint16(),
  22351. offset: font.getUint16()
  22352. };
  22353. // using only Macintosh and Windows platform/encoding names
  22354. if ((r.platform === 1 && r.encoding === 0 && r.language === 0) ||
  22355. (r.platform === 3 && r.encoding === 1 && r.language === 0x409)) {
  22356. records.push(r);
  22357. }
  22358. }
  22359. for (i = 0, ii = records.length; i < ii; i++) {
  22360. var record = records[i];
  22361. var pos = start + stringsStart + record.offset;
  22362. if (pos + record.length > end) {
  22363. continue; // outside of name table, ignoring
  22364. }
  22365. font.pos = pos;
  22366. var nameIndex = record.name;
  22367. if (record.encoding) {
  22368. // unicode
  22369. var str = '';
  22370. for (var j = 0, jj = record.length; j < jj; j += 2) {
  22371. str += String.fromCharCode(font.getUint16());
  22372. }
  22373. names[1][nameIndex] = str;
  22374. } else {
  22375. names[0][nameIndex] = bytesToString(font.getBytes(record.length));
  22376. }
  22377. }
  22378. return names;
  22379. }
  22380. var TTOpsStackDeltas = [
  22381. 0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, 0, 0, -2, -5,
  22382. -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, -1, -1,
  22383. 1, -1, -999, 0, 1, 0, -1, -2, 0, -1, -2, -1, -1, 0, -1, -1,
  22384. 0, 0, -999, -999, -1, -1, -1, -1, -2, -999, -2, -2, -999, 0, -2, -2,
  22385. 0, 0, -2, 0, -2, 0, 0, 0, -2, -1, -1, 1, 1, 0, 0, -1,
  22386. -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, -999, -1, -1,
  22387. -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22388. -2, -999, -999, -999, -999, -999, -1, -1, -2, -2, 0, 0, 0, 0, -1, -1,
  22389. -999, -2, -2, 0, 0, -1, -2, -2, 0, 0, 0, -1, -1, -1, -2];
  22390. // 0xC0-DF == -1 and 0xE0-FF == -2
  22391. function sanitizeTTProgram(table, ttContext) {
  22392. var data = table.data;
  22393. var i = 0, j, n, b, funcId, pc, lastEndf = 0, lastDeff = 0;
  22394. var stack = [];
  22395. var callstack = [];
  22396. var functionsCalled = [];
  22397. var tooComplexToFollowFunctions =
  22398. ttContext.tooComplexToFollowFunctions;
  22399. var inFDEF = false, ifLevel = 0, inELSE = 0;
  22400. for (var ii = data.length; i < ii;) {
  22401. var op = data[i++];
  22402. // The TrueType instruction set docs can be found at
  22403. // https://developer.apple.com/fonts/TTRefMan/RM05/Chap5.html
  22404. if (op === 0x40) { // NPUSHB - pushes n bytes
  22405. n = data[i++];
  22406. if (inFDEF || inELSE) {
  22407. i += n;
  22408. } else {
  22409. for (j = 0; j < n; j++) {
  22410. stack.push(data[i++]);
  22411. }
  22412. }
  22413. } else if (op === 0x41) { // NPUSHW - pushes n words
  22414. n = data[i++];
  22415. if (inFDEF || inELSE) {
  22416. i += n * 2;
  22417. } else {
  22418. for (j = 0; j < n; j++) {
  22419. b = data[i++];
  22420. stack.push((b << 8) | data[i++]);
  22421. }
  22422. }
  22423. } else if ((op & 0xF8) === 0xB0) { // PUSHB - pushes bytes
  22424. n = op - 0xB0 + 1;
  22425. if (inFDEF || inELSE) {
  22426. i += n;
  22427. } else {
  22428. for (j = 0; j < n; j++) {
  22429. stack.push(data[i++]);
  22430. }
  22431. }
  22432. } else if ((op & 0xF8) === 0xB8) { // PUSHW - pushes words
  22433. n = op - 0xB8 + 1;
  22434. if (inFDEF || inELSE) {
  22435. i += n * 2;
  22436. } else {
  22437. for (j = 0; j < n; j++) {
  22438. b = data[i++];
  22439. stack.push((b << 8) | data[i++]);
  22440. }
  22441. }
  22442. } else if (op === 0x2B && !tooComplexToFollowFunctions) { // CALL
  22443. if (!inFDEF && !inELSE) {
  22444. // collecting inforamtion about which functions are used
  22445. funcId = stack[stack.length - 1];
  22446. ttContext.functionsUsed[funcId] = true;
  22447. if (funcId in ttContext.functionsStackDeltas) {
  22448. stack.length += ttContext.functionsStackDeltas[funcId];
  22449. } else if (funcId in ttContext.functionsDefined &&
  22450. functionsCalled.indexOf(funcId) < 0) {
  22451. callstack.push({data: data, i: i, stackTop: stack.length - 1});
  22452. functionsCalled.push(funcId);
  22453. pc = ttContext.functionsDefined[funcId];
  22454. if (!pc) {
  22455. warn('TT: CALL non-existent function');
  22456. ttContext.hintsValid = false;
  22457. return;
  22458. }
  22459. data = pc.data;
  22460. i = pc.i;
  22461. }
  22462. }
  22463. } else if (op === 0x2C && !tooComplexToFollowFunctions) { // FDEF
  22464. if (inFDEF || inELSE) {
  22465. warn('TT: nested FDEFs not allowed');
  22466. tooComplexToFollowFunctions = true;
  22467. }
  22468. inFDEF = true;
  22469. // collecting inforamtion about which functions are defined
  22470. lastDeff = i;
  22471. funcId = stack.pop();
  22472. ttContext.functionsDefined[funcId] = {data: data, i: i};
  22473. } else if (op === 0x2D) { // ENDF - end of function
  22474. if (inFDEF) {
  22475. inFDEF = false;
  22476. lastEndf = i;
  22477. } else {
  22478. pc = callstack.pop();
  22479. if (!pc) {
  22480. warn('TT: ENDF bad stack');
  22481. ttContext.hintsValid = false;
  22482. return;
  22483. }
  22484. funcId = functionsCalled.pop();
  22485. data = pc.data;
  22486. i = pc.i;
  22487. ttContext.functionsStackDeltas[funcId] =
  22488. stack.length - pc.stackTop;
  22489. }
  22490. } else if (op === 0x89) { // IDEF - instruction definition
  22491. if (inFDEF || inELSE) {
  22492. warn('TT: nested IDEFs not allowed');
  22493. tooComplexToFollowFunctions = true;
  22494. }
  22495. inFDEF = true;
  22496. // recording it as a function to track ENDF
  22497. lastDeff = i;
  22498. } else if (op === 0x58) { // IF
  22499. ++ifLevel;
  22500. } else if (op === 0x1B) { // ELSE
  22501. inELSE = ifLevel;
  22502. } else if (op === 0x59) { // EIF
  22503. if (inELSE === ifLevel) {
  22504. inELSE = 0;
  22505. }
  22506. --ifLevel;
  22507. } else if (op === 0x1C) { // JMPR
  22508. if (!inFDEF && !inELSE) {
  22509. var offset = stack[stack.length - 1];
  22510. // only jumping forward to prevent infinite loop
  22511. if (offset > 0) {
  22512. i += offset - 1;
  22513. }
  22514. }
  22515. }
  22516. // Adjusting stack not extactly, but just enough to get function id
  22517. if (!inFDEF && !inELSE) {
  22518. var stackDelta = op <= 0x8E ? TTOpsStackDeltas[op] :
  22519. op >= 0xC0 && op <= 0xDF ? -1 : op >= 0xE0 ? -2 : 0;
  22520. if (op >= 0x71 && op <= 0x75) {
  22521. n = stack.pop();
  22522. if (n === n) {
  22523. stackDelta = -n * 2;
  22524. }
  22525. }
  22526. while (stackDelta < 0 && stack.length > 0) {
  22527. stack.pop();
  22528. stackDelta++;
  22529. }
  22530. while (stackDelta > 0) {
  22531. stack.push(NaN); // pushing any number into stack
  22532. stackDelta--;
  22533. }
  22534. }
  22535. }
  22536. ttContext.tooComplexToFollowFunctions = tooComplexToFollowFunctions;
  22537. var content = [data];
  22538. if (i > data.length) {
  22539. content.push(new Uint8Array(i - data.length));
  22540. }
  22541. if (lastDeff > lastEndf) {
  22542. warn('TT: complementing a missing function tail');
  22543. // new function definition started, but not finished
  22544. // complete function by [CLEAR, ENDF]
  22545. content.push(new Uint8Array([0x22, 0x2D]));
  22546. }
  22547. foldTTTable(table, content);
  22548. }
  22549. function checkInvalidFunctions(ttContext, maxFunctionDefs) {
  22550. if (ttContext.tooComplexToFollowFunctions) {
  22551. return;
  22552. }
  22553. if (ttContext.functionsDefined.length > maxFunctionDefs) {
  22554. warn('TT: more functions defined than expected');
  22555. ttContext.hintsValid = false;
  22556. return;
  22557. }
  22558. for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
  22559. if (j > maxFunctionDefs) {
  22560. warn('TT: invalid function id: ' + j);
  22561. ttContext.hintsValid = false;
  22562. return;
  22563. }
  22564. if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
  22565. warn('TT: undefined function: ' + j);
  22566. ttContext.hintsValid = false;
  22567. return;
  22568. }
  22569. }
  22570. }
  22571. function foldTTTable(table, content) {
  22572. if (content.length > 1) {
  22573. // concatenating the content items
  22574. var newLength = 0;
  22575. var j, jj;
  22576. for (j = 0, jj = content.length; j < jj; j++) {
  22577. newLength += content[j].length;
  22578. }
  22579. newLength = (newLength + 3) & ~3;
  22580. var result = new Uint8Array(newLength);
  22581. var pos = 0;
  22582. for (j = 0, jj = content.length; j < jj; j++) {
  22583. result.set(content[j], pos);
  22584. pos += content[j].length;
  22585. }
  22586. table.data = result;
  22587. table.length = newLength;
  22588. }
  22589. }
  22590. function sanitizeTTPrograms(fpgm, prep, cvt) {
  22591. var ttContext = {
  22592. functionsDefined: [],
  22593. functionsUsed: [],
  22594. functionsStackDeltas: [],
  22595. tooComplexToFollowFunctions: false,
  22596. hintsValid: true
  22597. };
  22598. if (fpgm) {
  22599. sanitizeTTProgram(fpgm, ttContext);
  22600. }
  22601. if (prep) {
  22602. sanitizeTTProgram(prep, ttContext);
  22603. }
  22604. if (fpgm) {
  22605. checkInvalidFunctions(ttContext, maxFunctionDefs);
  22606. }
  22607. if (cvt && (cvt.length & 1)) {
  22608. var cvtData = new Uint8Array(cvt.length + 1);
  22609. cvtData.set(cvt.data);
  22610. cvt.data = cvtData;
  22611. }
  22612. return ttContext.hintsValid;
  22613. }
  22614. // The following steps modify the original font data, making copy
  22615. font = new Stream(new Uint8Array(font.getBytes()));
  22616. var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp',
  22617. 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF '];
  22618. var header = readOpenTypeHeader(font);
  22619. var numTables = header.numTables;
  22620. var cff, cffFile;
  22621. var tables = { 'OS/2': null, cmap: null, head: null, hhea: null,
  22622. hmtx: null, maxp: null, name: null, post: null };
  22623. var table;
  22624. for (var i = 0; i < numTables; i++) {
  22625. table = readTableEntry(font);
  22626. if (VALID_TABLES.indexOf(table.tag) < 0) {
  22627. continue; // skipping table if it's not a required or optional table
  22628. }
  22629. if (table.length === 0) {
  22630. continue; // skipping empty tables
  22631. }
  22632. tables[table.tag] = table;
  22633. }
  22634. var isTrueType = !tables['CFF '];
  22635. if (!isTrueType) {
  22636. // OpenType font
  22637. if (header.version === 'OTTO' ||
  22638. !tables.head || !tables.hhea || !tables.maxp || !tables.post) {
  22639. // no major tables: throwing everything at CFFFont
  22640. cffFile = new Stream(tables['CFF '].data);
  22641. cff = new CFFFont(cffFile, properties);
  22642. return this.convert(name, cff, properties);
  22643. }
  22644. delete tables.glyf;
  22645. delete tables.loca;
  22646. delete tables.fpgm;
  22647. delete tables.prep;
  22648. delete tables['cvt '];
  22649. this.isOpenType = true;
  22650. } else {
  22651. if (!tables.glyf || !tables.loca) {
  22652. error('Required "glyf" or "loca" tables are not found');
  22653. }
  22654. this.isOpenType = false;
  22655. }
  22656. if (!tables.maxp) {
  22657. error('Required "maxp" table is not found');
  22658. }
  22659. font.pos = (font.start || 0) + tables.maxp.offset;
  22660. var version = font.getInt32();
  22661. var numGlyphs = font.getUint16();
  22662. var maxFunctionDefs = 0;
  22663. if (version >= 0x00010000 && tables.maxp.length >= 22) {
  22664. // maxZones can be invalid
  22665. font.pos += 8;
  22666. var maxZones = font.getUint16();
  22667. if (maxZones > 2) { // reset to 2 if font has invalid maxZones
  22668. tables.maxp.data[14] = 0;
  22669. tables.maxp.data[15] = 2;
  22670. }
  22671. font.pos += 4;
  22672. maxFunctionDefs = font.getUint16();
  22673. }
  22674. var dupFirstEntry = false;
  22675. if (properties.type === 'CIDFontType2' && properties.toUnicode &&
  22676. properties.toUnicode.get(0) > '\u0000') {
  22677. // oracle's defect (see 3427), duplicating first entry
  22678. dupFirstEntry = true;
  22679. numGlyphs++;
  22680. tables.maxp.data[4] = numGlyphs >> 8;
  22681. tables.maxp.data[5] = numGlyphs & 255;
  22682. }
  22683. var hintsValid = sanitizeTTPrograms(tables.fpgm, tables.prep,
  22684. tables['cvt '], maxFunctionDefs);
  22685. if (!hintsValid) {
  22686. delete tables.fpgm;
  22687. delete tables.prep;
  22688. delete tables['cvt '];
  22689. }
  22690. // Ensure the hmtx table contains the advance width and
  22691. // sidebearings information for numGlyphs in the maxp table
  22692. sanitizeMetrics(font, tables.hhea, tables.hmtx, numGlyphs);
  22693. if (!tables.head) {
  22694. error('Required "head" table is not found');
  22695. }
  22696. sanitizeHead(tables.head, numGlyphs, isTrueType ? tables.loca.length : 0);
  22697. var missingGlyphs = {};
  22698. if (isTrueType) {
  22699. var isGlyphLocationsLong = int16(tables.head.data[50],
  22700. tables.head.data[51]);
  22701. missingGlyphs = sanitizeGlyphLocations(tables.loca, tables.glyf,
  22702. numGlyphs, isGlyphLocationsLong,
  22703. hintsValid, dupFirstEntry);
  22704. }
  22705. if (!tables.hhea) {
  22706. error('Required "hhea" table is not found');
  22707. }
  22708. // Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth
  22709. // Sometimes it's 0. That needs to be fixed
  22710. if (tables.hhea.data[10] === 0 && tables.hhea.data[11] === 0) {
  22711. tables.hhea.data[10] = 0xFF;
  22712. tables.hhea.data[11] = 0xFF;
  22713. }
  22714. // The 'post' table has glyphs names.
  22715. if (tables.post) {
  22716. var valid = readPostScriptTable(tables.post, properties, numGlyphs);
  22717. if (!valid) {
  22718. tables.post = null;
  22719. }
  22720. }
  22721. var charCodeToGlyphId = [], charCode;
  22722. var toUnicode = properties.toUnicode, widths = properties.widths;
  22723. var skipToUnicode = (toUnicode instanceof IdentityToUnicodeMap ||
  22724. toUnicode.length === 0x10000);
  22725. // Helper function to try to skip mapping of empty glyphs.
  22726. // Note: In some cases, just relying on the glyph data doesn't work,
  22727. // hence we also use a few heuristics to fix various PDF files.
  22728. function hasGlyph(glyphId, charCode, widthCode) {
  22729. if (!missingGlyphs[glyphId]) {
  22730. return true;
  22731. }
  22732. if (!skipToUnicode && charCode >= 0 && toUnicode.has(charCode)) {
  22733. return true;
  22734. }
  22735. if (widths && widthCode >= 0 && isNum(widths[widthCode])) {
  22736. return true;
  22737. }
  22738. return false;
  22739. }
  22740. if (properties.type === 'CIDFontType2') {
  22741. var cidToGidMap = properties.cidToGidMap || [];
  22742. var isCidToGidMapEmpty = cidToGidMap.length === 0;
  22743. properties.cMap.forEach(function(charCode, cid) {
  22744. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  22745. var glyphId = -1;
  22746. if (isCidToGidMapEmpty) {
  22747. glyphId = charCode;
  22748. } else if (cidToGidMap[cid] !== undefined) {
  22749. glyphId = cidToGidMap[cid];
  22750. }
  22751. if (glyphId >= 0 && glyphId < numGlyphs &&
  22752. hasGlyph(glyphId, charCode, cid)) {
  22753. charCodeToGlyphId[charCode] = glyphId;
  22754. }
  22755. });
  22756. if (dupFirstEntry) {
  22757. charCodeToGlyphId[0] = numGlyphs - 1;
  22758. }
  22759. } else {
  22760. // Most of the following logic in this code branch is based on the
  22761. // 9.6.6.4 of the PDF spec.
  22762. var cmapTable = readCmapTable(tables.cmap, font, this.isSymbolicFont);
  22763. var cmapPlatformId = cmapTable.platformId;
  22764. var cmapEncodingId = cmapTable.encodingId;
  22765. var cmapMappings = cmapTable.mappings;
  22766. var cmapMappingsLength = cmapMappings.length;
  22767. var hasEncoding = properties.differences.length ||
  22768. !!properties.baseEncodingName;
  22769. // The spec seems to imply that if the font is symbolic the encoding
  22770. // should be ignored, this doesn't appear to work for 'preistabelle.pdf'
  22771. // where the the font is symbolic and it has an encoding.
  22772. if (hasEncoding &&
  22773. (cmapPlatformId === 3 && cmapEncodingId === 1 ||
  22774. cmapPlatformId === 1 && cmapEncodingId === 0) ||
  22775. (cmapPlatformId === -1 && cmapEncodingId === -1 && // Temporary hack
  22776. !!Encodings[properties.baseEncodingName])) { // Temporary hack
  22777. // When no preferred cmap table was found and |baseEncodingName| is
  22778. // one of the predefined encodings, we seem to obtain a better
  22779. // |charCodeToGlyphId| map from the code below (fixes bug 1057544).
  22780. // TODO: Note that this is a hack which should be removed as soon as
  22781. // we have proper support for more exotic cmap tables.
  22782. var baseEncoding = [];
  22783. if (properties.baseEncodingName === 'MacRomanEncoding' ||
  22784. properties.baseEncodingName === 'WinAnsiEncoding') {
  22785. baseEncoding = Encodings[properties.baseEncodingName];
  22786. }
  22787. for (charCode = 0; charCode < 256; charCode++) {
  22788. var glyphName;
  22789. if (this.differences && charCode in this.differences) {
  22790. glyphName = this.differences[charCode];
  22791. } else if (charCode in baseEncoding &&
  22792. baseEncoding[charCode] !== '') {
  22793. glyphName = baseEncoding[charCode];
  22794. } else {
  22795. glyphName = Encodings.StandardEncoding[charCode];
  22796. }
  22797. if (!glyphName) {
  22798. continue;
  22799. }
  22800. var unicodeOrCharCode;
  22801. if (cmapPlatformId === 3 && cmapEncodingId === 1) {
  22802. unicodeOrCharCode = GlyphsUnicode[glyphName];
  22803. } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {
  22804. // TODO: the encoding needs to be updated with mac os table.
  22805. unicodeOrCharCode = Encodings.MacRomanEncoding.indexOf(glyphName);
  22806. }
  22807. var found = false;
  22808. for (i = 0; i < cmapMappingsLength; ++i) {
  22809. if (cmapMappings[i].charCode === unicodeOrCharCode &&
  22810. hasGlyph(cmapMappings[i].glyphId, unicodeOrCharCode, -1)) {
  22811. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  22812. found = true;
  22813. break;
  22814. }
  22815. }
  22816. if (!found && properties.glyphNames) {
  22817. // Try to map using the post table.
  22818. var glyphId = properties.glyphNames.indexOf(glyphName);
  22819. if (glyphId > 0 && hasGlyph(glyphId, -1, -1)) {
  22820. charCodeToGlyphId[charCode] = glyphId;
  22821. } else {
  22822. charCodeToGlyphId[charCode] = 0; // notdef
  22823. }
  22824. }
  22825. }
  22826. } else if (cmapPlatformId === 0 && cmapEncodingId === 0) {
  22827. // Default Unicode semantics, use the charcodes as is.
  22828. for (i = 0; i < cmapMappingsLength; ++i) {
  22829. charCodeToGlyphId[cmapMappings[i].charCode] =
  22830. cmapMappings[i].glyphId;
  22831. }
  22832. } else {
  22833. // For (3, 0) cmap tables:
  22834. // The charcode key being stored in charCodeToGlyphId is the lower
  22835. // byte of the two-byte charcodes of the cmap table since according to
  22836. // the spec: 'each byte from the string shall be prepended with the
  22837. // high byte of the range [of charcodes in the cmap table], to form
  22838. // a two-byte character, which shall be used to select the
  22839. // associated glyph description from the subtable'.
  22840. //
  22841. // For (1, 0) cmap tables:
  22842. // 'single bytes from the string shall be used to look up the
  22843. // associated glyph descriptions from the subtable'. This means
  22844. // charcodes in the cmap will be single bytes, so no-op since
  22845. // glyph.charCode & 0xFF === glyph.charCode
  22846. for (i = 0; i < cmapMappingsLength; ++i) {
  22847. charCode = cmapMappings[i].charCode & 0xFF;
  22848. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  22849. }
  22850. }
  22851. }
  22852. if (charCodeToGlyphId.length === 0) {
  22853. // defines at least one glyph
  22854. charCodeToGlyphId[0] = 0;
  22855. }
  22856. // Converting glyphs and ids into font's cmap table
  22857. var newMapping = adjustMapping(charCodeToGlyphId, properties);
  22858. this.toFontChar = newMapping.toFontChar;
  22859. tables.cmap = {
  22860. tag: 'cmap',
  22861. data: createCmapTable(newMapping.charCodeToGlyphId)
  22862. };
  22863. if (!tables['OS/2'] || !validateOS2Table(tables['OS/2'])) {
  22864. // extract some more font properties from the OpenType head and
  22865. // hhea tables; yMin and descent value are always negative
  22866. var override = {
  22867. unitsPerEm: int16(tables.head.data[18], tables.head.data[19]),
  22868. yMax: int16(tables.head.data[42], tables.head.data[43]),
  22869. yMin: int16(tables.head.data[38], tables.head.data[39]) - 0x10000,
  22870. ascent: int16(tables.hhea.data[4], tables.hhea.data[5]),
  22871. descent: int16(tables.hhea.data[6], tables.hhea.data[7]) - 0x10000
  22872. };
  22873. tables['OS/2'] = {
  22874. tag: 'OS/2',
  22875. data: createOS2Table(properties, newMapping.charCodeToGlyphId,
  22876. override)
  22877. };
  22878. }
  22879. // Rewrite the 'post' table if needed
  22880. if (!tables.post) {
  22881. tables.post = {
  22882. tag: 'post',
  22883. data: createPostTable(properties)
  22884. };
  22885. }
  22886. if (!isTrueType) {
  22887. try {
  22888. // Trying to repair CFF file
  22889. cffFile = new Stream(tables['CFF '].data);
  22890. var parser = new CFFParser(cffFile, properties);
  22891. cff = parser.parse();
  22892. var compiler = new CFFCompiler(cff);
  22893. tables['CFF '].data = compiler.compile();
  22894. } catch (e) {
  22895. warn('Failed to compile font ' + properties.loadedName);
  22896. }
  22897. }
  22898. // Re-creating 'name' table
  22899. if (!tables.name) {
  22900. tables.name = {
  22901. tag: 'name',
  22902. data: createNameTable(this.name)
  22903. };
  22904. } else {
  22905. // ... using existing 'name' table as prototype
  22906. var namePrototype = readNameTable(tables.name);
  22907. tables.name.data = createNameTable(name, namePrototype);
  22908. }
  22909. var builder = new OpenTypeFileBuilder(header.version);
  22910. for (var tableTag in tables) {
  22911. builder.addTable(tableTag, tables[tableTag].data);
  22912. }
  22913. return builder.toArray();
  22914. },
  22915. convert: function Font_convert(fontName, font, properties) {
  22916. // TODO: Check the charstring widths to determine this.
  22917. properties.fixedPitch = false;
  22918. var mapping = font.getGlyphMapping(properties);
  22919. var newMapping = adjustMapping(mapping, properties);
  22920. this.toFontChar = newMapping.toFontChar;
  22921. var numGlyphs = font.numGlyphs;
  22922. function getCharCodes(charCodeToGlyphId, glyphId) {
  22923. var charCodes = null;
  22924. for (var charCode in charCodeToGlyphId) {
  22925. if (glyphId === charCodeToGlyphId[charCode]) {
  22926. if (!charCodes) {
  22927. charCodes = [];
  22928. }
  22929. charCodes.push(charCode | 0);
  22930. }
  22931. }
  22932. return charCodes;
  22933. }
  22934. function createCharCode(charCodeToGlyphId, glyphId) {
  22935. for (var charCode in charCodeToGlyphId) {
  22936. if (glyphId === charCodeToGlyphId[charCode]) {
  22937. return charCode | 0;
  22938. }
  22939. }
  22940. newMapping.charCodeToGlyphId[newMapping.nextAvailableFontCharCode] =
  22941. glyphId;
  22942. return newMapping.nextAvailableFontCharCode++;
  22943. }
  22944. var seacs = font.seacs;
  22945. if (SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {
  22946. var matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX;
  22947. var charset = font.getCharset();
  22948. var seacMap = Object.create(null);
  22949. for (var glyphId in seacs) {
  22950. glyphId |= 0;
  22951. var seac = seacs[glyphId];
  22952. var baseGlyphName = Encodings.StandardEncoding[seac[2]];
  22953. var accentGlyphName = Encodings.StandardEncoding[seac[3]];
  22954. var baseGlyphId = charset.indexOf(baseGlyphName);
  22955. var accentGlyphId = charset.indexOf(accentGlyphName);
  22956. if (baseGlyphId < 0 || accentGlyphId < 0) {
  22957. continue;
  22958. }
  22959. var accentOffset = {
  22960. x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],
  22961. y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5]
  22962. };
  22963. var charCodes = getCharCodes(mapping, glyphId);
  22964. if (!charCodes) {
  22965. // There's no point in mapping it if the char code was never mapped
  22966. // to begin with.
  22967. continue;
  22968. }
  22969. for (var i = 0, ii = charCodes.length; i < ii; i++) {
  22970. var charCode = charCodes[i];
  22971. // Find a fontCharCode that maps to the base and accent glyphs.
  22972. // If one doesn't exists, create it.
  22973. var charCodeToGlyphId = newMapping.charCodeToGlyphId;
  22974. var baseFontCharCode = createCharCode(charCodeToGlyphId,
  22975. baseGlyphId);
  22976. var accentFontCharCode = createCharCode(charCodeToGlyphId,
  22977. accentGlyphId);
  22978. seacMap[charCode] = {
  22979. baseFontCharCode: baseFontCharCode,
  22980. accentFontCharCode: accentFontCharCode,
  22981. accentOffset: accentOffset
  22982. };
  22983. }
  22984. }
  22985. properties.seacMap = seacMap;
  22986. }
  22987. var unitsPerEm = 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  22988. var builder = new OpenTypeFileBuilder('\x4F\x54\x54\x4F');
  22989. // PostScript Font Program
  22990. builder.addTable('CFF ', font.data);
  22991. // OS/2 and Windows Specific metrics
  22992. builder.addTable('OS/2', createOS2Table(properties,
  22993. newMapping.charCodeToGlyphId));
  22994. // Character to glyphs mapping
  22995. builder.addTable('cmap', createCmapTable(newMapping.charCodeToGlyphId));
  22996. // Font header
  22997. builder.addTable('head',
  22998. '\x00\x01\x00\x00' + // Version number
  22999. '\x00\x00\x10\x00' + // fontRevision
  23000. '\x00\x00\x00\x00' + // checksumAdjustement
  23001. '\x5F\x0F\x3C\xF5' + // magicNumber
  23002. '\x00\x00' + // Flags
  23003. safeString16(unitsPerEm) + // unitsPerEM
  23004. '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date
  23005. '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date
  23006. '\x00\x00' + // xMin
  23007. safeString16(properties.descent) + // yMin
  23008. '\x0F\xFF' + // xMax
  23009. safeString16(properties.ascent) + // yMax
  23010. string16(properties.italicAngle ? 2 : 0) + // macStyle
  23011. '\x00\x11' + // lowestRecPPEM
  23012. '\x00\x00' + // fontDirectionHint
  23013. '\x00\x00' + // indexToLocFormat
  23014. '\x00\x00'); // glyphDataFormat
  23015. // Horizontal header
  23016. builder.addTable('hhea',
  23017. '\x00\x01\x00\x00' + // Version number
  23018. safeString16(properties.ascent) + // Typographic Ascent
  23019. safeString16(properties.descent) + // Typographic Descent
  23020. '\x00\x00' + // Line Gap
  23021. '\xFF\xFF' + // advanceWidthMax
  23022. '\x00\x00' + // minLeftSidebearing
  23023. '\x00\x00' + // minRightSidebearing
  23024. '\x00\x00' + // xMaxExtent
  23025. safeString16(properties.capHeight) + // caretSlopeRise
  23026. safeString16(Math.tan(properties.italicAngle) *
  23027. properties.xHeight) + // caretSlopeRun
  23028. '\x00\x00' + // caretOffset
  23029. '\x00\x00' + // -reserved-
  23030. '\x00\x00' + // -reserved-
  23031. '\x00\x00' + // -reserved-
  23032. '\x00\x00' + // -reserved-
  23033. '\x00\x00' + // metricDataFormat
  23034. string16(numGlyphs)); // Number of HMetrics
  23035. // Horizontal metrics
  23036. builder.addTable('hmtx', (function fontFieldsHmtx() {
  23037. var charstrings = font.charstrings;
  23038. var cffWidths = font.cff ? font.cff.widths : null;
  23039. var hmtx = '\x00\x00\x00\x00'; // Fake .notdef
  23040. for (var i = 1, ii = numGlyphs; i < ii; i++) {
  23041. var width = 0;
  23042. if (charstrings) {
  23043. var charstring = charstrings[i - 1];
  23044. width = 'width' in charstring ? charstring.width : 0;
  23045. } else if (cffWidths) {
  23046. width = Math.ceil(cffWidths[i] || 0);
  23047. }
  23048. hmtx += string16(width) + string16(0);
  23049. }
  23050. return hmtx;
  23051. })());
  23052. // Maximum profile
  23053. builder.addTable('maxp',
  23054. '\x00\x00\x50\x00' + // Version number
  23055. string16(numGlyphs)); // Num of glyphs
  23056. // Naming tables
  23057. builder.addTable('name', createNameTable(fontName));
  23058. // PostScript informations
  23059. builder.addTable('post', createPostTable(properties));
  23060. return builder.toArray();
  23061. },
  23062. /**
  23063. * Builds a char code to unicode map based on section 9.10 of the spec.
  23064. * @param {Object} properties Font properties object.
  23065. * @return {Object} A ToUnicodeMap object.
  23066. */
  23067. buildToUnicode: function Font_buildToUnicode(properties) {
  23068. // Section 9.10.2 Mapping Character Codes to Unicode Values
  23069. if (properties.toUnicode && properties.toUnicode.length !== 0) {
  23070. return properties.toUnicode;
  23071. }
  23072. // According to the spec if the font is a simple font we should only map
  23073. // to unicode if the base encoding is MacRoman, MacExpert, or WinAnsi or
  23074. // the differences array only contains adobe standard or symbol set names,
  23075. // in pratice it seems better to always try to create a toUnicode
  23076. // map based of the default encoding.
  23077. var toUnicode, charcode;
  23078. if (!properties.composite /* is simple font */) {
  23079. toUnicode = [];
  23080. var encoding = properties.defaultEncoding.slice();
  23081. var baseEncodingName = properties.baseEncodingName;
  23082. // Merge in the differences array.
  23083. var differences = properties.differences;
  23084. for (charcode in differences) {
  23085. encoding[charcode] = differences[charcode];
  23086. }
  23087. for (charcode in encoding) {
  23088. // a) Map the character code to a character name.
  23089. var glyphName = encoding[charcode];
  23090. // b) Look up the character name in the Adobe Glyph List (see the
  23091. // Bibliography) to obtain the corresponding Unicode value.
  23092. if (glyphName === '') {
  23093. continue;
  23094. } else if (GlyphsUnicode[glyphName] === undefined) {
  23095. // (undocumented) c) Few heuristics to recognize unknown glyphs
  23096. // NOTE: Adobe Reader does not do this step, but OSX Preview does
  23097. var code = 0;
  23098. switch (glyphName[0]) {
  23099. case 'G': // Gxx glyph
  23100. if (glyphName.length === 3) {
  23101. code = parseInt(glyphName.substr(1), 16);
  23102. }
  23103. break;
  23104. case 'g': // g00xx glyph
  23105. if (glyphName.length === 5) {
  23106. code = parseInt(glyphName.substr(1), 16);
  23107. }
  23108. break;
  23109. case 'C': // Cddd glyph
  23110. case 'c': // cddd glyph
  23111. if (glyphName.length >= 3) {
  23112. code = +glyphName.substr(1);
  23113. }
  23114. break;
  23115. }
  23116. if (code) {
  23117. // If |baseEncodingName| is one the predefined encodings,
  23118. // and |code| equals |charcode|, using the glyph defined in the
  23119. // baseEncoding seems to yield a better |toUnicode| mapping
  23120. // (fixes issue 5070).
  23121. if (baseEncodingName && code === +charcode) {
  23122. var baseEncoding = Encodings[baseEncodingName];
  23123. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  23124. toUnicode[charcode] =
  23125. String.fromCharCode(GlyphsUnicode[glyphName]);
  23126. continue;
  23127. }
  23128. }
  23129. toUnicode[charcode] = String.fromCharCode(code);
  23130. }
  23131. continue;
  23132. }
  23133. toUnicode[charcode] = String.fromCharCode(GlyphsUnicode[glyphName]);
  23134. }
  23135. return new ToUnicodeMap(toUnicode);
  23136. }
  23137. // If the font is a composite font that uses one of the predefined CMaps
  23138. // listed in Table 118 (except Identity–H and Identity–V) or whose
  23139. // descendant CIDFont uses the Adobe-GB1, Adobe-CNS1, Adobe-Japan1, or
  23140. // Adobe-Korea1 character collection:
  23141. if (properties.composite && (
  23142. (properties.cMap.builtInCMap &&
  23143. !(properties.cMap instanceof IdentityCMap)) ||
  23144. (properties.cidSystemInfo.registry === 'Adobe' &&
  23145. (properties.cidSystemInfo.ordering === 'GB1' ||
  23146. properties.cidSystemInfo.ordering === 'CNS1' ||
  23147. properties.cidSystemInfo.ordering === 'Japan1' ||
  23148. properties.cidSystemInfo.ordering === 'Korea1')))) {
  23149. // Then:
  23150. // a) Map the character code to a character identifier (CID) according
  23151. // to the font’s CMap.
  23152. // b) Obtain the registry and ordering of the character collection used
  23153. // by the font’s CMap (for example, Adobe and Japan1) from its
  23154. // CIDSystemInfo dictionary.
  23155. var registry = properties.cidSystemInfo.registry;
  23156. var ordering = properties.cidSystemInfo.ordering;
  23157. // c) Construct a second CMap name by concatenating the registry and
  23158. // ordering obtained in step (b) in the format registry–ordering–UCS2
  23159. // (for example, Adobe–Japan1–UCS2).
  23160. var ucs2CMapName = new Name(registry + '-' + ordering + '-UCS2');
  23161. // d) Obtain the CMap with the name constructed in step (c) (available
  23162. // from the ASN Web site; see the Bibliography).
  23163. var ucs2CMap = CMapFactory.create(ucs2CMapName,
  23164. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  23165. var cMap = properties.cMap;
  23166. toUnicode = [];
  23167. cMap.forEach(function(charcode, cid) {
  23168. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  23169. // e) Map the CID obtained in step (a) according to the CMap obtained
  23170. // in step (d), producing a Unicode value.
  23171. var ucs2 = ucs2CMap.lookup(cid);
  23172. if (ucs2) {
  23173. toUnicode[charcode] =
  23174. String.fromCharCode((ucs2.charCodeAt(0) << 8) +
  23175. ucs2.charCodeAt(1));
  23176. }
  23177. });
  23178. return new ToUnicodeMap(toUnicode);
  23179. }
  23180. // The viewer's choice, just use an identity map.
  23181. return new IdentityToUnicodeMap(properties.firstChar,
  23182. properties.lastChar);
  23183. },
  23184. get spaceWidth() {
  23185. if ('_shadowWidth' in this) {
  23186. return this._shadowWidth;
  23187. }
  23188. // trying to estimate space character width
  23189. var possibleSpaceReplacements = ['space', 'minus', 'one', 'i'];
  23190. var width;
  23191. for (var i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) {
  23192. var glyphName = possibleSpaceReplacements[i];
  23193. // if possible, getting width by glyph name
  23194. if (glyphName in this.widths) {
  23195. width = this.widths[glyphName];
  23196. break;
  23197. }
  23198. var glyphUnicode = GlyphsUnicode[glyphName];
  23199. // finding the charcode via unicodeToCID map
  23200. var charcode = 0;
  23201. if (this.composite) {
  23202. if (this.cMap.contains(glyphUnicode)) {
  23203. charcode = this.cMap.lookup(glyphUnicode);
  23204. }
  23205. }
  23206. // ... via toUnicode map
  23207. if (!charcode && 'toUnicode' in this) {
  23208. charcode = this.toUnicode.charCodeOf(glyphUnicode);
  23209. }
  23210. // setting it to unicode if negative or undefined
  23211. if (charcode <= 0) {
  23212. charcode = glyphUnicode;
  23213. }
  23214. // trying to get width via charcode
  23215. width = this.widths[charcode];
  23216. if (width) {
  23217. break; // the non-zero width found
  23218. }
  23219. }
  23220. width = width || this.defaultWidth;
  23221. // Do not shadow the property here. See discussion:
  23222. // https://github.com/mozilla/pdf.js/pull/2127#discussion_r1662280
  23223. this._shadowWidth = width;
  23224. return width;
  23225. },
  23226. charToGlyph: function Font_charToGlyph(charcode) {
  23227. var fontCharCode, width, operatorListId;
  23228. var widthCode = charcode;
  23229. if (this.cMap && this.cMap.contains(charcode)) {
  23230. widthCode = this.cMap.lookup(charcode);
  23231. }
  23232. width = this.widths[widthCode];
  23233. width = isNum(width) ? width : this.defaultWidth;
  23234. var vmetric = this.vmetrics && this.vmetrics[widthCode];
  23235. var unicode = this.toUnicode.get(charcode) || charcode;
  23236. if (typeof unicode === 'number') {
  23237. unicode = String.fromCharCode(unicode);
  23238. }
  23239. // First try the toFontChar map, if it's not there then try falling
  23240. // back to the char code.
  23241. fontCharCode = this.toFontChar[charcode] || charcode;
  23242. if (this.missingFile) {
  23243. fontCharCode = mapSpecialUnicodeValues(fontCharCode);
  23244. }
  23245. if (this.isType3Font) {
  23246. // Font char code in this case is actually a glyph name.
  23247. operatorListId = fontCharCode;
  23248. }
  23249. var accent = null;
  23250. if (this.seacMap && this.seacMap[charcode]) {
  23251. var seac = this.seacMap[charcode];
  23252. fontCharCode = seac.baseFontCharCode;
  23253. accent = {
  23254. fontChar: String.fromCharCode(seac.accentFontCharCode),
  23255. offset: seac.accentOffset
  23256. };
  23257. }
  23258. var fontChar = String.fromCharCode(fontCharCode);
  23259. var glyph = this.glyphCache[charcode];
  23260. if (!glyph ||
  23261. !glyph.matchesForCache(fontChar, unicode, accent, width, vmetric,
  23262. operatorListId)) {
  23263. glyph = new Glyph(fontChar, unicode, accent, width, vmetric,
  23264. operatorListId);
  23265. this.glyphCache[charcode] = glyph;
  23266. }
  23267. return glyph;
  23268. },
  23269. charsToGlyphs: function Font_charsToGlyphs(chars) {
  23270. var charsCache = this.charsCache;
  23271. var glyphs, glyph, charcode;
  23272. // if we translated this string before, just grab it from the cache
  23273. if (charsCache) {
  23274. glyphs = charsCache[chars];
  23275. if (glyphs) {
  23276. return glyphs;
  23277. }
  23278. }
  23279. // lazily create the translation cache
  23280. if (!charsCache) {
  23281. charsCache = this.charsCache = Object.create(null);
  23282. }
  23283. glyphs = [];
  23284. var charsCacheKey = chars;
  23285. var i = 0, ii;
  23286. if (this.cMap) {
  23287. // composite fonts have multi-byte strings convert the string from
  23288. // single-byte to multi-byte
  23289. var c = {};
  23290. while (i < chars.length) {
  23291. this.cMap.readCharCode(chars, i, c);
  23292. charcode = c.charcode;
  23293. var length = c.length;
  23294. i += length;
  23295. glyph = this.charToGlyph(charcode);
  23296. glyphs.push(glyph);
  23297. // placing null after each word break charcode (ASCII SPACE)
  23298. // Ignore occurences of 0x20 in multiple-byte codes.
  23299. if (length === 1 && chars.charCodeAt(i - 1) === 0x20) {
  23300. glyphs.push(null);
  23301. }
  23302. }
  23303. } else {
  23304. for (i = 0, ii = chars.length; i < ii; ++i) {
  23305. charcode = chars.charCodeAt(i);
  23306. glyph = this.charToGlyph(charcode);
  23307. glyphs.push(glyph);
  23308. if (charcode === 0x20) {
  23309. glyphs.push(null);
  23310. }
  23311. }
  23312. }
  23313. // Enter the translated string into the cache
  23314. return (charsCache[charsCacheKey] = glyphs);
  23315. }
  23316. };
  23317. return Font;
  23318. })();
  23319. var ErrorFont = (function ErrorFontClosure() {
  23320. function ErrorFont(error) {
  23321. this.error = error;
  23322. this.loadedName = 'g_font_error';
  23323. this.loading = false;
  23324. }
  23325. ErrorFont.prototype = {
  23326. charsToGlyphs: function ErrorFont_charsToGlyphs() {
  23327. return [];
  23328. },
  23329. exportData: function ErrorFont_exportData() {
  23330. return {error: this.error};
  23331. }
  23332. };
  23333. return ErrorFont;
  23334. })();
  23335. /**
  23336. * Shared logic for building a char code to glyph id mapping for Type1 and
  23337. * simple CFF fonts. See section 9.6.6.2 of the spec.
  23338. * @param {Object} properties Font properties object.
  23339. * @param {Object} builtInEncoding The encoding contained within the actual font
  23340. * data.
  23341. * @param {Array} Array of glyph names where the index is the glyph ID.
  23342. * @returns {Object} A char code to glyph ID map.
  23343. */
  23344. function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
  23345. var charCodeToGlyphId = Object.create(null);
  23346. var glyphId, charCode, baseEncoding;
  23347. if (properties.baseEncodingName) {
  23348. // If a valid base encoding name was used, the mapping is initialized with
  23349. // that.
  23350. baseEncoding = Encodings[properties.baseEncodingName];
  23351. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  23352. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  23353. if (glyphId >= 0) {
  23354. charCodeToGlyphId[charCode] = glyphId;
  23355. } else {
  23356. charCodeToGlyphId[charCode] = 0; // notdef
  23357. }
  23358. }
  23359. } else if (!!(properties.flags & FontFlags.Symbolic)) {
  23360. // For a symbolic font the encoding should be the fonts built-in
  23361. // encoding.
  23362. for (charCode in builtInEncoding) {
  23363. charCodeToGlyphId[charCode] = builtInEncoding[charCode];
  23364. }
  23365. } else {
  23366. // For non-symbolic fonts that don't have a base encoding the standard
  23367. // encoding should be used.
  23368. baseEncoding = Encodings.StandardEncoding;
  23369. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  23370. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  23371. if (glyphId >= 0) {
  23372. charCodeToGlyphId[charCode] = glyphId;
  23373. } else {
  23374. charCodeToGlyphId[charCode] = 0; // notdef
  23375. }
  23376. }
  23377. }
  23378. // Lastly, merge in the differences.
  23379. var differences = properties.differences;
  23380. if (differences) {
  23381. for (charCode in differences) {
  23382. var glyphName = differences[charCode];
  23383. glyphId = glyphNames.indexOf(glyphName);
  23384. if (glyphId >= 0) {
  23385. charCodeToGlyphId[charCode] = glyphId;
  23386. } else {
  23387. charCodeToGlyphId[charCode] = 0; // notdef
  23388. }
  23389. }
  23390. }
  23391. return charCodeToGlyphId;
  23392. }
  23393. /*
  23394. * CharStrings are encoded following the the CharString Encoding sequence
  23395. * describe in Chapter 6 of the "Adobe Type1 Font Format" specification.
  23396. * The value in a byte indicates a command, a number, or subsequent bytes
  23397. * that are to be interpreted in a special way.
  23398. *
  23399. * CharString Number Encoding:
  23400. * A CharString byte containing the values from 32 through 255 inclusive
  23401. * indicate an integer. These values are decoded in four ranges.
  23402. *
  23403. * 1. A CharString byte containing a value, v, between 32 and 246 inclusive,
  23404. * indicate the integer v - 139. Thus, the integer values from -107 through
  23405. * 107 inclusive may be encoded in single byte.
  23406. *
  23407. * 2. A CharString byte containing a value, v, between 247 and 250 inclusive,
  23408. * indicates an integer involving the next byte, w, according to the formula:
  23409. * [(v - 247) x 256] + w + 108
  23410. *
  23411. * 3. A CharString byte containing a value, v, between 251 and 254 inclusive,
  23412. * indicates an integer involving the next byte, w, according to the formula:
  23413. * -[(v - 251) * 256] - w - 108
  23414. *
  23415. * 4. A CharString containing the value 255 indicates that the next 4 bytes
  23416. * are a two complement signed integer. The first of these bytes contains the
  23417. * highest order bits, the second byte contains the next higher order bits
  23418. * and the fourth byte contain the lowest order bits.
  23419. *
  23420. *
  23421. * CharString Command Encoding:
  23422. * CharStrings commands are encoded in 1 or 2 bytes.
  23423. *
  23424. * Single byte commands are encoded in 1 byte that contains a value between
  23425. * 0 and 31 inclusive.
  23426. * If a command byte contains the value 12, then the value in the next byte
  23427. * indicates a command. This "escape" mechanism allows many extra commands
  23428. * to be encoded and this encoding technique helps to minimize the length of
  23429. * the charStrings.
  23430. */
  23431. var Type1CharString = (function Type1CharStringClosure() {
  23432. var COMMAND_MAP = {
  23433. 'hstem': [1],
  23434. 'vstem': [3],
  23435. 'vmoveto': [4],
  23436. 'rlineto': [5],
  23437. 'hlineto': [6],
  23438. 'vlineto': [7],
  23439. 'rrcurveto': [8],
  23440. 'callsubr': [10],
  23441. 'flex': [12, 35],
  23442. 'drop' : [12, 18],
  23443. 'endchar': [14],
  23444. 'rmoveto': [21],
  23445. 'hmoveto': [22],
  23446. 'vhcurveto': [30],
  23447. 'hvcurveto': [31]
  23448. };
  23449. function Type1CharString() {
  23450. this.width = 0;
  23451. this.lsb = 0;
  23452. this.flexing = false;
  23453. this.output = [];
  23454. this.stack = [];
  23455. }
  23456. Type1CharString.prototype = {
  23457. convert: function Type1CharString_convert(encoded, subrs) {
  23458. var count = encoded.length;
  23459. var error = false;
  23460. var wx, sbx, subrNumber;
  23461. for (var i = 0; i < count; i++) {
  23462. var value = encoded[i];
  23463. if (value < 32) {
  23464. if (value === 12) {
  23465. value = (value << 8) + encoded[++i];
  23466. }
  23467. switch (value) {
  23468. case 1: // hstem
  23469. if (!HINTING_ENABLED) {
  23470. this.stack = [];
  23471. break;
  23472. }
  23473. error = this.executeCommand(2, COMMAND_MAP.hstem);
  23474. break;
  23475. case 3: // vstem
  23476. if (!HINTING_ENABLED) {
  23477. this.stack = [];
  23478. break;
  23479. }
  23480. error = this.executeCommand(2, COMMAND_MAP.vstem);
  23481. break;
  23482. case 4: // vmoveto
  23483. if (this.flexing) {
  23484. if (this.stack.length < 1) {
  23485. error = true;
  23486. break;
  23487. }
  23488. // Add the dx for flex and but also swap the values so they are
  23489. // the right order.
  23490. var dy = this.stack.pop();
  23491. this.stack.push(0, dy);
  23492. break;
  23493. }
  23494. error = this.executeCommand(1, COMMAND_MAP.vmoveto);
  23495. break;
  23496. case 5: // rlineto
  23497. error = this.executeCommand(2, COMMAND_MAP.rlineto);
  23498. break;
  23499. case 6: // hlineto
  23500. error = this.executeCommand(1, COMMAND_MAP.hlineto);
  23501. break;
  23502. case 7: // vlineto
  23503. error = this.executeCommand(1, COMMAND_MAP.vlineto);
  23504. break;
  23505. case 8: // rrcurveto
  23506. error = this.executeCommand(6, COMMAND_MAP.rrcurveto);
  23507. break;
  23508. case 9: // closepath
  23509. // closepath is a Type1 command that does not take argument and is
  23510. // useless in Type2 and it can simply be ignored.
  23511. this.stack = [];
  23512. break;
  23513. case 10: // callsubr
  23514. if (this.stack.length < 1) {
  23515. error = true;
  23516. break;
  23517. }
  23518. subrNumber = this.stack.pop();
  23519. error = this.convert(subrs[subrNumber], subrs);
  23520. break;
  23521. case 11: // return
  23522. return error;
  23523. case 13: // hsbw
  23524. if (this.stack.length < 2) {
  23525. error = true;
  23526. break;
  23527. }
  23528. // To convert to type2 we have to move the width value to the
  23529. // first part of the charstring and then use hmoveto with lsb.
  23530. wx = this.stack.pop();
  23531. sbx = this.stack.pop();
  23532. this.lsb = sbx;
  23533. this.width = wx;
  23534. this.stack.push(wx, sbx);
  23535. error = this.executeCommand(2, COMMAND_MAP.hmoveto);
  23536. break;
  23537. case 14: // endchar
  23538. this.output.push(COMMAND_MAP.endchar[0]);
  23539. break;
  23540. case 21: // rmoveto
  23541. if (this.flexing) {
  23542. break;
  23543. }
  23544. error = this.executeCommand(2, COMMAND_MAP.rmoveto);
  23545. break;
  23546. case 22: // hmoveto
  23547. if (this.flexing) {
  23548. // Add the dy for flex.
  23549. this.stack.push(0);
  23550. break;
  23551. }
  23552. error = this.executeCommand(1, COMMAND_MAP.hmoveto);
  23553. break;
  23554. case 30: // vhcurveto
  23555. error = this.executeCommand(4, COMMAND_MAP.vhcurveto);
  23556. break;
  23557. case 31: // hvcurveto
  23558. error = this.executeCommand(4, COMMAND_MAP.hvcurveto);
  23559. break;
  23560. case (12 << 8) + 0: // dotsection
  23561. // dotsection is a Type1 command to specify some hinting feature
  23562. // for dots that do not take a parameter and it can safely be
  23563. // ignored for Type2.
  23564. this.stack = [];
  23565. break;
  23566. case (12 << 8) + 1: // vstem3
  23567. if (!HINTING_ENABLED) {
  23568. this.stack = [];
  23569. break;
  23570. }
  23571. // [vh]stem3 are Type1 only and Type2 supports [vh]stem with
  23572. // multiple parameters, so instead of returning [vh]stem3 take a
  23573. // shortcut and return [vhstem] instead.
  23574. error = this.executeCommand(2, COMMAND_MAP.vstem);
  23575. break;
  23576. case (12 << 8) + 2: // hstem3
  23577. if (!HINTING_ENABLED) {
  23578. this.stack = [];
  23579. break;
  23580. }
  23581. // See vstem3.
  23582. error = this.executeCommand(2, COMMAND_MAP.hstem);
  23583. break;
  23584. case (12 << 8) + 6: // seac
  23585. // seac is like type 2's special endchar but it doesn't use the
  23586. // first argument asb, so remove it.
  23587. if (SEAC_ANALYSIS_ENABLED) {
  23588. this.seac = this.stack.splice(-4, 4);
  23589. error = this.executeCommand(0, COMMAND_MAP.endchar);
  23590. } else {
  23591. error = this.executeCommand(4, COMMAND_MAP.endchar);
  23592. }
  23593. break;
  23594. case (12 << 8) + 7: // sbw
  23595. if (this.stack.length < 4) {
  23596. error = true;
  23597. break;
  23598. }
  23599. // To convert to type2 we have to move the width value to the
  23600. // first part of the charstring and then use rmoveto with
  23601. // (dx, dy). The height argument will not be used for vmtx and
  23602. // vhea tables reconstruction -- ignoring it.
  23603. var wy = this.stack.pop();
  23604. wx = this.stack.pop();
  23605. var sby = this.stack.pop();
  23606. sbx = this.stack.pop();
  23607. this.lsb = sbx;
  23608. this.width = wx;
  23609. this.stack.push(wx, sbx, sby);
  23610. error = this.executeCommand(3, COMMAND_MAP.rmoveto);
  23611. break;
  23612. case (12 << 8) + 12: // div
  23613. if (this.stack.length < 2) {
  23614. error = true;
  23615. break;
  23616. }
  23617. var num2 = this.stack.pop();
  23618. var num1 = this.stack.pop();
  23619. this.stack.push(num1 / num2);
  23620. break;
  23621. case (12 << 8) + 16: // callothersubr
  23622. if (this.stack.length < 2) {
  23623. error = true;
  23624. break;
  23625. }
  23626. subrNumber = this.stack.pop();
  23627. var numArgs = this.stack.pop();
  23628. if (subrNumber === 0 && numArgs === 3) {
  23629. var flexArgs = this.stack.splice(this.stack.length - 17, 17);
  23630. this.stack.push(
  23631. flexArgs[2] + flexArgs[0], // bcp1x + rpx
  23632. flexArgs[3] + flexArgs[1], // bcp1y + rpy
  23633. flexArgs[4], // bcp2x
  23634. flexArgs[5], // bcp2y
  23635. flexArgs[6], // p2x
  23636. flexArgs[7], // p2y
  23637. flexArgs[8], // bcp3x
  23638. flexArgs[9], // bcp3y
  23639. flexArgs[10], // bcp4x
  23640. flexArgs[11], // bcp4y
  23641. flexArgs[12], // p3x
  23642. flexArgs[13], // p3y
  23643. flexArgs[14] // flexDepth
  23644. // 15 = finalx unused by flex
  23645. // 16 = finaly unused by flex
  23646. );
  23647. error = this.executeCommand(13, COMMAND_MAP.flex, true);
  23648. this.flexing = false;
  23649. this.stack.push(flexArgs[15], flexArgs[16]);
  23650. } else if (subrNumber === 1 && numArgs === 0) {
  23651. this.flexing = true;
  23652. }
  23653. break;
  23654. case (12 << 8) + 17: // pop
  23655. // Ignore this since it is only used with othersubr.
  23656. break;
  23657. case (12 << 8) + 33: // setcurrentpoint
  23658. // Ignore for now.
  23659. this.stack = [];
  23660. break;
  23661. default:
  23662. warn('Unknown type 1 charstring command of "' + value + '"');
  23663. break;
  23664. }
  23665. if (error) {
  23666. break;
  23667. }
  23668. continue;
  23669. } else if (value <= 246) {
  23670. value = value - 139;
  23671. } else if (value <= 250) {
  23672. value = ((value - 247) * 256) + encoded[++i] + 108;
  23673. } else if (value <= 254) {
  23674. value = -((value - 251) * 256) - encoded[++i] - 108;
  23675. } else {
  23676. value = (encoded[++i] & 0xff) << 24 | (encoded[++i] & 0xff) << 16 |
  23677. (encoded[++i] & 0xff) << 8 | (encoded[++i] & 0xff) << 0;
  23678. }
  23679. this.stack.push(value);
  23680. }
  23681. return error;
  23682. },
  23683. executeCommand: function(howManyArgs, command, keepStack) {
  23684. var stackLength = this.stack.length;
  23685. if (howManyArgs > stackLength) {
  23686. return true;
  23687. }
  23688. var start = stackLength - howManyArgs;
  23689. for (var i = start; i < stackLength; i++) {
  23690. var value = this.stack[i];
  23691. if (value === (value | 0)) { // int
  23692. this.output.push(28, (value >> 8) & 0xff, value & 0xff);
  23693. } else { // fixed point
  23694. value = (65536 * value) | 0;
  23695. this.output.push(255,
  23696. (value >> 24) & 0xFF,
  23697. (value >> 16) & 0xFF,
  23698. (value >> 8) & 0xFF,
  23699. value & 0xFF);
  23700. }
  23701. }
  23702. this.output.push.apply(this.output, command);
  23703. if (keepStack) {
  23704. this.stack.splice(start, howManyArgs);
  23705. } else {
  23706. this.stack.length = 0;
  23707. }
  23708. return false;
  23709. }
  23710. };
  23711. return Type1CharString;
  23712. })();
  23713. /*
  23714. * Type1Parser encapsulate the needed code for parsing a Type1 font
  23715. * program. Some of its logic depends on the Type2 charstrings
  23716. * structure.
  23717. * Note: this doesn't really parse the font since that would require evaluation
  23718. * of PostScript, but it is possible in most cases to extract what we need
  23719. * without a full parse.
  23720. */
  23721. var Type1Parser = (function Type1ParserClosure() {
  23722. /*
  23723. * Decrypt a Sequence of Ciphertext Bytes to Produce the Original Sequence
  23724. * of Plaintext Bytes. The function took a key as a parameter which can be
  23725. * for decrypting the eexec block of for decoding charStrings.
  23726. */
  23727. var EEXEC_ENCRYPT_KEY = 55665;
  23728. var CHAR_STRS_ENCRYPT_KEY = 4330;
  23729. function isHexDigit(code) {
  23730. return code >= 48 && code <= 57 || // '0'-'9'
  23731. code >= 65 && code <= 70 || // 'A'-'F'
  23732. code >= 97 && code <= 102; // 'a'-'f'
  23733. }
  23734. function decrypt(data, key, discardNumber) {
  23735. var r = key | 0, c1 = 52845, c2 = 22719;
  23736. var count = data.length;
  23737. var decrypted = new Uint8Array(count);
  23738. for (var i = 0; i < count; i++) {
  23739. var value = data[i];
  23740. decrypted[i] = value ^ (r >> 8);
  23741. r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
  23742. }
  23743. return Array.prototype.slice.call(decrypted, discardNumber);
  23744. }
  23745. function decryptAscii(data, key, discardNumber) {
  23746. var r = key | 0, c1 = 52845, c2 = 22719;
  23747. var count = data.length, maybeLength = count >>> 1;
  23748. var decrypted = new Uint8Array(maybeLength);
  23749. var i, j;
  23750. for (i = 0, j = 0; i < count; i++) {
  23751. var digit1 = data[i];
  23752. if (!isHexDigit(digit1)) {
  23753. continue;
  23754. }
  23755. i++;
  23756. var digit2;
  23757. while (i < count && !isHexDigit(digit2 = data[i])) {
  23758. i++;
  23759. }
  23760. if (i < count) {
  23761. var value = parseInt(String.fromCharCode(digit1, digit2), 16);
  23762. decrypted[j++] = value ^ (r >> 8);
  23763. r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
  23764. }
  23765. }
  23766. return Array.prototype.slice.call(decrypted, discardNumber, j);
  23767. }
  23768. function isSpecial(c) {
  23769. return c === 0x2F || // '/'
  23770. c === 0x5B || c === 0x5D || // '[', ']'
  23771. c === 0x7B || c === 0x7D || // '{', '}'
  23772. c === 0x28 || c === 0x29; // '(', ')'
  23773. }
  23774. function Type1Parser(stream, encrypted) {
  23775. if (encrypted) {
  23776. var data = stream.getBytes();
  23777. var isBinary = !(isHexDigit(data[0]) && isHexDigit(data[1]) &&
  23778. isHexDigit(data[2]) && isHexDigit(data[3]));
  23779. stream = new Stream(isBinary ? decrypt(data, EEXEC_ENCRYPT_KEY, 4) :
  23780. decryptAscii(data, EEXEC_ENCRYPT_KEY, 4));
  23781. }
  23782. this.stream = stream;
  23783. this.nextChar();
  23784. }
  23785. Type1Parser.prototype = {
  23786. readNumberArray: function Type1Parser_readNumberArray() {
  23787. this.getToken(); // read '[' or '{' (arrays can start with either)
  23788. var array = [];
  23789. while (true) {
  23790. var token = this.getToken();
  23791. if (token === null || token === ']' || token === '}') {
  23792. break;
  23793. }
  23794. array.push(parseFloat(token || 0));
  23795. }
  23796. return array;
  23797. },
  23798. readNumber: function Type1Parser_readNumber() {
  23799. var token = this.getToken();
  23800. return parseFloat(token || 0);
  23801. },
  23802. readInt: function Type1Parser_readInt() {
  23803. // Use '| 0' to prevent setting a double into length such as the double
  23804. // does not flow into the loop variable.
  23805. var token = this.getToken();
  23806. return parseInt(token || 0, 10) | 0;
  23807. },
  23808. readBoolean: function Type1Parser_readBoolean() {
  23809. var token = this.getToken();
  23810. // Use 1 and 0 since that's what type2 charstrings use.
  23811. return token === 'true' ? 1 : 0;
  23812. },
  23813. nextChar : function Type1_nextChar() {
  23814. return (this.currentChar = this.stream.getByte());
  23815. },
  23816. getToken: function Type1Parser_getToken() {
  23817. // Eat whitespace and comments.
  23818. var comment = false;
  23819. var ch = this.currentChar;
  23820. while (true) {
  23821. if (ch === -1) {
  23822. return null;
  23823. }
  23824. if (comment) {
  23825. if (ch === 0x0A || ch === 0x0D) {
  23826. comment = false;
  23827. }
  23828. } else if (ch === 0x25) { // '%'
  23829. comment = true;
  23830. } else if (!Lexer.isSpace(ch)) {
  23831. break;
  23832. }
  23833. ch = this.nextChar();
  23834. }
  23835. if (isSpecial(ch)) {
  23836. this.nextChar();
  23837. return String.fromCharCode(ch);
  23838. }
  23839. var token = '';
  23840. do {
  23841. token += String.fromCharCode(ch);
  23842. ch = this.nextChar();
  23843. } while (ch >= 0 && !Lexer.isSpace(ch) && !isSpecial(ch));
  23844. return token;
  23845. },
  23846. /*
  23847. * Returns an object containing a Subrs array and a CharStrings
  23848. * array extracted from and eexec encrypted block of data
  23849. */
  23850. extractFontProgram: function Type1Parser_extractFontProgram() {
  23851. var stream = this.stream;
  23852. var subrs = [], charstrings = [];
  23853. var program = {
  23854. subrs: [],
  23855. charstrings: [],
  23856. properties: {
  23857. 'privateData': {
  23858. 'lenIV': 4
  23859. }
  23860. }
  23861. };
  23862. var token, length, data, lenIV, encoded;
  23863. while ((token = this.getToken()) !== null) {
  23864. if (token !== '/') {
  23865. continue;
  23866. }
  23867. token = this.getToken();
  23868. switch (token) {
  23869. case 'CharStrings':
  23870. // The number immediately following CharStrings must be greater or
  23871. // equal to the number of CharStrings.
  23872. this.getToken();
  23873. this.getToken(); // read in 'dict'
  23874. this.getToken(); // read in 'dup'
  23875. this.getToken(); // read in 'begin'
  23876. while(true) {
  23877. token = this.getToken();
  23878. if (token === null || token === 'end') {
  23879. break;
  23880. }
  23881. if (token !== '/') {
  23882. continue;
  23883. }
  23884. var glyph = this.getToken();
  23885. length = this.readInt();
  23886. this.getToken(); // read in 'RD' or '-|'
  23887. data = stream.makeSubStream(stream.pos, length);
  23888. lenIV = program.properties.privateData['lenIV'];
  23889. encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);
  23890. // Skip past the required space and binary data.
  23891. stream.skip(length);
  23892. this.nextChar();
  23893. token = this.getToken(); // read in 'ND' or '|-'
  23894. if (token === 'noaccess') {
  23895. this.getToken(); // read in 'def'
  23896. }
  23897. charstrings.push({
  23898. glyph: glyph,
  23899. encoded: encoded
  23900. });
  23901. }
  23902. break;
  23903. case 'Subrs':
  23904. var num = this.readInt();
  23905. this.getToken(); // read in 'array'
  23906. while ((token = this.getToken()) === 'dup') {
  23907. var index = this.readInt();
  23908. length = this.readInt();
  23909. this.getToken(); // read in 'RD' or '-|'
  23910. data = stream.makeSubStream(stream.pos, length);
  23911. lenIV = program.properties.privateData['lenIV'];
  23912. encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);
  23913. // Skip past the required space and binary data.
  23914. stream.skip(length);
  23915. this.nextChar();
  23916. token = this.getToken(); // read in 'NP' or '|'
  23917. if (token === 'noaccess') {
  23918. this.getToken(); // read in 'put'
  23919. }
  23920. subrs[index] = encoded;
  23921. }
  23922. break;
  23923. case 'BlueValues':
  23924. case 'OtherBlues':
  23925. case 'FamilyBlues':
  23926. case 'FamilyOtherBlues':
  23927. var blueArray = this.readNumberArray();
  23928. // *Blue* values may contain invalid data: disables reading of
  23929. // those values when hinting is disabled.
  23930. if (blueArray.length > 0 && (blueArray.length % 2) === 0 &&
  23931. HINTING_ENABLED) {
  23932. program.properties.privateData[token] = blueArray;
  23933. }
  23934. break;
  23935. case 'StemSnapH':
  23936. case 'StemSnapV':
  23937. program.properties.privateData[token] = this.readNumberArray();
  23938. break;
  23939. case 'StdHW':
  23940. case 'StdVW':
  23941. program.properties.privateData[token] =
  23942. this.readNumberArray()[0];
  23943. break;
  23944. case 'BlueShift':
  23945. case 'lenIV':
  23946. case 'BlueFuzz':
  23947. case 'BlueScale':
  23948. case 'LanguageGroup':
  23949. case 'ExpansionFactor':
  23950. program.properties.privateData[token] = this.readNumber();
  23951. break;
  23952. case 'ForceBold':
  23953. program.properties.privateData[token] = this.readBoolean();
  23954. break;
  23955. }
  23956. }
  23957. for (var i = 0; i < charstrings.length; i++) {
  23958. glyph = charstrings[i].glyph;
  23959. encoded = charstrings[i].encoded;
  23960. var charString = new Type1CharString();
  23961. var error = charString.convert(encoded, subrs);
  23962. var output = charString.output;
  23963. if (error) {
  23964. // It seems when FreeType encounters an error while evaluating a glyph
  23965. // that it completely ignores the glyph so we'll mimic that behaviour
  23966. // here and put an endchar to make the validator happy.
  23967. output = [14];
  23968. }
  23969. program.charstrings.push({
  23970. glyphName: glyph,
  23971. charstring: output,
  23972. width: charString.width,
  23973. lsb: charString.lsb,
  23974. seac: charString.seac
  23975. });
  23976. }
  23977. return program;
  23978. },
  23979. extractFontHeader: function Type1Parser_extractFontHeader(properties) {
  23980. var token;
  23981. while ((token = this.getToken()) !== null) {
  23982. if (token !== '/') {
  23983. continue;
  23984. }
  23985. token = this.getToken();
  23986. switch (token) {
  23987. case 'FontMatrix':
  23988. var matrix = this.readNumberArray();
  23989. properties.fontMatrix = matrix;
  23990. break;
  23991. case 'Encoding':
  23992. var encodingArg = this.getToken();
  23993. var encoding;
  23994. if (!/^\d+$/.test(encodingArg)) {
  23995. // encoding name is specified
  23996. encoding = Encodings[encodingArg];
  23997. } else {
  23998. encoding = [];
  23999. var size = parseInt(encodingArg, 10) | 0;
  24000. this.getToken(); // read in 'array'
  24001. for (var j = 0; j < size; j++) {
  24002. token = this.getToken();
  24003. // skipping till first dup or def (e.g. ignoring for statement)
  24004. while (token !== 'dup' && token !== 'def') {
  24005. token = this.getToken();
  24006. if (token === null) {
  24007. return; // invalid header
  24008. }
  24009. }
  24010. if (token === 'def') {
  24011. break; // read all array data
  24012. }
  24013. var index = this.readInt();
  24014. this.getToken(); // read in '/'
  24015. var glyph = this.getToken();
  24016. encoding[index] = glyph;
  24017. this.getToken(); // read the in 'put'
  24018. }
  24019. }
  24020. properties.builtInEncoding = encoding;
  24021. break;
  24022. case 'FontBBox':
  24023. var fontBBox = this.readNumberArray();
  24024. // adjusting ascent/descent
  24025. properties.ascent = fontBBox[3];
  24026. properties.descent = fontBBox[1];
  24027. properties.ascentScaled = true;
  24028. break;
  24029. }
  24030. }
  24031. }
  24032. };
  24033. return Type1Parser;
  24034. })();
  24035. /**
  24036. * The CFF class takes a Type1 file and wrap it into a
  24037. * 'Compact Font Format' which itself embed Type2 charstrings.
  24038. */
  24039. var CFFStandardStrings = [
  24040. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  24041. 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
  24042. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
  24043. 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  24044. 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  24045. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  24046. 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum',
  24047. 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  24048. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
  24049. 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
  24050. 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  24051. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  24052. 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
  24053. 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase',
  24054. 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown',
  24055. 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent',
  24056. 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash',
  24057. 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae',
  24058. 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior',
  24059. 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn',
  24060. 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters',
  24061. 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior',
  24062. 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring',
  24063. 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave',
  24064. 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute',
  24065. 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute',
  24066. 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron',
  24067. 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde',
  24068. 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute',
  24069. 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex',
  24070. 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex',
  24071. 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall',
  24072. 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall',
  24073. 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  24074. 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle',
  24075. 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
  24076. 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior',
  24077. 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior',
  24078. 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior',
  24079. 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  24080. 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior',
  24081. 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall',
  24082. 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
  24083. 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
  24084. 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  24085. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
  24086. 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
  24087. 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
  24088. 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior',
  24089. 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth',
  24090. 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
  24091. 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
  24092. 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior',
  24093. 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior',
  24094. 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
  24095. 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
  24096. 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall',
  24097. 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
  24098. 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
  24099. 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall',
  24100. 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall',
  24101. 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
  24102. 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall',
  24103. 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003',
  24104. 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'
  24105. ];
  24106. // Type1Font is also a CIDFontType0.
  24107. var Type1Font = function Type1Font(name, file, properties) {
  24108. // Some bad generators embed pfb file as is, we have to strip 6-byte headers.
  24109. // Also, length1 and length2 might be off by 6 bytes as well.
  24110. // http://www.math.ubc.ca/~cass/piscript/type1.pdf
  24111. var PFB_HEADER_SIZE = 6;
  24112. var headerBlockLength = properties.length1;
  24113. var eexecBlockLength = properties.length2;
  24114. var pfbHeader = file.peekBytes(PFB_HEADER_SIZE);
  24115. var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01;
  24116. if (pfbHeaderPresent) {
  24117. file.skip(PFB_HEADER_SIZE);
  24118. headerBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
  24119. (pfbHeader[3] << 8) | pfbHeader[2];
  24120. }
  24121. // Get the data block containing glyphs and subrs informations
  24122. var headerBlock = new Stream(file.getBytes(headerBlockLength));
  24123. var headerBlockParser = new Type1Parser(headerBlock);
  24124. headerBlockParser.extractFontHeader(properties);
  24125. if (pfbHeaderPresent) {
  24126. pfbHeader = file.getBytes(PFB_HEADER_SIZE);
  24127. eexecBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
  24128. (pfbHeader[3] << 8) | pfbHeader[2];
  24129. }
  24130. // Decrypt the data blocks and retrieve it's content
  24131. var eexecBlock = new Stream(file.getBytes(eexecBlockLength));
  24132. var eexecBlockParser = new Type1Parser(eexecBlock, true);
  24133. var data = eexecBlockParser.extractFontProgram();
  24134. for (var info in data.properties) {
  24135. properties[info] = data.properties[info];
  24136. }
  24137. var charstrings = data.charstrings;
  24138. var type2Charstrings = this.getType2Charstrings(charstrings);
  24139. var subrs = this.getType2Subrs(data.subrs);
  24140. this.charstrings = charstrings;
  24141. this.data = this.wrap(name, type2Charstrings, this.charstrings,
  24142. subrs, properties);
  24143. this.seacs = this.getSeacs(data.charstrings);
  24144. };
  24145. Type1Font.prototype = {
  24146. get numGlyphs() {
  24147. return this.charstrings.length + 1;
  24148. },
  24149. getCharset: function Type1Font_getCharset() {
  24150. var charset = ['.notdef'];
  24151. var charstrings = this.charstrings;
  24152. for (var glyphId = 0; glyphId < charstrings.length; glyphId++) {
  24153. charset.push(charstrings[glyphId].glyphName);
  24154. }
  24155. return charset;
  24156. },
  24157. getGlyphMapping: function Type1Font_getGlyphMapping(properties) {
  24158. var charstrings = this.charstrings;
  24159. var glyphNames = ['.notdef'], glyphId;
  24160. for (glyphId = 0; glyphId < charstrings.length; glyphId++) {
  24161. glyphNames.push(charstrings[glyphId].glyphName);
  24162. }
  24163. var encoding = properties.builtInEncoding;
  24164. if (encoding) {
  24165. var builtInEncoding = {};
  24166. for (var charCode in encoding) {
  24167. glyphId = glyphNames.indexOf(encoding[charCode]);
  24168. if (glyphId >= 0) {
  24169. builtInEncoding[charCode] = glyphId;
  24170. }
  24171. }
  24172. }
  24173. return type1FontGlyphMapping(properties, builtInEncoding, glyphNames);
  24174. },
  24175. getSeacs: function Type1Font_getSeacs(charstrings) {
  24176. var i, ii;
  24177. var seacMap = [];
  24178. for (i = 0, ii = charstrings.length; i < ii; i++) {
  24179. var charstring = charstrings[i];
  24180. if (charstring.seac) {
  24181. // Offset by 1 for .notdef
  24182. seacMap[i + 1] = charstring.seac;
  24183. }
  24184. }
  24185. return seacMap;
  24186. },
  24187. getType2Charstrings: function Type1Font_getType2Charstrings(
  24188. type1Charstrings) {
  24189. var type2Charstrings = [];
  24190. for (var i = 0, ii = type1Charstrings.length; i < ii; i++) {
  24191. type2Charstrings.push(type1Charstrings[i].charstring);
  24192. }
  24193. return type2Charstrings;
  24194. },
  24195. getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) {
  24196. var bias = 0;
  24197. var count = type1Subrs.length;
  24198. if (count < 1133) {
  24199. bias = 107;
  24200. } else if (count < 33769) {
  24201. bias = 1131;
  24202. } else {
  24203. bias = 32768;
  24204. }
  24205. // Add a bunch of empty subrs to deal with the Type2 bias
  24206. var type2Subrs = [];
  24207. var i;
  24208. for (i = 0; i < bias; i++) {
  24209. type2Subrs.push([0x0B]);
  24210. }
  24211. for (i = 0; i < count; i++) {
  24212. type2Subrs.push(type1Subrs[i]);
  24213. }
  24214. return type2Subrs;
  24215. },
  24216. wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) {
  24217. var cff = new CFF();
  24218. cff.header = new CFFHeader(1, 0, 4, 4);
  24219. cff.names = [name];
  24220. var topDict = new CFFTopDict();
  24221. // CFF strings IDs 0...390 are predefined names, so refering
  24222. // to entries in our own String INDEX starts at SID 391.
  24223. topDict.setByName('version', 391);
  24224. topDict.setByName('Notice', 392);
  24225. topDict.setByName('FullName', 393);
  24226. topDict.setByName('FamilyName', 394);
  24227. topDict.setByName('Weight', 395);
  24228. topDict.setByName('Encoding', null); // placeholder
  24229. topDict.setByName('FontMatrix', properties.fontMatrix);
  24230. topDict.setByName('FontBBox', properties.bbox);
  24231. topDict.setByName('charset', null); // placeholder
  24232. topDict.setByName('CharStrings', null); // placeholder
  24233. topDict.setByName('Private', null); // placeholder
  24234. cff.topDict = topDict;
  24235. var strings = new CFFStrings();
  24236. strings.add('Version 0.11'); // Version
  24237. strings.add('See original notice'); // Notice
  24238. strings.add(name); // FullName
  24239. strings.add(name); // FamilyName
  24240. strings.add('Medium'); // Weight
  24241. cff.strings = strings;
  24242. cff.globalSubrIndex = new CFFIndex();
  24243. var count = glyphs.length;
  24244. var charsetArray = [0];
  24245. var i, ii;
  24246. for (i = 0; i < count; i++) {
  24247. var index = CFFStandardStrings.indexOf(charstrings[i].glyphName);
  24248. // TODO: Insert the string and correctly map it. Previously it was
  24249. // thought mapping names that aren't in the standard strings to .notdef
  24250. // was fine, however in issue818 when mapping them all to .notdef the
  24251. // adieresis glyph no longer worked.
  24252. if (index === -1) {
  24253. index = 0;
  24254. }
  24255. charsetArray.push((index >> 8) & 0xff, index & 0xff);
  24256. }
  24257. cff.charset = new CFFCharset(false, 0, [], charsetArray);
  24258. var charStringsIndex = new CFFIndex();
  24259. charStringsIndex.add([0x8B, 0x0E]); // .notdef
  24260. for (i = 0; i < count; i++) {
  24261. charStringsIndex.add(glyphs[i]);
  24262. }
  24263. cff.charStrings = charStringsIndex;
  24264. var privateDict = new CFFPrivateDict();
  24265. privateDict.setByName('Subrs', null); // placeholder
  24266. var fields = [
  24267. 'BlueValues',
  24268. 'OtherBlues',
  24269. 'FamilyBlues',
  24270. 'FamilyOtherBlues',
  24271. 'StemSnapH',
  24272. 'StemSnapV',
  24273. 'BlueShift',
  24274. 'BlueFuzz',
  24275. 'BlueScale',
  24276. 'LanguageGroup',
  24277. 'ExpansionFactor',
  24278. 'ForceBold',
  24279. 'StdHW',
  24280. 'StdVW'
  24281. ];
  24282. for (i = 0, ii = fields.length; i < ii; i++) {
  24283. var field = fields[i];
  24284. if (!properties.privateData.hasOwnProperty(field)) {
  24285. continue;
  24286. }
  24287. var value = properties.privateData[field];
  24288. if (isArray(value)) {
  24289. // All of the private dictionary array data in CFF must be stored as
  24290. // "delta-encoded" numbers.
  24291. for (var j = value.length - 1; j > 0; j--) {
  24292. value[j] -= value[j - 1]; // ... difference from previous value
  24293. }
  24294. }
  24295. privateDict.setByName(field, value);
  24296. }
  24297. cff.topDict.privateDict = privateDict;
  24298. var subrIndex = new CFFIndex();
  24299. for (i = 0, ii = subrs.length; i < ii; i++) {
  24300. subrIndex.add(subrs[i]);
  24301. }
  24302. privateDict.subrsIndex = subrIndex;
  24303. var compiler = new CFFCompiler(cff);
  24304. return compiler.compile();
  24305. }
  24306. };
  24307. var CFFFont = (function CFFFontClosure() {
  24308. function CFFFont(file, properties) {
  24309. this.properties = properties;
  24310. var parser = new CFFParser(file, properties);
  24311. this.cff = parser.parse();
  24312. var compiler = new CFFCompiler(this.cff);
  24313. this.seacs = this.cff.seacs;
  24314. try {
  24315. this.data = compiler.compile();
  24316. } catch (e) {
  24317. warn('Failed to compile font ' + properties.loadedName);
  24318. // There may have just been an issue with the compiler, set the data
  24319. // anyway and hope the font loaded.
  24320. this.data = file;
  24321. }
  24322. }
  24323. CFFFont.prototype = {
  24324. get numGlyphs() {
  24325. return this.cff.charStrings.count;
  24326. },
  24327. getCharset: function CFFFont_getCharset() {
  24328. return this.cff.charset.charset;
  24329. },
  24330. getGlyphMapping: function CFFFont_getGlyphMapping() {
  24331. var cff = this.cff;
  24332. var properties = this.properties;
  24333. var charsets = cff.charset.charset;
  24334. var charCodeToGlyphId;
  24335. var glyphId;
  24336. if (properties.composite) {
  24337. charCodeToGlyphId = Object.create(null);
  24338. if (cff.isCIDFont) {
  24339. // If the font is actually a CID font then we should use the charset
  24340. // to map CIDs to GIDs.
  24341. for (glyphId = 0; glyphId < charsets.length; glyphId++) {
  24342. var cid = charsets[glyphId];
  24343. var charCode = properties.cMap.charCodeOf(cid);
  24344. charCodeToGlyphId[charCode] = glyphId;
  24345. }
  24346. } else {
  24347. // If it is NOT actually a CID font then CIDs should be mapped
  24348. // directly to GIDs.
  24349. for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {
  24350. charCodeToGlyphId[glyphId] = glyphId;
  24351. }
  24352. }
  24353. return charCodeToGlyphId;
  24354. }
  24355. var encoding = cff.encoding ? cff.encoding.encoding : null;
  24356. charCodeToGlyphId = type1FontGlyphMapping(properties, encoding, charsets);
  24357. return charCodeToGlyphId;
  24358. }
  24359. };
  24360. return CFFFont;
  24361. })();
  24362. var CFFParser = (function CFFParserClosure() {
  24363. var CharstringValidationData = [
  24364. null,
  24365. { id: 'hstem', min: 2, stackClearing: true, stem: true },
  24366. null,
  24367. { id: 'vstem', min: 2, stackClearing: true, stem: true },
  24368. { id: 'vmoveto', min: 1, stackClearing: true },
  24369. { id: 'rlineto', min: 2, resetStack: true },
  24370. { id: 'hlineto', min: 1, resetStack: true },
  24371. { id: 'vlineto', min: 1, resetStack: true },
  24372. { id: 'rrcurveto', min: 6, resetStack: true },
  24373. null,
  24374. { id: 'callsubr', min: 1, undefStack: true },
  24375. { id: 'return', min: 0, undefStack: true },
  24376. null, // 12
  24377. null,
  24378. { id: 'endchar', min: 0, stackClearing: true },
  24379. null,
  24380. null,
  24381. null,
  24382. { id: 'hstemhm', min: 2, stackClearing: true, stem: true },
  24383. { id: 'hintmask', min: 0, stackClearing: true },
  24384. { id: 'cntrmask', min: 0, stackClearing: true },
  24385. { id: 'rmoveto', min: 2, stackClearing: true },
  24386. { id: 'hmoveto', min: 1, stackClearing: true },
  24387. { id: 'vstemhm', min: 2, stackClearing: true, stem: true },
  24388. { id: 'rcurveline', min: 8, resetStack: true },
  24389. { id: 'rlinecurve', min: 8, resetStack: true },
  24390. { id: 'vvcurveto', min: 4, resetStack: true },
  24391. { id: 'hhcurveto', min: 4, resetStack: true },
  24392. null, // shortint
  24393. { id: 'callgsubr', min: 1, undefStack: true },
  24394. { id: 'vhcurveto', min: 4, resetStack: true },
  24395. { id: 'hvcurveto', min: 4, resetStack: true }
  24396. ];
  24397. var CharstringValidationData12 = [
  24398. null,
  24399. null,
  24400. null,
  24401. { id: 'and', min: 2, stackDelta: -1 },
  24402. { id: 'or', min: 2, stackDelta: -1 },
  24403. { id: 'not', min: 1, stackDelta: 0 },
  24404. null,
  24405. null,
  24406. null,
  24407. { id: 'abs', min: 1, stackDelta: 0 },
  24408. { id: 'add', min: 2, stackDelta: -1,
  24409. stackFn: function stack_div(stack, index) {
  24410. stack[index - 2] = stack[index - 2] + stack[index - 1];
  24411. }
  24412. },
  24413. { id: 'sub', min: 2, stackDelta: -1,
  24414. stackFn: function stack_div(stack, index) {
  24415. stack[index - 2] = stack[index - 2] - stack[index - 1];
  24416. }
  24417. },
  24418. { id: 'div', min: 2, stackDelta: -1,
  24419. stackFn: function stack_div(stack, index) {
  24420. stack[index - 2] = stack[index - 2] / stack[index - 1];
  24421. }
  24422. },
  24423. null,
  24424. { id: 'neg', min: 1, stackDelta: 0,
  24425. stackFn: function stack_div(stack, index) {
  24426. stack[index - 1] = -stack[index - 1];
  24427. }
  24428. },
  24429. { id: 'eq', min: 2, stackDelta: -1 },
  24430. null,
  24431. null,
  24432. { id: 'drop', min: 1, stackDelta: -1 },
  24433. null,
  24434. { id: 'put', min: 2, stackDelta: -2 },
  24435. { id: 'get', min: 1, stackDelta: 0 },
  24436. { id: 'ifelse', min: 4, stackDelta: -3 },
  24437. { id: 'random', min: 0, stackDelta: 1 },
  24438. { id: 'mul', min: 2, stackDelta: -1,
  24439. stackFn: function stack_div(stack, index) {
  24440. stack[index - 2] = stack[index - 2] * stack[index - 1];
  24441. }
  24442. },
  24443. null,
  24444. { id: 'sqrt', min: 1, stackDelta: 0 },
  24445. { id: 'dup', min: 1, stackDelta: 1 },
  24446. { id: 'exch', min: 2, stackDelta: 0 },
  24447. { id: 'index', min: 2, stackDelta: 0 },
  24448. { id: 'roll', min: 3, stackDelta: -2 },
  24449. null,
  24450. null,
  24451. null,
  24452. { id: 'hflex', min: 7, resetStack: true },
  24453. { id: 'flex', min: 13, resetStack: true },
  24454. { id: 'hflex1', min: 9, resetStack: true },
  24455. { id: 'flex1', min: 11, resetStack: true }
  24456. ];
  24457. function CFFParser(file, properties) {
  24458. this.bytes = file.getBytes();
  24459. this.properties = properties;
  24460. }
  24461. CFFParser.prototype = {
  24462. parse: function CFFParser_parse() {
  24463. var properties = this.properties;
  24464. var cff = new CFF();
  24465. this.cff = cff;
  24466. // The first five sections must be in order, all the others are reached
  24467. // via offsets contained in one of the below.
  24468. var header = this.parseHeader();
  24469. var nameIndex = this.parseIndex(header.endPos);
  24470. var topDictIndex = this.parseIndex(nameIndex.endPos);
  24471. var stringIndex = this.parseIndex(topDictIndex.endPos);
  24472. var globalSubrIndex = this.parseIndex(stringIndex.endPos);
  24473. var topDictParsed = this.parseDict(topDictIndex.obj.get(0));
  24474. var topDict = this.createDict(CFFTopDict, topDictParsed, cff.strings);
  24475. cff.header = header.obj;
  24476. cff.names = this.parseNameIndex(nameIndex.obj);
  24477. cff.strings = this.parseStringIndex(stringIndex.obj);
  24478. cff.topDict = topDict;
  24479. cff.globalSubrIndex = globalSubrIndex.obj;
  24480. this.parsePrivateDict(cff.topDict);
  24481. cff.isCIDFont = topDict.hasName('ROS');
  24482. var charStringOffset = topDict.getByName('CharStrings');
  24483. var charStringsAndSeacs = this.parseCharStrings(charStringOffset);
  24484. cff.charStrings = charStringsAndSeacs.charStrings;
  24485. cff.seacs = charStringsAndSeacs.seacs;
  24486. cff.widths = charStringsAndSeacs.widths;
  24487. var fontMatrix = topDict.getByName('FontMatrix');
  24488. if (fontMatrix) {
  24489. properties.fontMatrix = fontMatrix;
  24490. }
  24491. var fontBBox = topDict.getByName('FontBBox');
  24492. if (fontBBox) {
  24493. // adjusting ascent/descent
  24494. properties.ascent = fontBBox[3];
  24495. properties.descent = fontBBox[1];
  24496. properties.ascentScaled = true;
  24497. }
  24498. var charset, encoding;
  24499. if (cff.isCIDFont) {
  24500. var fdArrayIndex = this.parseIndex(topDict.getByName('FDArray')).obj;
  24501. for (var i = 0, ii = fdArrayIndex.count; i < ii; ++i) {
  24502. var dictRaw = fdArrayIndex.get(i);
  24503. var fontDict = this.createDict(CFFTopDict, this.parseDict(dictRaw),
  24504. cff.strings);
  24505. this.parsePrivateDict(fontDict);
  24506. cff.fdArray.push(fontDict);
  24507. }
  24508. // cid fonts don't have an encoding
  24509. encoding = null;
  24510. charset = this.parseCharsets(topDict.getByName('charset'),
  24511. cff.charStrings.count, cff.strings, true);
  24512. cff.fdSelect = this.parseFDSelect(topDict.getByName('FDSelect'),
  24513. cff.charStrings.count);
  24514. } else {
  24515. charset = this.parseCharsets(topDict.getByName('charset'),
  24516. cff.charStrings.count, cff.strings, false);
  24517. encoding = this.parseEncoding(topDict.getByName('Encoding'),
  24518. properties,
  24519. cff.strings, charset.charset);
  24520. }
  24521. cff.charset = charset;
  24522. cff.encoding = encoding;
  24523. return cff;
  24524. },
  24525. parseHeader: function CFFParser_parseHeader() {
  24526. var bytes = this.bytes;
  24527. var bytesLength = bytes.length;
  24528. var offset = 0;
  24529. // Prevent an infinite loop, by checking that the offset is within the
  24530. // bounds of the bytes array. Necessary in empty, or invalid, font files.
  24531. while (offset < bytesLength && bytes[offset] !== 1) {
  24532. ++offset;
  24533. }
  24534. if (offset >= bytesLength) {
  24535. error('Invalid CFF header');
  24536. } else if (offset !== 0) {
  24537. info('cff data is shifted');
  24538. bytes = bytes.subarray(offset);
  24539. this.bytes = bytes;
  24540. }
  24541. var major = bytes[0];
  24542. var minor = bytes[1];
  24543. var hdrSize = bytes[2];
  24544. var offSize = bytes[3];
  24545. var header = new CFFHeader(major, minor, hdrSize, offSize);
  24546. return { obj: header, endPos: hdrSize };
  24547. },
  24548. parseDict: function CFFParser_parseDict(dict) {
  24549. var pos = 0;
  24550. function parseOperand() {
  24551. var value = dict[pos++];
  24552. if (value === 30) {
  24553. return parseFloatOperand(pos);
  24554. } else if (value === 28) {
  24555. value = dict[pos++];
  24556. value = ((value << 24) | (dict[pos++] << 16)) >> 16;
  24557. return value;
  24558. } else if (value === 29) {
  24559. value = dict[pos++];
  24560. value = (value << 8) | dict[pos++];
  24561. value = (value << 8) | dict[pos++];
  24562. value = (value << 8) | dict[pos++];
  24563. return value;
  24564. } else if (value >= 32 && value <= 246) {
  24565. return value - 139;
  24566. } else if (value >= 247 && value <= 250) {
  24567. return ((value - 247) * 256) + dict[pos++] + 108;
  24568. } else if (value >= 251 && value <= 254) {
  24569. return -((value - 251) * 256) - dict[pos++] - 108;
  24570. } else {
  24571. error('255 is not a valid DICT command');
  24572. }
  24573. return -1;
  24574. }
  24575. function parseFloatOperand() {
  24576. var str = '';
  24577. var eof = 15;
  24578. var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
  24579. '9', '.', 'E', 'E-', null, '-'];
  24580. var length = dict.length;
  24581. while (pos < length) {
  24582. var b = dict[pos++];
  24583. var b1 = b >> 4;
  24584. var b2 = b & 15;
  24585. if (b1 === eof) {
  24586. break;
  24587. }
  24588. str += lookup[b1];
  24589. if (b2 === eof) {
  24590. break;
  24591. }
  24592. str += lookup[b2];
  24593. }
  24594. return parseFloat(str);
  24595. }
  24596. var operands = [];
  24597. var entries = [];
  24598. pos = 0;
  24599. var end = dict.length;
  24600. while (pos < end) {
  24601. var b = dict[pos];
  24602. if (b <= 21) {
  24603. if (b === 12) {
  24604. b = (b << 8) | dict[++pos];
  24605. }
  24606. entries.push([b, operands]);
  24607. operands = [];
  24608. ++pos;
  24609. } else {
  24610. operands.push(parseOperand());
  24611. }
  24612. }
  24613. return entries;
  24614. },
  24615. parseIndex: function CFFParser_parseIndex(pos) {
  24616. var cffIndex = new CFFIndex();
  24617. var bytes = this.bytes;
  24618. var count = (bytes[pos++] << 8) | bytes[pos++];
  24619. var offsets = [];
  24620. var end = pos;
  24621. var i, ii;
  24622. if (count !== 0) {
  24623. var offsetSize = bytes[pos++];
  24624. // add 1 for offset to determine size of last object
  24625. var startPos = pos + ((count + 1) * offsetSize) - 1;
  24626. for (i = 0, ii = count + 1; i < ii; ++i) {
  24627. var offset = 0;
  24628. for (var j = 0; j < offsetSize; ++j) {
  24629. offset <<= 8;
  24630. offset += bytes[pos++];
  24631. }
  24632. offsets.push(startPos + offset);
  24633. }
  24634. end = offsets[count];
  24635. }
  24636. for (i = 0, ii = offsets.length - 1; i < ii; ++i) {
  24637. var offsetStart = offsets[i];
  24638. var offsetEnd = offsets[i + 1];
  24639. cffIndex.add(bytes.subarray(offsetStart, offsetEnd));
  24640. }
  24641. return {obj: cffIndex, endPos: end};
  24642. },
  24643. parseNameIndex: function CFFParser_parseNameIndex(index) {
  24644. var names = [];
  24645. for (var i = 0, ii = index.count; i < ii; ++i) {
  24646. var name = index.get(i);
  24647. // OTS doesn't allow names to be over 127 characters.
  24648. var length = Math.min(name.length, 127);
  24649. var data = [];
  24650. // OTS also only permits certain characters in the name.
  24651. for (var j = 0; j < length; ++j) {
  24652. var c = name[j];
  24653. if (j === 0 && c === 0) {
  24654. data[j] = c;
  24655. continue;
  24656. }
  24657. if ((c < 33 || c > 126) || c === 91 /* [ */ || c === 93 /* ] */ ||
  24658. c === 40 /* ( */ || c === 41 /* ) */ || c === 123 /* { */ ||
  24659. c === 125 /* } */ || c === 60 /* < */ || c === 62 /* > */ ||
  24660. c === 47 /* / */ || c === 37 /* % */ || c === 35 /* # */) {
  24661. data[j] = 95;
  24662. continue;
  24663. }
  24664. data[j] = c;
  24665. }
  24666. names.push(bytesToString(data));
  24667. }
  24668. return names;
  24669. },
  24670. parseStringIndex: function CFFParser_parseStringIndex(index) {
  24671. var strings = new CFFStrings();
  24672. for (var i = 0, ii = index.count; i < ii; ++i) {
  24673. var data = index.get(i);
  24674. strings.add(bytesToString(data));
  24675. }
  24676. return strings;
  24677. },
  24678. createDict: function CFFParser_createDict(Type, dict, strings) {
  24679. var cffDict = new Type(strings);
  24680. for (var i = 0, ii = dict.length; i < ii; ++i) {
  24681. var pair = dict[i];
  24682. var key = pair[0];
  24683. var value = pair[1];
  24684. cffDict.setByKey(key, value);
  24685. }
  24686. return cffDict;
  24687. },
  24688. parseCharStrings: function CFFParser_parseCharStrings(charStringOffset) {
  24689. var charStrings = this.parseIndex(charStringOffset).obj;
  24690. var seacs = [];
  24691. var widths = [];
  24692. var count = charStrings.count;
  24693. for (var i = 0; i < count; i++) {
  24694. var charstring = charStrings.get(i);
  24695. var stackSize = 0;
  24696. var stack = [];
  24697. var undefStack = true;
  24698. var hints = 0;
  24699. var valid = true;
  24700. var data = charstring;
  24701. var length = data.length;
  24702. var firstStackClearing = true;
  24703. for (var j = 0; j < length;) {
  24704. var value = data[j++];
  24705. var validationCommand = null;
  24706. if (value === 12) {
  24707. var q = data[j++];
  24708. if (q === 0) {
  24709. // The CFF specification state that the 'dotsection' command
  24710. // (12, 0) is deprecated and treated as a no-op, but all Type2
  24711. // charstrings processors should support them. Unfortunately
  24712. // the font sanitizer don't. As a workaround the sequence (12, 0)
  24713. // is replaced by a useless (0, hmoveto).
  24714. data[j - 2] = 139;
  24715. data[j - 1] = 22;
  24716. stackSize = 0;
  24717. } else {
  24718. validationCommand = CharstringValidationData12[q];
  24719. }
  24720. } else if (value === 28) { // number (16 bit)
  24721. stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16)) >> 16;
  24722. j += 2;
  24723. stackSize++;
  24724. } else if (value === 14) {
  24725. if (stackSize >= 4) {
  24726. stackSize -= 4;
  24727. if (SEAC_ANALYSIS_ENABLED) {
  24728. seacs[i] = stack.slice(stackSize, stackSize + 4);
  24729. valid = false;
  24730. }
  24731. }
  24732. validationCommand = CharstringValidationData[value];
  24733. } else if (value >= 32 && value <= 246) { // number
  24734. stack[stackSize] = value - 139;
  24735. stackSize++;
  24736. } else if (value >= 247 && value <= 254) { // number (+1 bytes)
  24737. stack[stackSize] = (value < 251 ?
  24738. ((value - 247) << 8) + data[j] + 108 :
  24739. -((value - 251) << 8) - data[j] - 108);
  24740. j++;
  24741. stackSize++;
  24742. } else if (value === 255) { // number (32 bit)
  24743. stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16) |
  24744. (data[j + 2] << 8) | data[j + 3]) / 65536;
  24745. j += 4;
  24746. stackSize++;
  24747. } else if (value === 19 || value === 20) {
  24748. hints += stackSize >> 1;
  24749. j += (hints + 7) >> 3; // skipping right amount of hints flag data
  24750. stackSize %= 2;
  24751. validationCommand = CharstringValidationData[value];
  24752. } else {
  24753. validationCommand = CharstringValidationData[value];
  24754. }
  24755. if (validationCommand) {
  24756. if (validationCommand.stem) {
  24757. hints += stackSize >> 1;
  24758. }
  24759. if ('min' in validationCommand) {
  24760. if (!undefStack && stackSize < validationCommand.min) {
  24761. warn('Not enough parameters for ' + validationCommand.id +
  24762. '; actual: ' + stackSize +
  24763. ', expected: ' + validationCommand.min);
  24764. valid = false;
  24765. break;
  24766. }
  24767. }
  24768. if (firstStackClearing && validationCommand.stackClearing) {
  24769. firstStackClearing = false;
  24770. // the optional character width can be found before the first
  24771. // stack-clearing command arguments
  24772. stackSize -= validationCommand.min;
  24773. if (stackSize >= 2 && validationCommand.stem) {
  24774. // there are even amount of arguments for stem commands
  24775. stackSize %= 2;
  24776. } else if (stackSize > 1) {
  24777. warn('Found too many parameters for stack-clearing command');
  24778. }
  24779. if (stackSize > 0 && stack[stackSize - 1] >= 0) {
  24780. widths[i] = stack[stackSize - 1];
  24781. }
  24782. }
  24783. if ('stackDelta' in validationCommand) {
  24784. if ('stackFn' in validationCommand) {
  24785. validationCommand.stackFn(stack, stackSize);
  24786. }
  24787. stackSize += validationCommand.stackDelta;
  24788. } else if (validationCommand.stackClearing) {
  24789. stackSize = 0;
  24790. } else if (validationCommand.resetStack) {
  24791. stackSize = 0;
  24792. undefStack = false;
  24793. } else if (validationCommand.undefStack) {
  24794. stackSize = 0;
  24795. undefStack = true;
  24796. firstStackClearing = false;
  24797. }
  24798. }
  24799. }
  24800. if (!valid) {
  24801. // resetting invalid charstring to single 'endchar'
  24802. charStrings.set(i, new Uint8Array([14]));
  24803. }
  24804. }
  24805. return { charStrings: charStrings, seacs: seacs, widths: widths };
  24806. },
  24807. emptyPrivateDictionary:
  24808. function CFFParser_emptyPrivateDictionary(parentDict) {
  24809. var privateDict = this.createDict(CFFPrivateDict, [],
  24810. parentDict.strings);
  24811. parentDict.setByKey(18, [0, 0]);
  24812. parentDict.privateDict = privateDict;
  24813. },
  24814. parsePrivateDict: function CFFParser_parsePrivateDict(parentDict) {
  24815. // no private dict, do nothing
  24816. if (!parentDict.hasName('Private')) {
  24817. this.emptyPrivateDictionary(parentDict);
  24818. return;
  24819. }
  24820. var privateOffset = parentDict.getByName('Private');
  24821. // make sure the params are formatted correctly
  24822. if (!isArray(privateOffset) || privateOffset.length !== 2) {
  24823. parentDict.removeByName('Private');
  24824. return;
  24825. }
  24826. var size = privateOffset[0];
  24827. var offset = privateOffset[1];
  24828. // remove empty dicts or ones that refer to invalid location
  24829. if (size === 0 || offset >= this.bytes.length) {
  24830. this.emptyPrivateDictionary(parentDict);
  24831. return;
  24832. }
  24833. var privateDictEnd = offset + size;
  24834. var dictData = this.bytes.subarray(offset, privateDictEnd);
  24835. var dict = this.parseDict(dictData);
  24836. var privateDict = this.createDict(CFFPrivateDict, dict,
  24837. parentDict.strings);
  24838. parentDict.privateDict = privateDict;
  24839. // Parse the Subrs index also since it's relative to the private dict.
  24840. if (!privateDict.getByName('Subrs')) {
  24841. return;
  24842. }
  24843. var subrsOffset = privateDict.getByName('Subrs');
  24844. var relativeOffset = offset + subrsOffset;
  24845. // Validate the offset.
  24846. if (subrsOffset === 0 || relativeOffset >= this.bytes.length) {
  24847. this.emptyPrivateDictionary(parentDict);
  24848. return;
  24849. }
  24850. var subrsIndex = this.parseIndex(relativeOffset);
  24851. privateDict.subrsIndex = subrsIndex.obj;
  24852. },
  24853. parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) {
  24854. if (pos === 0) {
  24855. return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE,
  24856. ISOAdobeCharset);
  24857. } else if (pos === 1) {
  24858. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT,
  24859. ExpertCharset);
  24860. } else if (pos === 2) {
  24861. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET,
  24862. ExpertSubsetCharset);
  24863. }
  24864. var bytes = this.bytes;
  24865. var start = pos;
  24866. var format = bytes[pos++];
  24867. var charset = ['.notdef'];
  24868. var id, count, i;
  24869. // subtract 1 for the .notdef glyph
  24870. length -= 1;
  24871. switch (format) {
  24872. case 0:
  24873. for (i = 0; i < length; i++) {
  24874. id = (bytes[pos++] << 8) | bytes[pos++];
  24875. charset.push(cid ? id : strings.get(id));
  24876. }
  24877. break;
  24878. case 1:
  24879. while (charset.length <= length) {
  24880. id = (bytes[pos++] << 8) | bytes[pos++];
  24881. count = bytes[pos++];
  24882. for (i = 0; i <= count; i++) {
  24883. charset.push(cid ? id++ : strings.get(id++));
  24884. }
  24885. }
  24886. break;
  24887. case 2:
  24888. while (charset.length <= length) {
  24889. id = (bytes[pos++] << 8) | bytes[pos++];
  24890. count = (bytes[pos++] << 8) | bytes[pos++];
  24891. for (i = 0; i <= count; i++) {
  24892. charset.push(cid ? id++ : strings.get(id++));
  24893. }
  24894. }
  24895. break;
  24896. default:
  24897. error('Unknown charset format');
  24898. }
  24899. // Raw won't be needed if we actually compile the charset.
  24900. var end = pos;
  24901. var raw = bytes.subarray(start, end);
  24902. return new CFFCharset(false, format, charset, raw);
  24903. },
  24904. parseEncoding: function CFFParser_parseEncoding(pos,
  24905. properties,
  24906. strings,
  24907. charset) {
  24908. var encoding = {};
  24909. var bytes = this.bytes;
  24910. var predefined = false;
  24911. var hasSupplement = false;
  24912. var format, i, ii;
  24913. var raw = null;
  24914. function readSupplement() {
  24915. var supplementsCount = bytes[pos++];
  24916. for (i = 0; i < supplementsCount; i++) {
  24917. var code = bytes[pos++];
  24918. var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);
  24919. encoding[code] = charset.indexOf(strings.get(sid));
  24920. }
  24921. }
  24922. if (pos === 0 || pos === 1) {
  24923. predefined = true;
  24924. format = pos;
  24925. var baseEncoding = pos ? Encodings.ExpertEncoding :
  24926. Encodings.StandardEncoding;
  24927. for (i = 0, ii = charset.length; i < ii; i++) {
  24928. var index = baseEncoding.indexOf(charset[i]);
  24929. if (index !== -1) {
  24930. encoding[index] = i;
  24931. }
  24932. }
  24933. } else {
  24934. var dataStart = pos;
  24935. format = bytes[pos++];
  24936. switch (format & 0x7f) {
  24937. case 0:
  24938. var glyphsCount = bytes[pos++];
  24939. for (i = 1; i <= glyphsCount; i++) {
  24940. encoding[bytes[pos++]] = i;
  24941. }
  24942. break;
  24943. case 1:
  24944. var rangesCount = bytes[pos++];
  24945. var gid = 1;
  24946. for (i = 0; i < rangesCount; i++) {
  24947. var start = bytes[pos++];
  24948. var left = bytes[pos++];
  24949. for (var j = start; j <= start + left; j++) {
  24950. encoding[j] = gid++;
  24951. }
  24952. }
  24953. break;
  24954. default:
  24955. error('Unknow encoding format: ' + format + ' in CFF');
  24956. break;
  24957. }
  24958. var dataEnd = pos;
  24959. if (format & 0x80) {
  24960. // The font sanitizer does not support CFF encoding with a
  24961. // supplement, since the encoding is not really used to map
  24962. // between gid to glyph, let's overwrite what is declared in
  24963. // the top dictionary to let the sanitizer think the font use
  24964. // StandardEncoding, that's a lie but that's ok.
  24965. bytes[dataStart] &= 0x7f;
  24966. readSupplement();
  24967. hasSupplement = true;
  24968. }
  24969. raw = bytes.subarray(dataStart, dataEnd);
  24970. }
  24971. format = format & 0x7f;
  24972. return new CFFEncoding(predefined, format, encoding, raw);
  24973. },
  24974. parseFDSelect: function CFFParser_parseFDSelect(pos, length) {
  24975. var start = pos;
  24976. var bytes = this.bytes;
  24977. var format = bytes[pos++];
  24978. var fdSelect = [];
  24979. var i;
  24980. switch (format) {
  24981. case 0:
  24982. for (i = 0; i < length; ++i) {
  24983. var id = bytes[pos++];
  24984. fdSelect.push(id);
  24985. }
  24986. break;
  24987. case 3:
  24988. var rangesCount = (bytes[pos++] << 8) | bytes[pos++];
  24989. for (i = 0; i < rangesCount; ++i) {
  24990. var first = (bytes[pos++] << 8) | bytes[pos++];
  24991. var fdIndex = bytes[pos++];
  24992. var next = (bytes[pos] << 8) | bytes[pos + 1];
  24993. for (var j = first; j < next; ++j) {
  24994. fdSelect.push(fdIndex);
  24995. }
  24996. }
  24997. // Advance past the sentinel(next).
  24998. pos += 2;
  24999. break;
  25000. default:
  25001. error('Unknown fdselect format ' + format);
  25002. break;
  25003. }
  25004. var end = pos;
  25005. return new CFFFDSelect(fdSelect, bytes.subarray(start, end));
  25006. }
  25007. };
  25008. return CFFParser;
  25009. })();
  25010. // Compact Font Format
  25011. var CFF = (function CFFClosure() {
  25012. function CFF() {
  25013. this.header = null;
  25014. this.names = [];
  25015. this.topDict = null;
  25016. this.strings = new CFFStrings();
  25017. this.globalSubrIndex = null;
  25018. // The following could really be per font, but since we only have one font
  25019. // store them here.
  25020. this.encoding = null;
  25021. this.charset = null;
  25022. this.charStrings = null;
  25023. this.fdArray = [];
  25024. this.fdSelect = null;
  25025. this.isCIDFont = false;
  25026. }
  25027. return CFF;
  25028. })();
  25029. var CFFHeader = (function CFFHeaderClosure() {
  25030. function CFFHeader(major, minor, hdrSize, offSize) {
  25031. this.major = major;
  25032. this.minor = minor;
  25033. this.hdrSize = hdrSize;
  25034. this.offSize = offSize;
  25035. }
  25036. return CFFHeader;
  25037. })();
  25038. var CFFStrings = (function CFFStringsClosure() {
  25039. function CFFStrings() {
  25040. this.strings = [];
  25041. }
  25042. CFFStrings.prototype = {
  25043. get: function CFFStrings_get(index) {
  25044. if (index >= 0 && index <= 390) {
  25045. return CFFStandardStrings[index];
  25046. }
  25047. if (index - 391 <= this.strings.length) {
  25048. return this.strings[index - 391];
  25049. }
  25050. return CFFStandardStrings[0];
  25051. },
  25052. add: function CFFStrings_add(value) {
  25053. this.strings.push(value);
  25054. },
  25055. get count() {
  25056. return this.strings.length;
  25057. }
  25058. };
  25059. return CFFStrings;
  25060. })();
  25061. var CFFIndex = (function CFFIndexClosure() {
  25062. function CFFIndex() {
  25063. this.objects = [];
  25064. this.length = 0;
  25065. }
  25066. CFFIndex.prototype = {
  25067. add: function CFFIndex_add(data) {
  25068. this.length += data.length;
  25069. this.objects.push(data);
  25070. },
  25071. set: function CFFIndex_set(index, data) {
  25072. this.length += data.length - this.objects[index].length;
  25073. this.objects[index] = data;
  25074. },
  25075. get: function CFFIndex_get(index) {
  25076. return this.objects[index];
  25077. },
  25078. get count() {
  25079. return this.objects.length;
  25080. }
  25081. };
  25082. return CFFIndex;
  25083. })();
  25084. var CFFDict = (function CFFDictClosure() {
  25085. function CFFDict(tables, strings) {
  25086. this.keyToNameMap = tables.keyToNameMap;
  25087. this.nameToKeyMap = tables.nameToKeyMap;
  25088. this.defaults = tables.defaults;
  25089. this.types = tables.types;
  25090. this.opcodes = tables.opcodes;
  25091. this.order = tables.order;
  25092. this.strings = strings;
  25093. this.values = {};
  25094. }
  25095. CFFDict.prototype = {
  25096. // value should always be an array
  25097. setByKey: function CFFDict_setByKey(key, value) {
  25098. if (!(key in this.keyToNameMap)) {
  25099. return false;
  25100. }
  25101. // ignore empty values
  25102. if (value.length === 0) {
  25103. return true;
  25104. }
  25105. var type = this.types[key];
  25106. // remove the array wrapping these types of values
  25107. if (type === 'num' || type === 'sid' || type === 'offset') {
  25108. value = value[0];
  25109. }
  25110. this.values[key] = value;
  25111. return true;
  25112. },
  25113. setByName: function CFFDict_setByName(name, value) {
  25114. if (!(name in this.nameToKeyMap)) {
  25115. error('Invalid dictionary name "' + name + '"');
  25116. }
  25117. this.values[this.nameToKeyMap[name]] = value;
  25118. },
  25119. hasName: function CFFDict_hasName(name) {
  25120. return this.nameToKeyMap[name] in this.values;
  25121. },
  25122. getByName: function CFFDict_getByName(name) {
  25123. if (!(name in this.nameToKeyMap)) {
  25124. error('Invalid dictionary name "' + name + '"');
  25125. }
  25126. var key = this.nameToKeyMap[name];
  25127. if (!(key in this.values)) {
  25128. return this.defaults[key];
  25129. }
  25130. return this.values[key];
  25131. },
  25132. removeByName: function CFFDict_removeByName(name) {
  25133. delete this.values[this.nameToKeyMap[name]];
  25134. }
  25135. };
  25136. CFFDict.createTables = function CFFDict_createTables(layout) {
  25137. var tables = {
  25138. keyToNameMap: {},
  25139. nameToKeyMap: {},
  25140. defaults: {},
  25141. types: {},
  25142. opcodes: {},
  25143. order: []
  25144. };
  25145. for (var i = 0, ii = layout.length; i < ii; ++i) {
  25146. var entry = layout[i];
  25147. var key = isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0];
  25148. tables.keyToNameMap[key] = entry[1];
  25149. tables.nameToKeyMap[entry[1]] = key;
  25150. tables.types[key] = entry[2];
  25151. tables.defaults[key] = entry[3];
  25152. tables.opcodes[key] = isArray(entry[0]) ? entry[0] : [entry[0]];
  25153. tables.order.push(key);
  25154. }
  25155. return tables;
  25156. };
  25157. return CFFDict;
  25158. })();
  25159. var CFFTopDict = (function CFFTopDictClosure() {
  25160. var layout = [
  25161. [[12, 30], 'ROS', ['sid', 'sid', 'num'], null],
  25162. [[12, 20], 'SyntheticBase', 'num', null],
  25163. [0, 'version', 'sid', null],
  25164. [1, 'Notice', 'sid', null],
  25165. [[12, 0], 'Copyright', 'sid', null],
  25166. [2, 'FullName', 'sid', null],
  25167. [3, 'FamilyName', 'sid', null],
  25168. [4, 'Weight', 'sid', null],
  25169. [[12, 1], 'isFixedPitch', 'num', 0],
  25170. [[12, 2], 'ItalicAngle', 'num', 0],
  25171. [[12, 3], 'UnderlinePosition', 'num', -100],
  25172. [[12, 4], 'UnderlineThickness', 'num', 50],
  25173. [[12, 5], 'PaintType', 'num', 0],
  25174. [[12, 6], 'CharstringType', 'num', 2],
  25175. [[12, 7], 'FontMatrix', ['num', 'num', 'num', 'num', 'num', 'num'],
  25176. [0.001, 0, 0, 0.001, 0, 0]],
  25177. [13, 'UniqueID', 'num', null],
  25178. [5, 'FontBBox', ['num', 'num', 'num', 'num'], [0, 0, 0, 0]],
  25179. [[12, 8], 'StrokeWidth', 'num', 0],
  25180. [14, 'XUID', 'array', null],
  25181. [15, 'charset', 'offset', 0],
  25182. [16, 'Encoding', 'offset', 0],
  25183. [17, 'CharStrings', 'offset', 0],
  25184. [18, 'Private', ['offset', 'offset'], null],
  25185. [[12, 21], 'PostScript', 'sid', null],
  25186. [[12, 22], 'BaseFontName', 'sid', null],
  25187. [[12, 23], 'BaseFontBlend', 'delta', null],
  25188. [[12, 31], 'CIDFontVersion', 'num', 0],
  25189. [[12, 32], 'CIDFontRevision', 'num', 0],
  25190. [[12, 33], 'CIDFontType', 'num', 0],
  25191. [[12, 34], 'CIDCount', 'num', 8720],
  25192. [[12, 35], 'UIDBase', 'num', null],
  25193. // XXX: CID Fonts on DirectWrite 6.1 only seem to work if FDSelect comes
  25194. // before FDArray.
  25195. [[12, 37], 'FDSelect', 'offset', null],
  25196. [[12, 36], 'FDArray', 'offset', null],
  25197. [[12, 38], 'FontName', 'sid', null]
  25198. ];
  25199. var tables = null;
  25200. function CFFTopDict(strings) {
  25201. if (tables === null) {
  25202. tables = CFFDict.createTables(layout);
  25203. }
  25204. CFFDict.call(this, tables, strings);
  25205. this.privateDict = null;
  25206. }
  25207. CFFTopDict.prototype = Object.create(CFFDict.prototype);
  25208. return CFFTopDict;
  25209. })();
  25210. var CFFPrivateDict = (function CFFPrivateDictClosure() {
  25211. var layout = [
  25212. [6, 'BlueValues', 'delta', null],
  25213. [7, 'OtherBlues', 'delta', null],
  25214. [8, 'FamilyBlues', 'delta', null],
  25215. [9, 'FamilyOtherBlues', 'delta', null],
  25216. [[12, 9], 'BlueScale', 'num', 0.039625],
  25217. [[12, 10], 'BlueShift', 'num', 7],
  25218. [[12, 11], 'BlueFuzz', 'num', 1],
  25219. [10, 'StdHW', 'num', null],
  25220. [11, 'StdVW', 'num', null],
  25221. [[12, 12], 'StemSnapH', 'delta', null],
  25222. [[12, 13], 'StemSnapV', 'delta', null],
  25223. [[12, 14], 'ForceBold', 'num', 0],
  25224. [[12, 17], 'LanguageGroup', 'num', 0],
  25225. [[12, 18], 'ExpansionFactor', 'num', 0.06],
  25226. [[12, 19], 'initialRandomSeed', 'num', 0],
  25227. [20, 'defaultWidthX', 'num', 0],
  25228. [21, 'nominalWidthX', 'num', 0],
  25229. [19, 'Subrs', 'offset', null]
  25230. ];
  25231. var tables = null;
  25232. function CFFPrivateDict(strings) {
  25233. if (tables === null) {
  25234. tables = CFFDict.createTables(layout);
  25235. }
  25236. CFFDict.call(this, tables, strings);
  25237. this.subrsIndex = null;
  25238. }
  25239. CFFPrivateDict.prototype = Object.create(CFFDict.prototype);
  25240. return CFFPrivateDict;
  25241. })();
  25242. var CFFCharsetPredefinedTypes = {
  25243. ISO_ADOBE: 0,
  25244. EXPERT: 1,
  25245. EXPERT_SUBSET: 2
  25246. };
  25247. var CFFCharset = (function CFFCharsetClosure() {
  25248. function CFFCharset(predefined, format, charset, raw) {
  25249. this.predefined = predefined;
  25250. this.format = format;
  25251. this.charset = charset;
  25252. this.raw = raw;
  25253. }
  25254. return CFFCharset;
  25255. })();
  25256. var CFFEncoding = (function CFFEncodingClosure() {
  25257. function CFFEncoding(predefined, format, encoding, raw) {
  25258. this.predefined = predefined;
  25259. this.format = format;
  25260. this.encoding = encoding;
  25261. this.raw = raw;
  25262. }
  25263. return CFFEncoding;
  25264. })();
  25265. var CFFFDSelect = (function CFFFDSelectClosure() {
  25266. function CFFFDSelect(fdSelect, raw) {
  25267. this.fdSelect = fdSelect;
  25268. this.raw = raw;
  25269. }
  25270. return CFFFDSelect;
  25271. })();
  25272. // Helper class to keep track of where an offset is within the data and helps
  25273. // filling in that offset once it's known.
  25274. var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
  25275. function CFFOffsetTracker() {
  25276. this.offsets = {};
  25277. }
  25278. CFFOffsetTracker.prototype = {
  25279. isTracking: function CFFOffsetTracker_isTracking(key) {
  25280. return key in this.offsets;
  25281. },
  25282. track: function CFFOffsetTracker_track(key, location) {
  25283. if (key in this.offsets) {
  25284. error('Already tracking location of ' + key);
  25285. }
  25286. this.offsets[key] = location;
  25287. },
  25288. offset: function CFFOffsetTracker_offset(value) {
  25289. for (var key in this.offsets) {
  25290. this.offsets[key] += value;
  25291. }
  25292. },
  25293. setEntryLocation: function CFFOffsetTracker_setEntryLocation(key,
  25294. values,
  25295. output) {
  25296. if (!(key in this.offsets)) {
  25297. error('Not tracking location of ' + key);
  25298. }
  25299. var data = output.data;
  25300. var dataOffset = this.offsets[key];
  25301. var size = 5;
  25302. for (var i = 0, ii = values.length; i < ii; ++i) {
  25303. var offset0 = i * size + dataOffset;
  25304. var offset1 = offset0 + 1;
  25305. var offset2 = offset0 + 2;
  25306. var offset3 = offset0 + 3;
  25307. var offset4 = offset0 + 4;
  25308. // It's easy to screw up offsets so perform this sanity check.
  25309. if (data[offset0] !== 0x1d || data[offset1] !== 0 ||
  25310. data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
  25311. error('writing to an offset that is not empty');
  25312. }
  25313. var value = values[i];
  25314. data[offset0] = 0x1d;
  25315. data[offset1] = (value >> 24) & 0xFF;
  25316. data[offset2] = (value >> 16) & 0xFF;
  25317. data[offset3] = (value >> 8) & 0xFF;
  25318. data[offset4] = value & 0xFF;
  25319. }
  25320. }
  25321. };
  25322. return CFFOffsetTracker;
  25323. })();
  25324. // Takes a CFF and converts it to the binary representation.
  25325. var CFFCompiler = (function CFFCompilerClosure() {
  25326. function CFFCompiler(cff) {
  25327. this.cff = cff;
  25328. }
  25329. CFFCompiler.prototype = {
  25330. compile: function CFFCompiler_compile() {
  25331. var cff = this.cff;
  25332. var output = {
  25333. data: [],
  25334. length: 0,
  25335. add: function CFFCompiler_add(data) {
  25336. this.data = this.data.concat(data);
  25337. this.length = this.data.length;
  25338. }
  25339. };
  25340. // Compile the five entries that must be in order.
  25341. var header = this.compileHeader(cff.header);
  25342. output.add(header);
  25343. var nameIndex = this.compileNameIndex(cff.names);
  25344. output.add(nameIndex);
  25345. if (cff.isCIDFont) {
  25346. // The spec is unclear on how font matrices should relate to each other
  25347. // when there is one in the main top dict and the sub top dicts.
  25348. // Windows handles this differently than linux and osx so we have to
  25349. // normalize to work on all.
  25350. // Rules based off of some mailing list discussions:
  25351. // - If main font has a matrix and subfont doesn't, use the main matrix.
  25352. // - If no main font matrix and there is a subfont matrix, use the
  25353. // subfont matrix.
  25354. // - If both have matrices, concat together.
  25355. // - If neither have matrices, use default.
  25356. // To make this work on all platforms we move the top matrix into each
  25357. // sub top dict and concat if necessary.
  25358. if (cff.topDict.hasName('FontMatrix')) {
  25359. var base = cff.topDict.getByName('FontMatrix');
  25360. cff.topDict.removeByName('FontMatrix');
  25361. for (var i = 0, ii = cff.fdArray.length; i < ii; i++) {
  25362. var subDict = cff.fdArray[i];
  25363. var matrix = base.slice(0);
  25364. if (subDict.hasName('FontMatrix')) {
  25365. matrix = Util.transform(matrix, subDict.getByName('FontMatrix'));
  25366. }
  25367. subDict.setByName('FontMatrix', matrix);
  25368. }
  25369. }
  25370. }
  25371. var compiled = this.compileTopDicts([cff.topDict],
  25372. output.length,
  25373. cff.isCIDFont);
  25374. output.add(compiled.output);
  25375. var topDictTracker = compiled.trackers[0];
  25376. var stringIndex = this.compileStringIndex(cff.strings.strings);
  25377. output.add(stringIndex);
  25378. var globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
  25379. output.add(globalSubrIndex);
  25380. // Now start on the other entries that have no specfic order.
  25381. if (cff.encoding && cff.topDict.hasName('Encoding')) {
  25382. if (cff.encoding.predefined) {
  25383. topDictTracker.setEntryLocation('Encoding', [cff.encoding.format],
  25384. output);
  25385. } else {
  25386. var encoding = this.compileEncoding(cff.encoding);
  25387. topDictTracker.setEntryLocation('Encoding', [output.length], output);
  25388. output.add(encoding);
  25389. }
  25390. }
  25391. if (cff.charset && cff.topDict.hasName('charset')) {
  25392. if (cff.charset.predefined) {
  25393. topDictTracker.setEntryLocation('charset', [cff.charset.format],
  25394. output);
  25395. } else {
  25396. var charset = this.compileCharset(cff.charset);
  25397. topDictTracker.setEntryLocation('charset', [output.length], output);
  25398. output.add(charset);
  25399. }
  25400. }
  25401. var charStrings = this.compileCharStrings(cff.charStrings);
  25402. topDictTracker.setEntryLocation('CharStrings', [output.length], output);
  25403. output.add(charStrings);
  25404. if (cff.isCIDFont) {
  25405. // For some reason FDSelect must be in front of FDArray on windows. OSX
  25406. // and linux don't seem to care.
  25407. topDictTracker.setEntryLocation('FDSelect', [output.length], output);
  25408. var fdSelect = this.compileFDSelect(cff.fdSelect.raw);
  25409. output.add(fdSelect);
  25410. // It is unclear if the sub font dictionary can have CID related
  25411. // dictionary keys, but the sanitizer doesn't like them so remove them.
  25412. compiled = this.compileTopDicts(cff.fdArray, output.length, true);
  25413. topDictTracker.setEntryLocation('FDArray', [output.length], output);
  25414. output.add(compiled.output);
  25415. var fontDictTrackers = compiled.trackers;
  25416. this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
  25417. }
  25418. this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
  25419. // If the font data ends with INDEX whose object data is zero-length,
  25420. // the sanitizer will bail out. Add a dummy byte to avoid that.
  25421. output.add([0]);
  25422. return output.data;
  25423. },
  25424. encodeNumber: function CFFCompiler_encodeNumber(value) {
  25425. if (parseFloat(value) === parseInt(value, 10) && !isNaN(value)) { // isInt
  25426. return this.encodeInteger(value);
  25427. } else {
  25428. return this.encodeFloat(value);
  25429. }
  25430. },
  25431. encodeFloat: function CFFCompiler_encodeFloat(num) {
  25432. var value = num.toString();
  25433. // rounding inaccurate doubles
  25434. var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
  25435. if (m) {
  25436. var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
  25437. value = (Math.round(num * epsilon) / epsilon).toString();
  25438. }
  25439. var nibbles = '';
  25440. var i, ii;
  25441. for (i = 0, ii = value.length; i < ii; ++i) {
  25442. var a = value[i];
  25443. if (a === 'e') {
  25444. nibbles += value[++i] === '-' ? 'c' : 'b';
  25445. } else if (a === '.') {
  25446. nibbles += 'a';
  25447. } else if (a === '-') {
  25448. nibbles += 'e';
  25449. } else {
  25450. nibbles += a;
  25451. }
  25452. }
  25453. nibbles += (nibbles.length & 1) ? 'f' : 'ff';
  25454. var out = [30];
  25455. for (i = 0, ii = nibbles.length; i < ii; i += 2) {
  25456. out.push(parseInt(nibbles.substr(i, 2), 16));
  25457. }
  25458. return out;
  25459. },
  25460. encodeInteger: function CFFCompiler_encodeInteger(value) {
  25461. var code;
  25462. if (value >= -107 && value <= 107) {
  25463. code = [value + 139];
  25464. } else if (value >= 108 && value <= 1131) {
  25465. value = [value - 108];
  25466. code = [(value >> 8) + 247, value & 0xFF];
  25467. } else if (value >= -1131 && value <= -108) {
  25468. value = -value - 108;
  25469. code = [(value >> 8) + 251, value & 0xFF];
  25470. } else if (value >= -32768 && value <= 32767) {
  25471. code = [0x1c, (value >> 8) & 0xFF, value & 0xFF];
  25472. } else {
  25473. code = [0x1d,
  25474. (value >> 24) & 0xFF,
  25475. (value >> 16) & 0xFF,
  25476. (value >> 8) & 0xFF,
  25477. value & 0xFF];
  25478. }
  25479. return code;
  25480. },
  25481. compileHeader: function CFFCompiler_compileHeader(header) {
  25482. return [
  25483. header.major,
  25484. header.minor,
  25485. header.hdrSize,
  25486. header.offSize
  25487. ];
  25488. },
  25489. compileNameIndex: function CFFCompiler_compileNameIndex(names) {
  25490. var nameIndex = new CFFIndex();
  25491. for (var i = 0, ii = names.length; i < ii; ++i) {
  25492. nameIndex.add(stringToBytes(names[i]));
  25493. }
  25494. return this.compileIndex(nameIndex);
  25495. },
  25496. compileTopDicts: function CFFCompiler_compileTopDicts(dicts,
  25497. length,
  25498. removeCidKeys) {
  25499. var fontDictTrackers = [];
  25500. var fdArrayIndex = new CFFIndex();
  25501. for (var i = 0, ii = dicts.length; i < ii; ++i) {
  25502. var fontDict = dicts[i];
  25503. if (removeCidKeys) {
  25504. fontDict.removeByName('CIDFontVersion');
  25505. fontDict.removeByName('CIDFontRevision');
  25506. fontDict.removeByName('CIDFontType');
  25507. fontDict.removeByName('CIDCount');
  25508. fontDict.removeByName('UIDBase');
  25509. }
  25510. var fontDictTracker = new CFFOffsetTracker();
  25511. var fontDictData = this.compileDict(fontDict, fontDictTracker);
  25512. fontDictTrackers.push(fontDictTracker);
  25513. fdArrayIndex.add(fontDictData);
  25514. fontDictTracker.offset(length);
  25515. }
  25516. fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
  25517. return {
  25518. trackers: fontDictTrackers,
  25519. output: fdArrayIndex
  25520. };
  25521. },
  25522. compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts,
  25523. trackers,
  25524. output) {
  25525. for (var i = 0, ii = dicts.length; i < ii; ++i) {
  25526. var fontDict = dicts[i];
  25527. assert(fontDict.privateDict && fontDict.hasName('Private'),
  25528. 'There must be an private dictionary.');
  25529. var privateDict = fontDict.privateDict;
  25530. var privateDictTracker = new CFFOffsetTracker();
  25531. var privateDictData = this.compileDict(privateDict, privateDictTracker);
  25532. var outputLength = output.length;
  25533. privateDictTracker.offset(outputLength);
  25534. if (!privateDictData.length) {
  25535. // The private dictionary was empty, set the output length to zero to
  25536. // ensure the offset length isn't out of bounds in the eyes of the
  25537. // sanitizer.
  25538. outputLength = 0;
  25539. }
  25540. trackers[i].setEntryLocation('Private',
  25541. [privateDictData.length, outputLength],
  25542. output);
  25543. output.add(privateDictData);
  25544. if (privateDict.subrsIndex && privateDict.hasName('Subrs')) {
  25545. var subrs = this.compileIndex(privateDict.subrsIndex);
  25546. privateDictTracker.setEntryLocation('Subrs', [privateDictData.length],
  25547. output);
  25548. output.add(subrs);
  25549. }
  25550. }
  25551. },
  25552. compileDict: function CFFCompiler_compileDict(dict, offsetTracker) {
  25553. var out = [];
  25554. // The dictionary keys must be in a certain order.
  25555. var order = dict.order;
  25556. for (var i = 0; i < order.length; ++i) {
  25557. var key = order[i];
  25558. if (!(key in dict.values)) {
  25559. continue;
  25560. }
  25561. var values = dict.values[key];
  25562. var types = dict.types[key];
  25563. if (!isArray(types)) {
  25564. types = [types];
  25565. }
  25566. if (!isArray(values)) {
  25567. values = [values];
  25568. }
  25569. // Remove any empty dict values.
  25570. if (values.length === 0) {
  25571. continue;
  25572. }
  25573. for (var j = 0, jj = types.length; j < jj; ++j) {
  25574. var type = types[j];
  25575. var value = values[j];
  25576. switch (type) {
  25577. case 'num':
  25578. case 'sid':
  25579. out = out.concat(this.encodeNumber(value));
  25580. break;
  25581. case 'offset':
  25582. // For offsets we just insert a 32bit integer so we don't have to
  25583. // deal with figuring out the length of the offset when it gets
  25584. // replaced later on by the compiler.
  25585. var name = dict.keyToNameMap[key];
  25586. // Some offsets have the offset and the length, so just record the
  25587. // position of the first one.
  25588. if (!offsetTracker.isTracking(name)) {
  25589. offsetTracker.track(name, out.length);
  25590. }
  25591. out = out.concat([0x1d, 0, 0, 0, 0]);
  25592. break;
  25593. case 'array':
  25594. case 'delta':
  25595. out = out.concat(this.encodeNumber(value));
  25596. for (var k = 1, kk = values.length; k < kk; ++k) {
  25597. out = out.concat(this.encodeNumber(values[k]));
  25598. }
  25599. break;
  25600. default:
  25601. error('Unknown data type of ' + type);
  25602. break;
  25603. }
  25604. }
  25605. out = out.concat(dict.opcodes[key]);
  25606. }
  25607. return out;
  25608. },
  25609. compileStringIndex: function CFFCompiler_compileStringIndex(strings) {
  25610. var stringIndex = new CFFIndex();
  25611. for (var i = 0, ii = strings.length; i < ii; ++i) {
  25612. stringIndex.add(stringToBytes(strings[i]));
  25613. }
  25614. return this.compileIndex(stringIndex);
  25615. },
  25616. compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() {
  25617. var globalSubrIndex = this.cff.globalSubrIndex;
  25618. this.out.writeByteArray(this.compileIndex(globalSubrIndex));
  25619. },
  25620. compileCharStrings: function CFFCompiler_compileCharStrings(charStrings) {
  25621. return this.compileIndex(charStrings);
  25622. },
  25623. compileCharset: function CFFCompiler_compileCharset(charset) {
  25624. return this.compileTypedArray(charset.raw);
  25625. },
  25626. compileEncoding: function CFFCompiler_compileEncoding(encoding) {
  25627. return this.compileTypedArray(encoding.raw);
  25628. },
  25629. compileFDSelect: function CFFCompiler_compileFDSelect(fdSelect) {
  25630. return this.compileTypedArray(fdSelect);
  25631. },
  25632. compileTypedArray: function CFFCompiler_compileTypedArray(data) {
  25633. var out = [];
  25634. for (var i = 0, ii = data.length; i < ii; ++i) {
  25635. out[i] = data[i];
  25636. }
  25637. return out;
  25638. },
  25639. compileIndex: function CFFCompiler_compileIndex(index, trackers) {
  25640. trackers = trackers || [];
  25641. var objects = index.objects;
  25642. // First 2 bytes contains the number of objects contained into this index
  25643. var count = objects.length;
  25644. // If there is no object, just create an index. This technically
  25645. // should just be [0, 0] but OTS has an issue with that.
  25646. if (count === 0) {
  25647. return [0, 0, 0];
  25648. }
  25649. var data = [(count >> 8) & 0xFF, count & 0xff];
  25650. var lastOffset = 1, i;
  25651. for (i = 0; i < count; ++i) {
  25652. lastOffset += objects[i].length;
  25653. }
  25654. var offsetSize;
  25655. if (lastOffset < 0x100) {
  25656. offsetSize = 1;
  25657. } else if (lastOffset < 0x10000) {
  25658. offsetSize = 2;
  25659. } else if (lastOffset < 0x1000000) {
  25660. offsetSize = 3;
  25661. } else {
  25662. offsetSize = 4;
  25663. }
  25664. // Next byte contains the offset size use to reference object in the file
  25665. data.push(offsetSize);
  25666. // Add another offset after this one because we need a new offset
  25667. var relativeOffset = 1;
  25668. for (i = 0; i < count + 1; i++) {
  25669. if (offsetSize === 1) {
  25670. data.push(relativeOffset & 0xFF);
  25671. } else if (offsetSize === 2) {
  25672. data.push((relativeOffset >> 8) & 0xFF,
  25673. relativeOffset & 0xFF);
  25674. } else if (offsetSize === 3) {
  25675. data.push((relativeOffset >> 16) & 0xFF,
  25676. (relativeOffset >> 8) & 0xFF,
  25677. relativeOffset & 0xFF);
  25678. } else {
  25679. data.push((relativeOffset >>> 24) & 0xFF,
  25680. (relativeOffset >> 16) & 0xFF,
  25681. (relativeOffset >> 8) & 0xFF,
  25682. relativeOffset & 0xFF);
  25683. }
  25684. if (objects[i]) {
  25685. relativeOffset += objects[i].length;
  25686. }
  25687. }
  25688. for (i = 0; i < count; i++) {
  25689. // Notify the tracker where the object will be offset in the data.
  25690. if (trackers[i]) {
  25691. trackers[i].offset(data.length);
  25692. }
  25693. for (var j = 0, jj = objects[i].length; j < jj; j++) {
  25694. data.push(objects[i][j]);
  25695. }
  25696. }
  25697. return data;
  25698. }
  25699. };
  25700. return CFFCompiler;
  25701. })();
  25702. // Workaround for seac on Windows.
  25703. (function checkSeacSupport() {
  25704. if (/Windows/.test(navigator.userAgent)) {
  25705. SEAC_ANALYSIS_ENABLED = true;
  25706. }
  25707. })();
  25708. // Workaround for Private Use Area characters in Chrome on Windows
  25709. // http://code.google.com/p/chromium/issues/detail?id=122465
  25710. // https://github.com/mozilla/pdf.js/issues/1689
  25711. (function checkChromeWindows() {
  25712. if (/Windows.*Chrome/.test(navigator.userAgent)) {
  25713. SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = true;
  25714. }
  25715. })();
  25716. var FontRendererFactory = (function FontRendererFactoryClosure() {
  25717. function getLong(data, offset) {
  25718. return (data[offset] << 24) | (data[offset + 1] << 16) |
  25719. (data[offset + 2] << 8) | data[offset + 3];
  25720. }
  25721. function getUshort(data, offset) {
  25722. return (data[offset] << 8) | data[offset + 1];
  25723. }
  25724. function parseCmap(data, start, end) {
  25725. var offset = (getUshort(data, start + 2) === 1 ?
  25726. getLong(data, start + 8) : getLong(data, start + 16));
  25727. var format = getUshort(data, start + offset);
  25728. var length, ranges, p, i;
  25729. if (format === 4) {
  25730. length = getUshort(data, start + offset + 2);
  25731. var segCount = getUshort(data, start + offset + 6) >> 1;
  25732. p = start + offset + 14;
  25733. ranges = [];
  25734. for (i = 0; i < segCount; i++, p += 2) {
  25735. ranges[i] = {end: getUshort(data, p)};
  25736. }
  25737. p += 2;
  25738. for (i = 0; i < segCount; i++, p += 2) {
  25739. ranges[i].start = getUshort(data, p);
  25740. }
  25741. for (i = 0; i < segCount; i++, p += 2) {
  25742. ranges[i].idDelta = getUshort(data, p);
  25743. }
  25744. for (i = 0; i < segCount; i++, p += 2) {
  25745. var idOffset = getUshort(data, p);
  25746. if (idOffset === 0) {
  25747. continue;
  25748. }
  25749. ranges[i].ids = [];
  25750. for (var j = 0, jj = ranges[i].end - ranges[i].start + 1; j < jj; j++) {
  25751. ranges[i].ids[j] = getUshort(data, p + idOffset);
  25752. idOffset += 2;
  25753. }
  25754. }
  25755. return ranges;
  25756. } else if (format === 12) {
  25757. length = getLong(data, start + offset + 4);
  25758. var groups = getLong(data, start + offset + 12);
  25759. p = start + offset + 16;
  25760. ranges = [];
  25761. for (i = 0; i < groups; i++) {
  25762. ranges.push({
  25763. start: getLong(data, p),
  25764. end: getLong(data, p + 4),
  25765. idDelta: getLong(data, p + 8) - getLong(data, p)
  25766. });
  25767. p += 12;
  25768. }
  25769. return ranges;
  25770. }
  25771. error('not supported cmap: ' + format);
  25772. }
  25773. function parseCff(data, start, end) {
  25774. var properties = {};
  25775. var parser = new CFFParser(new Stream(data, start, end - start),
  25776. properties);
  25777. var cff = parser.parse();
  25778. return {
  25779. glyphs: cff.charStrings.objects,
  25780. subrs: (cff.topDict.privateDict && cff.topDict.privateDict.subrsIndex &&
  25781. cff.topDict.privateDict.subrsIndex.objects),
  25782. gsubrs: cff.globalSubrIndex && cff.globalSubrIndex.objects
  25783. };
  25784. }
  25785. function parseGlyfTable(glyf, loca, isGlyphLocationsLong) {
  25786. var itemSize, itemDecode;
  25787. if (isGlyphLocationsLong) {
  25788. itemSize = 4;
  25789. itemDecode = function fontItemDecodeLong(data, offset) {
  25790. return (data[offset] << 24) | (data[offset + 1] << 16) |
  25791. (data[offset + 2] << 8) | data[offset + 3];
  25792. };
  25793. } else {
  25794. itemSize = 2;
  25795. itemDecode = function fontItemDecode(data, offset) {
  25796. return (data[offset] << 9) | (data[offset + 1] << 1);
  25797. };
  25798. }
  25799. var glyphs = [];
  25800. var startOffset = itemDecode(loca, 0);
  25801. for (var j = itemSize; j < loca.length; j += itemSize) {
  25802. var endOffset = itemDecode(loca, j);
  25803. glyphs.push(glyf.subarray(startOffset, endOffset));
  25804. startOffset = endOffset;
  25805. }
  25806. return glyphs;
  25807. }
  25808. function lookupCmap(ranges, unicode) {
  25809. var code = unicode.charCodeAt(0);
  25810. var l = 0, r = ranges.length - 1;
  25811. while (l < r) {
  25812. var c = (l + r + 1) >> 1;
  25813. if (code < ranges[c].start) {
  25814. r = c - 1;
  25815. } else {
  25816. l = c;
  25817. }
  25818. }
  25819. if (ranges[l].start <= code && code <= ranges[l].end) {
  25820. return (ranges[l].idDelta + (ranges[l].ids ?
  25821. ranges[l].ids[code - ranges[l].start] : code)) & 0xFFFF;
  25822. }
  25823. return 0;
  25824. }
  25825. function compileGlyf(code, js, font) {
  25826. function moveTo(x, y) {
  25827. js.push('c.moveTo(' + x + ',' + y + ');');
  25828. }
  25829. function lineTo(x, y) {
  25830. js.push('c.lineTo(' + x + ',' + y + ');');
  25831. }
  25832. function quadraticCurveTo(xa, ya, x, y) {
  25833. js.push('c.quadraticCurveTo(' + xa + ',' + ya + ',' +
  25834. x + ',' + y + ');');
  25835. }
  25836. var i = 0;
  25837. var numberOfContours = ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25838. var flags;
  25839. var x = 0, y = 0;
  25840. i += 10;
  25841. if (numberOfContours < 0) {
  25842. // composite glyph
  25843. do {
  25844. flags = (code[i] << 8) | code[i + 1];
  25845. var glyphIndex = (code[i + 2] << 8) | code[i + 3];
  25846. i += 4;
  25847. var arg1, arg2;
  25848. if ((flags & 0x01)) {
  25849. arg1 = ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25850. arg2 = ((code[i + 2] << 24) | (code[i + 3] << 16)) >> 16;
  25851. i += 4;
  25852. } else {
  25853. arg1 = code[i++]; arg2 = code[i++];
  25854. }
  25855. if ((flags & 0x02)) {
  25856. x = arg1;
  25857. y = arg2;
  25858. } else {
  25859. x = 0; y = 0; // TODO "they are points" ?
  25860. }
  25861. var scaleX = 1, scaleY = 1, scale01 = 0, scale10 = 0;
  25862. if ((flags & 0x08)) {
  25863. scaleX =
  25864. scaleY = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  25865. i += 2;
  25866. } else if ((flags & 0x40)) {
  25867. scaleX = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  25868. scaleY = ((code[i + 2] << 24) | (code[i + 3] << 16)) / 1073741824;
  25869. i += 4;
  25870. } else if ((flags & 0x80)) {
  25871. scaleX = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  25872. scale01 = ((code[i + 2] << 24) | (code[i + 3] << 16)) / 1073741824;
  25873. scale10 = ((code[i + 4] << 24) | (code[i + 5] << 16)) / 1073741824;
  25874. scaleY = ((code[i + 6] << 24) | (code[i + 7] << 16)) / 1073741824;
  25875. i += 8;
  25876. }
  25877. var subglyph = font.glyphs[glyphIndex];
  25878. if (subglyph) {
  25879. js.push('c.save();');
  25880. js.push('c.transform(' + scaleX + ',' + scale01 + ',' +
  25881. scale10 + ',' + scaleY + ',' + x + ',' + y + ');');
  25882. compileGlyf(subglyph, js, font);
  25883. js.push('c.restore();');
  25884. }
  25885. } while ((flags & 0x20));
  25886. } else {
  25887. // simple glyph
  25888. var endPtsOfContours = [];
  25889. var j, jj;
  25890. for (j = 0; j < numberOfContours; j++) {
  25891. endPtsOfContours.push((code[i] << 8) | code[i + 1]);
  25892. i += 2;
  25893. }
  25894. var instructionLength = (code[i] << 8) | code[i + 1];
  25895. i += 2 + instructionLength; // skipping the instructions
  25896. var numberOfPoints = endPtsOfContours[endPtsOfContours.length - 1] + 1;
  25897. var points = [];
  25898. while (points.length < numberOfPoints) {
  25899. flags = code[i++];
  25900. var repeat = 1;
  25901. if ((flags & 0x08)) {
  25902. repeat += code[i++];
  25903. }
  25904. while (repeat-- > 0) {
  25905. points.push({flags: flags});
  25906. }
  25907. }
  25908. for (j = 0; j < numberOfPoints; j++) {
  25909. switch (points[j].flags & 0x12) {
  25910. case 0x00:
  25911. x += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25912. i += 2;
  25913. break;
  25914. case 0x02:
  25915. x -= code[i++];
  25916. break;
  25917. case 0x12:
  25918. x += code[i++];
  25919. break;
  25920. }
  25921. points[j].x = x;
  25922. }
  25923. for (j = 0; j < numberOfPoints; j++) {
  25924. switch (points[j].flags & 0x24) {
  25925. case 0x00:
  25926. y += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25927. i += 2;
  25928. break;
  25929. case 0x04:
  25930. y -= code[i++];
  25931. break;
  25932. case 0x24:
  25933. y += code[i++];
  25934. break;
  25935. }
  25936. points[j].y = y;
  25937. }
  25938. var startPoint = 0;
  25939. for (i = 0; i < numberOfContours; i++) {
  25940. var endPoint = endPtsOfContours[i];
  25941. // contours might have implicit points, which is located in the middle
  25942. // between two neighboring off-curve points
  25943. var contour = points.slice(startPoint, endPoint + 1);
  25944. if ((contour[0].flags & 1)) {
  25945. contour.push(contour[0]); // using start point at the contour end
  25946. } else if ((contour[contour.length - 1].flags & 1)) {
  25947. // first is off-curve point, trying to use one from the end
  25948. contour.unshift(contour[contour.length - 1]);
  25949. } else {
  25950. // start and end are off-curve points, creating implicit one
  25951. var p = {
  25952. flags: 1,
  25953. x: (contour[0].x + contour[contour.length - 1].x) / 2,
  25954. y: (contour[0].y + contour[contour.length - 1].y) / 2
  25955. };
  25956. contour.unshift(p);
  25957. contour.push(p);
  25958. }
  25959. moveTo(contour[0].x, contour[0].y);
  25960. for (j = 1, jj = contour.length; j < jj; j++) {
  25961. if ((contour[j].flags & 1)) {
  25962. lineTo(contour[j].x, contour[j].y);
  25963. } else if ((contour[j + 1].flags & 1)){
  25964. quadraticCurveTo(contour[j].x, contour[j].y,
  25965. contour[j + 1].x, contour[j + 1].y);
  25966. j++;
  25967. } else {
  25968. quadraticCurveTo(contour[j].x, contour[j].y,
  25969. (contour[j].x + contour[j + 1].x) / 2,
  25970. (contour[j].y + contour[j + 1].y) / 2);
  25971. }
  25972. }
  25973. startPoint = endPoint + 1;
  25974. }
  25975. }
  25976. }
  25977. function compileCharString(code, js, font) {
  25978. var stack = [];
  25979. var x = 0, y = 0;
  25980. var stems = 0;
  25981. function moveTo(x, y) {
  25982. js.push('c.moveTo(' + x + ',' + y + ');');
  25983. }
  25984. function lineTo(x, y) {
  25985. js.push('c.lineTo(' + x + ',' + y + ');');
  25986. }
  25987. function bezierCurveTo(x1, y1, x2, y2, x, y) {
  25988. js.push('c.bezierCurveTo(' + x1 + ',' + y1 + ',' + x2 + ',' + y2 + ',' +
  25989. x + ',' + y + ');');
  25990. }
  25991. function parse(code) {
  25992. var i = 0;
  25993. while (i < code.length) {
  25994. var stackClean = false;
  25995. var v = code[i++];
  25996. var xa, xb, ya, yb, y1, y2, y3, n, subrCode;
  25997. switch (v) {
  25998. case 1: // hstem
  25999. stems += stack.length >> 1;
  26000. stackClean = true;
  26001. break;
  26002. case 3: // vstem
  26003. stems += stack.length >> 1;
  26004. stackClean = true;
  26005. break;
  26006. case 4: // vmoveto
  26007. y += stack.pop();
  26008. moveTo(x, y);
  26009. stackClean = true;
  26010. break;
  26011. case 5: // rlineto
  26012. while (stack.length > 0) {
  26013. x += stack.shift();
  26014. y += stack.shift();
  26015. lineTo(x, y);
  26016. }
  26017. break;
  26018. case 6: // hlineto
  26019. while (stack.length > 0) {
  26020. x += stack.shift();
  26021. lineTo(x, y);
  26022. if (stack.length === 0) {
  26023. break;
  26024. }
  26025. y += stack.shift();
  26026. lineTo(x, y);
  26027. }
  26028. break;
  26029. case 7: // vlineto
  26030. while (stack.length > 0) {
  26031. y += stack.shift();
  26032. lineTo(x, y);
  26033. if (stack.length === 0) {
  26034. break;
  26035. }
  26036. x += stack.shift();
  26037. lineTo(x, y);
  26038. }
  26039. break;
  26040. case 8: // rrcurveto
  26041. while (stack.length > 0) {
  26042. xa = x + stack.shift(); ya = y + stack.shift();
  26043. xb = xa + stack.shift(); yb = ya + stack.shift();
  26044. x = xb + stack.shift(); y = yb + stack.shift();
  26045. bezierCurveTo(xa, ya, xb, yb, x, y);
  26046. }
  26047. break;
  26048. case 10: // callsubr
  26049. n = stack.pop() + font.subrsBias;
  26050. subrCode = font.subrs[n];
  26051. if (subrCode) {
  26052. parse(subrCode);
  26053. }
  26054. break;
  26055. case 11: // return
  26056. return;
  26057. case 12:
  26058. v = code[i++];
  26059. switch (v) {
  26060. case 34: // flex
  26061. xa = x + stack.shift();
  26062. xb = xa + stack.shift(); y1 = y + stack.shift();
  26063. x = xb + stack.shift();
  26064. bezierCurveTo(xa, y, xb, y1, x, y1);
  26065. xa = x + stack.shift();
  26066. xb = xa + stack.shift();
  26067. x = xb + stack.shift();
  26068. bezierCurveTo(xa, y1, xb, y, x, y);
  26069. break;
  26070. case 35: // flex
  26071. xa = x + stack.shift(); ya = y + stack.shift();
  26072. xb = xa + stack.shift(); yb = ya + stack.shift();
  26073. x = xb + stack.shift(); y = yb + stack.shift();
  26074. bezierCurveTo(xa, ya, xb, yb, x, y);
  26075. xa = x + stack.shift(); ya = y + stack.shift();
  26076. xb = xa + stack.shift(); yb = ya + stack.shift();
  26077. x = xb + stack.shift(); y = yb + stack.shift();
  26078. bezierCurveTo(xa, ya, xb, yb, x, y);
  26079. stack.pop(); // fd
  26080. break;
  26081. case 36: // hflex1
  26082. xa = x + stack.shift(); y1 = y + stack.shift();
  26083. xb = xa + stack.shift(); y2 = y1 + stack.shift();
  26084. x = xb + stack.shift();
  26085. bezierCurveTo(xa, y1, xb, y2, x, y2);
  26086. xa = x + stack.shift();
  26087. xb = xa + stack.shift(); y3 = y2 + stack.shift();
  26088. x = xb + stack.shift();
  26089. bezierCurveTo(xa, y2, xb, y3, x, y);
  26090. break;
  26091. case 37: // flex1
  26092. var x0 = x, y0 = y;
  26093. xa = x + stack.shift(); ya = y + stack.shift();
  26094. xb = xa + stack.shift(); yb = ya + stack.shift();
  26095. x = xb + stack.shift(); y = yb + stack.shift();
  26096. bezierCurveTo(xa, ya, xb, yb, x, y);
  26097. xa = x + stack.shift(); ya = y + stack.shift();
  26098. xb = xa + stack.shift(); yb = ya + stack.shift();
  26099. x = xb; y = yb;
  26100. if (Math.abs(x - x0) > Math.abs(y - y0)) {
  26101. x += stack.shift();
  26102. } else {
  26103. y += stack.shift();
  26104. }
  26105. bezierCurveTo(xa, ya, xb, yb, x, y);
  26106. break;
  26107. default:
  26108. error('unknown operator: 12 ' + v);
  26109. }
  26110. break;
  26111. case 14: // endchar
  26112. if (stack.length >= 4) {
  26113. var achar = stack.pop();
  26114. var bchar = stack.pop();
  26115. y = stack.pop();
  26116. x = stack.pop();
  26117. js.push('c.save();');
  26118. js.push('c.translate('+ x + ',' + y + ');');
  26119. var gid = lookupCmap(font.cmap, String.fromCharCode(
  26120. font.glyphNameMap[Encodings.StandardEncoding[achar]]));
  26121. compileCharString(font.glyphs[gid], js, font);
  26122. js.push('c.restore();');
  26123. gid = lookupCmap(font.cmap, String.fromCharCode(
  26124. font.glyphNameMap[Encodings.StandardEncoding[bchar]]));
  26125. compileCharString(font.glyphs[gid], js, font);
  26126. }
  26127. return;
  26128. case 18: // hstemhm
  26129. stems += stack.length >> 1;
  26130. stackClean = true;
  26131. break;
  26132. case 19: // hintmask
  26133. stems += stack.length >> 1;
  26134. i += (stems + 7) >> 3;
  26135. stackClean = true;
  26136. break;
  26137. case 20: // cntrmask
  26138. stems += stack.length >> 1;
  26139. i += (stems + 7) >> 3;
  26140. stackClean = true;
  26141. break;
  26142. case 21: // rmoveto
  26143. y += stack.pop();
  26144. x += stack.pop();
  26145. moveTo(x, y);
  26146. stackClean = true;
  26147. break;
  26148. case 22: // hmoveto
  26149. x += stack.pop();
  26150. moveTo(x, y);
  26151. stackClean = true;
  26152. break;
  26153. case 23: // vstemhm
  26154. stems += stack.length >> 1;
  26155. stackClean = true;
  26156. break;
  26157. case 24: // rcurveline
  26158. while (stack.length > 2) {
  26159. xa = x + stack.shift(); ya = y + stack.shift();
  26160. xb = xa + stack.shift(); yb = ya + stack.shift();
  26161. x = xb + stack.shift(); y = yb + stack.shift();
  26162. bezierCurveTo(xa, ya, xb, yb, x, y);
  26163. }
  26164. x += stack.shift();
  26165. y += stack.shift();
  26166. lineTo(x, y);
  26167. break;
  26168. case 25: // rlinecurve
  26169. while (stack.length > 6) {
  26170. x += stack.shift();
  26171. y += stack.shift();
  26172. lineTo(x, y);
  26173. }
  26174. xa = x + stack.shift(); ya = y + stack.shift();
  26175. xb = xa + stack.shift(); yb = ya + stack.shift();
  26176. x = xb + stack.shift(); y = yb + stack.shift();
  26177. bezierCurveTo(xa, ya, xb, yb, x, y);
  26178. break;
  26179. case 26: // vvcurveto
  26180. if (stack.length % 2) {
  26181. x += stack.shift();
  26182. }
  26183. while (stack.length > 0) {
  26184. xa = x; ya = y + stack.shift();
  26185. xb = xa + stack.shift(); yb = ya + stack.shift();
  26186. x = xb; y = yb + stack.shift();
  26187. bezierCurveTo(xa, ya, xb, yb, x, y);
  26188. }
  26189. break;
  26190. case 27: // hhcurveto
  26191. if (stack.length % 2) {
  26192. y += stack.shift();
  26193. }
  26194. while (stack.length > 0) {
  26195. xa = x + stack.shift(); ya = y;
  26196. xb = xa + stack.shift(); yb = ya + stack.shift();
  26197. x = xb + stack.shift(); y = yb;
  26198. bezierCurveTo(xa, ya, xb, yb, x, y);
  26199. }
  26200. break;
  26201. case 28:
  26202. stack.push(((code[i] << 24) | (code[i + 1] << 16)) >> 16);
  26203. i += 2;
  26204. break;
  26205. case 29: // callgsubr
  26206. n = stack.pop() + font.gsubrsBias;
  26207. subrCode = font.gsubrs[n];
  26208. if (subrCode) {
  26209. parse(subrCode);
  26210. }
  26211. break;
  26212. case 30: // vhcurveto
  26213. while (stack.length > 0) {
  26214. xa = x; ya = y + stack.shift();
  26215. xb = xa + stack.shift(); yb = ya + stack.shift();
  26216. x = xb + stack.shift();
  26217. y = yb + (stack.length === 1 ? stack.shift() : 0);
  26218. bezierCurveTo(xa, ya, xb, yb, x, y);
  26219. if (stack.length === 0) {
  26220. break;
  26221. }
  26222. xa = x + stack.shift(); ya = y;
  26223. xb = xa + stack.shift(); yb = ya + stack.shift();
  26224. y = yb + stack.shift();
  26225. x = xb + (stack.length === 1 ? stack.shift() : 0);
  26226. bezierCurveTo(xa, ya, xb, yb, x, y);
  26227. }
  26228. break;
  26229. case 31: // hvcurveto
  26230. while (stack.length > 0) {
  26231. xa = x + stack.shift(); ya = y;
  26232. xb = xa + stack.shift(); yb = ya + stack.shift();
  26233. y = yb + stack.shift();
  26234. x = xb + (stack.length === 1 ? stack.shift() : 0);
  26235. bezierCurveTo(xa, ya, xb, yb, x, y);
  26236. if (stack.length === 0) {
  26237. break;
  26238. }
  26239. xa = x; ya = y + stack.shift();
  26240. xb = xa + stack.shift(); yb = ya + stack.shift();
  26241. x = xb + stack.shift();
  26242. y = yb + (stack.length === 1 ? stack.shift() : 0);
  26243. bezierCurveTo(xa, ya, xb, yb, x, y);
  26244. }
  26245. break;
  26246. default:
  26247. if (v < 32) {
  26248. error('unknown operator: ' + v);
  26249. }
  26250. if (v < 247) {
  26251. stack.push(v - 139);
  26252. } else if (v < 251) {
  26253. stack.push((v - 247) * 256 + code[i++] + 108);
  26254. } else if (v < 255) {
  26255. stack.push(-(v - 251) * 256 - code[i++] - 108);
  26256. } else {
  26257. stack.push(((code[i] << 24) | (code[i + 1] << 16) |
  26258. (code[i + 2] << 8) | code[i + 3]) / 65536);
  26259. i += 4;
  26260. }
  26261. break;
  26262. }
  26263. if (stackClean) {
  26264. stack.length = 0;
  26265. }
  26266. }
  26267. }
  26268. parse(code);
  26269. }
  26270. var noop = '';
  26271. function CompiledFont(fontMatrix) {
  26272. this.compiledGlyphs = {};
  26273. this.fontMatrix = fontMatrix;
  26274. }
  26275. CompiledFont.prototype = {
  26276. getPathJs: function (unicode) {
  26277. var gid = lookupCmap(this.cmap, unicode);
  26278. var fn = this.compiledGlyphs[gid];
  26279. if (!fn) {
  26280. this.compiledGlyphs[gid] = fn = this.compileGlyph(this.glyphs[gid]);
  26281. }
  26282. return fn;
  26283. },
  26284. compileGlyph: function (code) {
  26285. if (!code || code.length === 0 || code[0] === 14) {
  26286. return noop;
  26287. }
  26288. var js = [];
  26289. js.push('c.save();');
  26290. js.push('c.transform(' + this.fontMatrix.join(',') + ');');
  26291. js.push('c.scale(size, -size);');
  26292. this.compileGlyphImpl(code, js);
  26293. js.push('c.restore();');
  26294. return js.join('\n');
  26295. },
  26296. compileGlyphImpl: function () {
  26297. error('Children classes should implement this.');
  26298. },
  26299. hasBuiltPath: function (unicode) {
  26300. var gid = lookupCmap(this.cmap, unicode);
  26301. return gid in this.compiledGlyphs;
  26302. }
  26303. };
  26304. function TrueTypeCompiled(glyphs, cmap, fontMatrix) {
  26305. fontMatrix = fontMatrix || [0.000488, 0, 0, 0.000488, 0, 0];
  26306. CompiledFont.call(this, fontMatrix);
  26307. this.glyphs = glyphs;
  26308. this.cmap = cmap;
  26309. this.compiledGlyphs = [];
  26310. }
  26311. Util.inherit(TrueTypeCompiled, CompiledFont, {
  26312. compileGlyphImpl: function (code, js) {
  26313. compileGlyf(code, js, this);
  26314. }
  26315. });
  26316. function Type2Compiled(cffInfo, cmap, fontMatrix, glyphNameMap) {
  26317. fontMatrix = fontMatrix || [0.001, 0, 0, 0.001, 0, 0];
  26318. CompiledFont.call(this, fontMatrix);
  26319. this.glyphs = cffInfo.glyphs;
  26320. this.gsubrs = cffInfo.gsubrs || [];
  26321. this.subrs = cffInfo.subrs || [];
  26322. this.cmap = cmap;
  26323. this.glyphNameMap = glyphNameMap || GlyphsUnicode;
  26324. this.compiledGlyphs = [];
  26325. this.gsubrsBias = (this.gsubrs.length < 1240 ?
  26326. 107 : (this.gsubrs.length < 33900 ? 1131 : 32768));
  26327. this.subrsBias = (this.subrs.length < 1240 ?
  26328. 107 : (this.subrs.length < 33900 ? 1131 : 32768));
  26329. }
  26330. Util.inherit(Type2Compiled, CompiledFont, {
  26331. compileGlyphImpl: function (code, js) {
  26332. compileCharString(code, js, this);
  26333. }
  26334. });
  26335. return {
  26336. create: function FontRendererFactory_create(font) {
  26337. var data = new Uint8Array(font.data);
  26338. var cmap, glyf, loca, cff, indexToLocFormat, unitsPerEm;
  26339. var numTables = getUshort(data, 4);
  26340. for (var i = 0, p = 12; i < numTables; i++, p += 16) {
  26341. var tag = bytesToString(data.subarray(p, p + 4));
  26342. var offset = getLong(data, p + 8);
  26343. var length = getLong(data, p + 12);
  26344. switch (tag) {
  26345. case 'cmap':
  26346. cmap = parseCmap(data, offset, offset + length);
  26347. break;
  26348. case 'glyf':
  26349. glyf = data.subarray(offset, offset + length);
  26350. break;
  26351. case 'loca':
  26352. loca = data.subarray(offset, offset + length);
  26353. break;
  26354. case 'head':
  26355. unitsPerEm = getUshort(data, offset + 18);
  26356. indexToLocFormat = getUshort(data, offset + 50);
  26357. break;
  26358. case 'CFF ':
  26359. cff = parseCff(data, offset, offset + length);
  26360. break;
  26361. }
  26362. }
  26363. if (glyf) {
  26364. var fontMatrix = (!unitsPerEm ? font.fontMatrix :
  26365. [1 / unitsPerEm, 0, 0, 1 / unitsPerEm, 0, 0]);
  26366. return new TrueTypeCompiled(
  26367. parseGlyfTable(glyf, loca, indexToLocFormat), cmap, fontMatrix);
  26368. } else {
  26369. return new Type2Compiled(cff, cmap, font.fontMatrix, font.glyphNameMap);
  26370. }
  26371. }
  26372. };
  26373. })();
  26374. var GlyphsUnicode = {
  26375. A: 0x0041,
  26376. AE: 0x00C6,
  26377. AEacute: 0x01FC,
  26378. AEmacron: 0x01E2,
  26379. AEsmall: 0xF7E6,
  26380. Aacute: 0x00C1,
  26381. Aacutesmall: 0xF7E1,
  26382. Abreve: 0x0102,
  26383. Abreveacute: 0x1EAE,
  26384. Abrevecyrillic: 0x04D0,
  26385. Abrevedotbelow: 0x1EB6,
  26386. Abrevegrave: 0x1EB0,
  26387. Abrevehookabove: 0x1EB2,
  26388. Abrevetilde: 0x1EB4,
  26389. Acaron: 0x01CD,
  26390. Acircle: 0x24B6,
  26391. Acircumflex: 0x00C2,
  26392. Acircumflexacute: 0x1EA4,
  26393. Acircumflexdotbelow: 0x1EAC,
  26394. Acircumflexgrave: 0x1EA6,
  26395. Acircumflexhookabove: 0x1EA8,
  26396. Acircumflexsmall: 0xF7E2,
  26397. Acircumflextilde: 0x1EAA,
  26398. Acute: 0xF6C9,
  26399. Acutesmall: 0xF7B4,
  26400. Acyrillic: 0x0410,
  26401. Adblgrave: 0x0200,
  26402. Adieresis: 0x00C4,
  26403. Adieresiscyrillic: 0x04D2,
  26404. Adieresismacron: 0x01DE,
  26405. Adieresissmall: 0xF7E4,
  26406. Adotbelow: 0x1EA0,
  26407. Adotmacron: 0x01E0,
  26408. Agrave: 0x00C0,
  26409. Agravesmall: 0xF7E0,
  26410. Ahookabove: 0x1EA2,
  26411. Aiecyrillic: 0x04D4,
  26412. Ainvertedbreve: 0x0202,
  26413. Alpha: 0x0391,
  26414. Alphatonos: 0x0386,
  26415. Amacron: 0x0100,
  26416. Amonospace: 0xFF21,
  26417. Aogonek: 0x0104,
  26418. Aring: 0x00C5,
  26419. Aringacute: 0x01FA,
  26420. Aringbelow: 0x1E00,
  26421. Aringsmall: 0xF7E5,
  26422. Asmall: 0xF761,
  26423. Atilde: 0x00C3,
  26424. Atildesmall: 0xF7E3,
  26425. Aybarmenian: 0x0531,
  26426. B: 0x0042,
  26427. Bcircle: 0x24B7,
  26428. Bdotaccent: 0x1E02,
  26429. Bdotbelow: 0x1E04,
  26430. Becyrillic: 0x0411,
  26431. Benarmenian: 0x0532,
  26432. Beta: 0x0392,
  26433. Bhook: 0x0181,
  26434. Blinebelow: 0x1E06,
  26435. Bmonospace: 0xFF22,
  26436. Brevesmall: 0xF6F4,
  26437. Bsmall: 0xF762,
  26438. Btopbar: 0x0182,
  26439. C: 0x0043,
  26440. Caarmenian: 0x053E,
  26441. Cacute: 0x0106,
  26442. Caron: 0xF6CA,
  26443. Caronsmall: 0xF6F5,
  26444. Ccaron: 0x010C,
  26445. Ccedilla: 0x00C7,
  26446. Ccedillaacute: 0x1E08,
  26447. Ccedillasmall: 0xF7E7,
  26448. Ccircle: 0x24B8,
  26449. Ccircumflex: 0x0108,
  26450. Cdot: 0x010A,
  26451. Cdotaccent: 0x010A,
  26452. Cedillasmall: 0xF7B8,
  26453. Chaarmenian: 0x0549,
  26454. Cheabkhasiancyrillic: 0x04BC,
  26455. Checyrillic: 0x0427,
  26456. Chedescenderabkhasiancyrillic: 0x04BE,
  26457. Chedescendercyrillic: 0x04B6,
  26458. Chedieresiscyrillic: 0x04F4,
  26459. Cheharmenian: 0x0543,
  26460. Chekhakassiancyrillic: 0x04CB,
  26461. Cheverticalstrokecyrillic: 0x04B8,
  26462. Chi: 0x03A7,
  26463. Chook: 0x0187,
  26464. Circumflexsmall: 0xF6F6,
  26465. Cmonospace: 0xFF23,
  26466. Coarmenian: 0x0551,
  26467. Csmall: 0xF763,
  26468. D: 0x0044,
  26469. DZ: 0x01F1,
  26470. DZcaron: 0x01C4,
  26471. Daarmenian: 0x0534,
  26472. Dafrican: 0x0189,
  26473. Dcaron: 0x010E,
  26474. Dcedilla: 0x1E10,
  26475. Dcircle: 0x24B9,
  26476. Dcircumflexbelow: 0x1E12,
  26477. Dcroat: 0x0110,
  26478. Ddotaccent: 0x1E0A,
  26479. Ddotbelow: 0x1E0C,
  26480. Decyrillic: 0x0414,
  26481. Deicoptic: 0x03EE,
  26482. Delta: 0x2206,
  26483. Deltagreek: 0x0394,
  26484. Dhook: 0x018A,
  26485. Dieresis: 0xF6CB,
  26486. DieresisAcute: 0xF6CC,
  26487. DieresisGrave: 0xF6CD,
  26488. Dieresissmall: 0xF7A8,
  26489. Digammagreek: 0x03DC,
  26490. Djecyrillic: 0x0402,
  26491. Dlinebelow: 0x1E0E,
  26492. Dmonospace: 0xFF24,
  26493. Dotaccentsmall: 0xF6F7,
  26494. Dslash: 0x0110,
  26495. Dsmall: 0xF764,
  26496. Dtopbar: 0x018B,
  26497. Dz: 0x01F2,
  26498. Dzcaron: 0x01C5,
  26499. Dzeabkhasiancyrillic: 0x04E0,
  26500. Dzecyrillic: 0x0405,
  26501. Dzhecyrillic: 0x040F,
  26502. E: 0x0045,
  26503. Eacute: 0x00C9,
  26504. Eacutesmall: 0xF7E9,
  26505. Ebreve: 0x0114,
  26506. Ecaron: 0x011A,
  26507. Ecedillabreve: 0x1E1C,
  26508. Echarmenian: 0x0535,
  26509. Ecircle: 0x24BA,
  26510. Ecircumflex: 0x00CA,
  26511. Ecircumflexacute: 0x1EBE,
  26512. Ecircumflexbelow: 0x1E18,
  26513. Ecircumflexdotbelow: 0x1EC6,
  26514. Ecircumflexgrave: 0x1EC0,
  26515. Ecircumflexhookabove: 0x1EC2,
  26516. Ecircumflexsmall: 0xF7EA,
  26517. Ecircumflextilde: 0x1EC4,
  26518. Ecyrillic: 0x0404,
  26519. Edblgrave: 0x0204,
  26520. Edieresis: 0x00CB,
  26521. Edieresissmall: 0xF7EB,
  26522. Edot: 0x0116,
  26523. Edotaccent: 0x0116,
  26524. Edotbelow: 0x1EB8,
  26525. Efcyrillic: 0x0424,
  26526. Egrave: 0x00C8,
  26527. Egravesmall: 0xF7E8,
  26528. Eharmenian: 0x0537,
  26529. Ehookabove: 0x1EBA,
  26530. Eightroman: 0x2167,
  26531. Einvertedbreve: 0x0206,
  26532. Eiotifiedcyrillic: 0x0464,
  26533. Elcyrillic: 0x041B,
  26534. Elevenroman: 0x216A,
  26535. Emacron: 0x0112,
  26536. Emacronacute: 0x1E16,
  26537. Emacrongrave: 0x1E14,
  26538. Emcyrillic: 0x041C,
  26539. Emonospace: 0xFF25,
  26540. Encyrillic: 0x041D,
  26541. Endescendercyrillic: 0x04A2,
  26542. Eng: 0x014A,
  26543. Enghecyrillic: 0x04A4,
  26544. Enhookcyrillic: 0x04C7,
  26545. Eogonek: 0x0118,
  26546. Eopen: 0x0190,
  26547. Epsilon: 0x0395,
  26548. Epsilontonos: 0x0388,
  26549. Ercyrillic: 0x0420,
  26550. Ereversed: 0x018E,
  26551. Ereversedcyrillic: 0x042D,
  26552. Escyrillic: 0x0421,
  26553. Esdescendercyrillic: 0x04AA,
  26554. Esh: 0x01A9,
  26555. Esmall: 0xF765,
  26556. Eta: 0x0397,
  26557. Etarmenian: 0x0538,
  26558. Etatonos: 0x0389,
  26559. Eth: 0x00D0,
  26560. Ethsmall: 0xF7F0,
  26561. Etilde: 0x1EBC,
  26562. Etildebelow: 0x1E1A,
  26563. Euro: 0x20AC,
  26564. Ezh: 0x01B7,
  26565. Ezhcaron: 0x01EE,
  26566. Ezhreversed: 0x01B8,
  26567. F: 0x0046,
  26568. Fcircle: 0x24BB,
  26569. Fdotaccent: 0x1E1E,
  26570. Feharmenian: 0x0556,
  26571. Feicoptic: 0x03E4,
  26572. Fhook: 0x0191,
  26573. Fitacyrillic: 0x0472,
  26574. Fiveroman: 0x2164,
  26575. Fmonospace: 0xFF26,
  26576. Fourroman: 0x2163,
  26577. Fsmall: 0xF766,
  26578. G: 0x0047,
  26579. GBsquare: 0x3387,
  26580. Gacute: 0x01F4,
  26581. Gamma: 0x0393,
  26582. Gammaafrican: 0x0194,
  26583. Gangiacoptic: 0x03EA,
  26584. Gbreve: 0x011E,
  26585. Gcaron: 0x01E6,
  26586. Gcedilla: 0x0122,
  26587. Gcircle: 0x24BC,
  26588. Gcircumflex: 0x011C,
  26589. Gcommaaccent: 0x0122,
  26590. Gdot: 0x0120,
  26591. Gdotaccent: 0x0120,
  26592. Gecyrillic: 0x0413,
  26593. Ghadarmenian: 0x0542,
  26594. Ghemiddlehookcyrillic: 0x0494,
  26595. Ghestrokecyrillic: 0x0492,
  26596. Gheupturncyrillic: 0x0490,
  26597. Ghook: 0x0193,
  26598. Gimarmenian: 0x0533,
  26599. Gjecyrillic: 0x0403,
  26600. Gmacron: 0x1E20,
  26601. Gmonospace: 0xFF27,
  26602. Grave: 0xF6CE,
  26603. Gravesmall: 0xF760,
  26604. Gsmall: 0xF767,
  26605. Gsmallhook: 0x029B,
  26606. Gstroke: 0x01E4,
  26607. H: 0x0048,
  26608. H18533: 0x25CF,
  26609. H18543: 0x25AA,
  26610. H18551: 0x25AB,
  26611. H22073: 0x25A1,
  26612. HPsquare: 0x33CB,
  26613. Haabkhasiancyrillic: 0x04A8,
  26614. Hadescendercyrillic: 0x04B2,
  26615. Hardsigncyrillic: 0x042A,
  26616. Hbar: 0x0126,
  26617. Hbrevebelow: 0x1E2A,
  26618. Hcedilla: 0x1E28,
  26619. Hcircle: 0x24BD,
  26620. Hcircumflex: 0x0124,
  26621. Hdieresis: 0x1E26,
  26622. Hdotaccent: 0x1E22,
  26623. Hdotbelow: 0x1E24,
  26624. Hmonospace: 0xFF28,
  26625. Hoarmenian: 0x0540,
  26626. Horicoptic: 0x03E8,
  26627. Hsmall: 0xF768,
  26628. Hungarumlaut: 0xF6CF,
  26629. Hungarumlautsmall: 0xF6F8,
  26630. Hzsquare: 0x3390,
  26631. I: 0x0049,
  26632. IAcyrillic: 0x042F,
  26633. IJ: 0x0132,
  26634. IUcyrillic: 0x042E,
  26635. Iacute: 0x00CD,
  26636. Iacutesmall: 0xF7ED,
  26637. Ibreve: 0x012C,
  26638. Icaron: 0x01CF,
  26639. Icircle: 0x24BE,
  26640. Icircumflex: 0x00CE,
  26641. Icircumflexsmall: 0xF7EE,
  26642. Icyrillic: 0x0406,
  26643. Idblgrave: 0x0208,
  26644. Idieresis: 0x00CF,
  26645. Idieresisacute: 0x1E2E,
  26646. Idieresiscyrillic: 0x04E4,
  26647. Idieresissmall: 0xF7EF,
  26648. Idot: 0x0130,
  26649. Idotaccent: 0x0130,
  26650. Idotbelow: 0x1ECA,
  26651. Iebrevecyrillic: 0x04D6,
  26652. Iecyrillic: 0x0415,
  26653. Ifraktur: 0x2111,
  26654. Igrave: 0x00CC,
  26655. Igravesmall: 0xF7EC,
  26656. Ihookabove: 0x1EC8,
  26657. Iicyrillic: 0x0418,
  26658. Iinvertedbreve: 0x020A,
  26659. Iishortcyrillic: 0x0419,
  26660. Imacron: 0x012A,
  26661. Imacroncyrillic: 0x04E2,
  26662. Imonospace: 0xFF29,
  26663. Iniarmenian: 0x053B,
  26664. Iocyrillic: 0x0401,
  26665. Iogonek: 0x012E,
  26666. Iota: 0x0399,
  26667. Iotaafrican: 0x0196,
  26668. Iotadieresis: 0x03AA,
  26669. Iotatonos: 0x038A,
  26670. Ismall: 0xF769,
  26671. Istroke: 0x0197,
  26672. Itilde: 0x0128,
  26673. Itildebelow: 0x1E2C,
  26674. Izhitsacyrillic: 0x0474,
  26675. Izhitsadblgravecyrillic: 0x0476,
  26676. J: 0x004A,
  26677. Jaarmenian: 0x0541,
  26678. Jcircle: 0x24BF,
  26679. Jcircumflex: 0x0134,
  26680. Jecyrillic: 0x0408,
  26681. Jheharmenian: 0x054B,
  26682. Jmonospace: 0xFF2A,
  26683. Jsmall: 0xF76A,
  26684. K: 0x004B,
  26685. KBsquare: 0x3385,
  26686. KKsquare: 0x33CD,
  26687. Kabashkircyrillic: 0x04A0,
  26688. Kacute: 0x1E30,
  26689. Kacyrillic: 0x041A,
  26690. Kadescendercyrillic: 0x049A,
  26691. Kahookcyrillic: 0x04C3,
  26692. Kappa: 0x039A,
  26693. Kastrokecyrillic: 0x049E,
  26694. Kaverticalstrokecyrillic: 0x049C,
  26695. Kcaron: 0x01E8,
  26696. Kcedilla: 0x0136,
  26697. Kcircle: 0x24C0,
  26698. Kcommaaccent: 0x0136,
  26699. Kdotbelow: 0x1E32,
  26700. Keharmenian: 0x0554,
  26701. Kenarmenian: 0x053F,
  26702. Khacyrillic: 0x0425,
  26703. Kheicoptic: 0x03E6,
  26704. Khook: 0x0198,
  26705. Kjecyrillic: 0x040C,
  26706. Klinebelow: 0x1E34,
  26707. Kmonospace: 0xFF2B,
  26708. Koppacyrillic: 0x0480,
  26709. Koppagreek: 0x03DE,
  26710. Ksicyrillic: 0x046E,
  26711. Ksmall: 0xF76B,
  26712. L: 0x004C,
  26713. LJ: 0x01C7,
  26714. LL: 0xF6BF,
  26715. Lacute: 0x0139,
  26716. Lambda: 0x039B,
  26717. Lcaron: 0x013D,
  26718. Lcedilla: 0x013B,
  26719. Lcircle: 0x24C1,
  26720. Lcircumflexbelow: 0x1E3C,
  26721. Lcommaaccent: 0x013B,
  26722. Ldot: 0x013F,
  26723. Ldotaccent: 0x013F,
  26724. Ldotbelow: 0x1E36,
  26725. Ldotbelowmacron: 0x1E38,
  26726. Liwnarmenian: 0x053C,
  26727. Lj: 0x01C8,
  26728. Ljecyrillic: 0x0409,
  26729. Llinebelow: 0x1E3A,
  26730. Lmonospace: 0xFF2C,
  26731. Lslash: 0x0141,
  26732. Lslashsmall: 0xF6F9,
  26733. Lsmall: 0xF76C,
  26734. M: 0x004D,
  26735. MBsquare: 0x3386,
  26736. Macron: 0xF6D0,
  26737. Macronsmall: 0xF7AF,
  26738. Macute: 0x1E3E,
  26739. Mcircle: 0x24C2,
  26740. Mdotaccent: 0x1E40,
  26741. Mdotbelow: 0x1E42,
  26742. Menarmenian: 0x0544,
  26743. Mmonospace: 0xFF2D,
  26744. Msmall: 0xF76D,
  26745. Mturned: 0x019C,
  26746. Mu: 0x039C,
  26747. N: 0x004E,
  26748. NJ: 0x01CA,
  26749. Nacute: 0x0143,
  26750. Ncaron: 0x0147,
  26751. Ncedilla: 0x0145,
  26752. Ncircle: 0x24C3,
  26753. Ncircumflexbelow: 0x1E4A,
  26754. Ncommaaccent: 0x0145,
  26755. Ndotaccent: 0x1E44,
  26756. Ndotbelow: 0x1E46,
  26757. Nhookleft: 0x019D,
  26758. Nineroman: 0x2168,
  26759. Nj: 0x01CB,
  26760. Njecyrillic: 0x040A,
  26761. Nlinebelow: 0x1E48,
  26762. Nmonospace: 0xFF2E,
  26763. Nowarmenian: 0x0546,
  26764. Nsmall: 0xF76E,
  26765. Ntilde: 0x00D1,
  26766. Ntildesmall: 0xF7F1,
  26767. Nu: 0x039D,
  26768. O: 0x004F,
  26769. OE: 0x0152,
  26770. OEsmall: 0xF6FA,
  26771. Oacute: 0x00D3,
  26772. Oacutesmall: 0xF7F3,
  26773. Obarredcyrillic: 0x04E8,
  26774. Obarreddieresiscyrillic: 0x04EA,
  26775. Obreve: 0x014E,
  26776. Ocaron: 0x01D1,
  26777. Ocenteredtilde: 0x019F,
  26778. Ocircle: 0x24C4,
  26779. Ocircumflex: 0x00D4,
  26780. Ocircumflexacute: 0x1ED0,
  26781. Ocircumflexdotbelow: 0x1ED8,
  26782. Ocircumflexgrave: 0x1ED2,
  26783. Ocircumflexhookabove: 0x1ED4,
  26784. Ocircumflexsmall: 0xF7F4,
  26785. Ocircumflextilde: 0x1ED6,
  26786. Ocyrillic: 0x041E,
  26787. Odblacute: 0x0150,
  26788. Odblgrave: 0x020C,
  26789. Odieresis: 0x00D6,
  26790. Odieresiscyrillic: 0x04E6,
  26791. Odieresissmall: 0xF7F6,
  26792. Odotbelow: 0x1ECC,
  26793. Ogoneksmall: 0xF6FB,
  26794. Ograve: 0x00D2,
  26795. Ogravesmall: 0xF7F2,
  26796. Oharmenian: 0x0555,
  26797. Ohm: 0x2126,
  26798. Ohookabove: 0x1ECE,
  26799. Ohorn: 0x01A0,
  26800. Ohornacute: 0x1EDA,
  26801. Ohorndotbelow: 0x1EE2,
  26802. Ohorngrave: 0x1EDC,
  26803. Ohornhookabove: 0x1EDE,
  26804. Ohorntilde: 0x1EE0,
  26805. Ohungarumlaut: 0x0150,
  26806. Oi: 0x01A2,
  26807. Oinvertedbreve: 0x020E,
  26808. Omacron: 0x014C,
  26809. Omacronacute: 0x1E52,
  26810. Omacrongrave: 0x1E50,
  26811. Omega: 0x2126,
  26812. Omegacyrillic: 0x0460,
  26813. Omegagreek: 0x03A9,
  26814. Omegaroundcyrillic: 0x047A,
  26815. Omegatitlocyrillic: 0x047C,
  26816. Omegatonos: 0x038F,
  26817. Omicron: 0x039F,
  26818. Omicrontonos: 0x038C,
  26819. Omonospace: 0xFF2F,
  26820. Oneroman: 0x2160,
  26821. Oogonek: 0x01EA,
  26822. Oogonekmacron: 0x01EC,
  26823. Oopen: 0x0186,
  26824. Oslash: 0x00D8,
  26825. Oslashacute: 0x01FE,
  26826. Oslashsmall: 0xF7F8,
  26827. Osmall: 0xF76F,
  26828. Ostrokeacute: 0x01FE,
  26829. Otcyrillic: 0x047E,
  26830. Otilde: 0x00D5,
  26831. Otildeacute: 0x1E4C,
  26832. Otildedieresis: 0x1E4E,
  26833. Otildesmall: 0xF7F5,
  26834. P: 0x0050,
  26835. Pacute: 0x1E54,
  26836. Pcircle: 0x24C5,
  26837. Pdotaccent: 0x1E56,
  26838. Pecyrillic: 0x041F,
  26839. Peharmenian: 0x054A,
  26840. Pemiddlehookcyrillic: 0x04A6,
  26841. Phi: 0x03A6,
  26842. Phook: 0x01A4,
  26843. Pi: 0x03A0,
  26844. Piwrarmenian: 0x0553,
  26845. Pmonospace: 0xFF30,
  26846. Psi: 0x03A8,
  26847. Psicyrillic: 0x0470,
  26848. Psmall: 0xF770,
  26849. Q: 0x0051,
  26850. Qcircle: 0x24C6,
  26851. Qmonospace: 0xFF31,
  26852. Qsmall: 0xF771,
  26853. R: 0x0052,
  26854. Raarmenian: 0x054C,
  26855. Racute: 0x0154,
  26856. Rcaron: 0x0158,
  26857. Rcedilla: 0x0156,
  26858. Rcircle: 0x24C7,
  26859. Rcommaaccent: 0x0156,
  26860. Rdblgrave: 0x0210,
  26861. Rdotaccent: 0x1E58,
  26862. Rdotbelow: 0x1E5A,
  26863. Rdotbelowmacron: 0x1E5C,
  26864. Reharmenian: 0x0550,
  26865. Rfraktur: 0x211C,
  26866. Rho: 0x03A1,
  26867. Ringsmall: 0xF6FC,
  26868. Rinvertedbreve: 0x0212,
  26869. Rlinebelow: 0x1E5E,
  26870. Rmonospace: 0xFF32,
  26871. Rsmall: 0xF772,
  26872. Rsmallinverted: 0x0281,
  26873. Rsmallinvertedsuperior: 0x02B6,
  26874. S: 0x0053,
  26875. SF010000: 0x250C,
  26876. SF020000: 0x2514,
  26877. SF030000: 0x2510,
  26878. SF040000: 0x2518,
  26879. SF050000: 0x253C,
  26880. SF060000: 0x252C,
  26881. SF070000: 0x2534,
  26882. SF080000: 0x251C,
  26883. SF090000: 0x2524,
  26884. SF100000: 0x2500,
  26885. SF110000: 0x2502,
  26886. SF190000: 0x2561,
  26887. SF200000: 0x2562,
  26888. SF210000: 0x2556,
  26889. SF220000: 0x2555,
  26890. SF230000: 0x2563,
  26891. SF240000: 0x2551,
  26892. SF250000: 0x2557,
  26893. SF260000: 0x255D,
  26894. SF270000: 0x255C,
  26895. SF280000: 0x255B,
  26896. SF360000: 0x255E,
  26897. SF370000: 0x255F,
  26898. SF380000: 0x255A,
  26899. SF390000: 0x2554,
  26900. SF400000: 0x2569,
  26901. SF410000: 0x2566,
  26902. SF420000: 0x2560,
  26903. SF430000: 0x2550,
  26904. SF440000: 0x256C,
  26905. SF450000: 0x2567,
  26906. SF460000: 0x2568,
  26907. SF470000: 0x2564,
  26908. SF480000: 0x2565,
  26909. SF490000: 0x2559,
  26910. SF500000: 0x2558,
  26911. SF510000: 0x2552,
  26912. SF520000: 0x2553,
  26913. SF530000: 0x256B,
  26914. SF540000: 0x256A,
  26915. Sacute: 0x015A,
  26916. Sacutedotaccent: 0x1E64,
  26917. Sampigreek: 0x03E0,
  26918. Scaron: 0x0160,
  26919. Scarondotaccent: 0x1E66,
  26920. Scaronsmall: 0xF6FD,
  26921. Scedilla: 0x015E,
  26922. Schwa: 0x018F,
  26923. Schwacyrillic: 0x04D8,
  26924. Schwadieresiscyrillic: 0x04DA,
  26925. Scircle: 0x24C8,
  26926. Scircumflex: 0x015C,
  26927. Scommaaccent: 0x0218,
  26928. Sdotaccent: 0x1E60,
  26929. Sdotbelow: 0x1E62,
  26930. Sdotbelowdotaccent: 0x1E68,
  26931. Seharmenian: 0x054D,
  26932. Sevenroman: 0x2166,
  26933. Shaarmenian: 0x0547,
  26934. Shacyrillic: 0x0428,
  26935. Shchacyrillic: 0x0429,
  26936. Sheicoptic: 0x03E2,
  26937. Shhacyrillic: 0x04BA,
  26938. Shimacoptic: 0x03EC,
  26939. Sigma: 0x03A3,
  26940. Sixroman: 0x2165,
  26941. Smonospace: 0xFF33,
  26942. Softsigncyrillic: 0x042C,
  26943. Ssmall: 0xF773,
  26944. Stigmagreek: 0x03DA,
  26945. T: 0x0054,
  26946. Tau: 0x03A4,
  26947. Tbar: 0x0166,
  26948. Tcaron: 0x0164,
  26949. Tcedilla: 0x0162,
  26950. Tcircle: 0x24C9,
  26951. Tcircumflexbelow: 0x1E70,
  26952. Tcommaaccent: 0x0162,
  26953. Tdotaccent: 0x1E6A,
  26954. Tdotbelow: 0x1E6C,
  26955. Tecyrillic: 0x0422,
  26956. Tedescendercyrillic: 0x04AC,
  26957. Tenroman: 0x2169,
  26958. Tetsecyrillic: 0x04B4,
  26959. Theta: 0x0398,
  26960. Thook: 0x01AC,
  26961. Thorn: 0x00DE,
  26962. Thornsmall: 0xF7FE,
  26963. Threeroman: 0x2162,
  26964. Tildesmall: 0xF6FE,
  26965. Tiwnarmenian: 0x054F,
  26966. Tlinebelow: 0x1E6E,
  26967. Tmonospace: 0xFF34,
  26968. Toarmenian: 0x0539,
  26969. Tonefive: 0x01BC,
  26970. Tonesix: 0x0184,
  26971. Tonetwo: 0x01A7,
  26972. Tretroflexhook: 0x01AE,
  26973. Tsecyrillic: 0x0426,
  26974. Tshecyrillic: 0x040B,
  26975. Tsmall: 0xF774,
  26976. Twelveroman: 0x216B,
  26977. Tworoman: 0x2161,
  26978. U: 0x0055,
  26979. Uacute: 0x00DA,
  26980. Uacutesmall: 0xF7FA,
  26981. Ubreve: 0x016C,
  26982. Ucaron: 0x01D3,
  26983. Ucircle: 0x24CA,
  26984. Ucircumflex: 0x00DB,
  26985. Ucircumflexbelow: 0x1E76,
  26986. Ucircumflexsmall: 0xF7FB,
  26987. Ucyrillic: 0x0423,
  26988. Udblacute: 0x0170,
  26989. Udblgrave: 0x0214,
  26990. Udieresis: 0x00DC,
  26991. Udieresisacute: 0x01D7,
  26992. Udieresisbelow: 0x1E72,
  26993. Udieresiscaron: 0x01D9,
  26994. Udieresiscyrillic: 0x04F0,
  26995. Udieresisgrave: 0x01DB,
  26996. Udieresismacron: 0x01D5,
  26997. Udieresissmall: 0xF7FC,
  26998. Udotbelow: 0x1EE4,
  26999. Ugrave: 0x00D9,
  27000. Ugravesmall: 0xF7F9,
  27001. Uhookabove: 0x1EE6,
  27002. Uhorn: 0x01AF,
  27003. Uhornacute: 0x1EE8,
  27004. Uhorndotbelow: 0x1EF0,
  27005. Uhorngrave: 0x1EEA,
  27006. Uhornhookabove: 0x1EEC,
  27007. Uhorntilde: 0x1EEE,
  27008. Uhungarumlaut: 0x0170,
  27009. Uhungarumlautcyrillic: 0x04F2,
  27010. Uinvertedbreve: 0x0216,
  27011. Ukcyrillic: 0x0478,
  27012. Umacron: 0x016A,
  27013. Umacroncyrillic: 0x04EE,
  27014. Umacrondieresis: 0x1E7A,
  27015. Umonospace: 0xFF35,
  27016. Uogonek: 0x0172,
  27017. Upsilon: 0x03A5,
  27018. Upsilon1: 0x03D2,
  27019. Upsilonacutehooksymbolgreek: 0x03D3,
  27020. Upsilonafrican: 0x01B1,
  27021. Upsilondieresis: 0x03AB,
  27022. Upsilondieresishooksymbolgreek: 0x03D4,
  27023. Upsilonhooksymbol: 0x03D2,
  27024. Upsilontonos: 0x038E,
  27025. Uring: 0x016E,
  27026. Ushortcyrillic: 0x040E,
  27027. Usmall: 0xF775,
  27028. Ustraightcyrillic: 0x04AE,
  27029. Ustraightstrokecyrillic: 0x04B0,
  27030. Utilde: 0x0168,
  27031. Utildeacute: 0x1E78,
  27032. Utildebelow: 0x1E74,
  27033. V: 0x0056,
  27034. Vcircle: 0x24CB,
  27035. Vdotbelow: 0x1E7E,
  27036. Vecyrillic: 0x0412,
  27037. Vewarmenian: 0x054E,
  27038. Vhook: 0x01B2,
  27039. Vmonospace: 0xFF36,
  27040. Voarmenian: 0x0548,
  27041. Vsmall: 0xF776,
  27042. Vtilde: 0x1E7C,
  27043. W: 0x0057,
  27044. Wacute: 0x1E82,
  27045. Wcircle: 0x24CC,
  27046. Wcircumflex: 0x0174,
  27047. Wdieresis: 0x1E84,
  27048. Wdotaccent: 0x1E86,
  27049. Wdotbelow: 0x1E88,
  27050. Wgrave: 0x1E80,
  27051. Wmonospace: 0xFF37,
  27052. Wsmall: 0xF777,
  27053. X: 0x0058,
  27054. Xcircle: 0x24CD,
  27055. Xdieresis: 0x1E8C,
  27056. Xdotaccent: 0x1E8A,
  27057. Xeharmenian: 0x053D,
  27058. Xi: 0x039E,
  27059. Xmonospace: 0xFF38,
  27060. Xsmall: 0xF778,
  27061. Y: 0x0059,
  27062. Yacute: 0x00DD,
  27063. Yacutesmall: 0xF7FD,
  27064. Yatcyrillic: 0x0462,
  27065. Ycircle: 0x24CE,
  27066. Ycircumflex: 0x0176,
  27067. Ydieresis: 0x0178,
  27068. Ydieresissmall: 0xF7FF,
  27069. Ydotaccent: 0x1E8E,
  27070. Ydotbelow: 0x1EF4,
  27071. Yericyrillic: 0x042B,
  27072. Yerudieresiscyrillic: 0x04F8,
  27073. Ygrave: 0x1EF2,
  27074. Yhook: 0x01B3,
  27075. Yhookabove: 0x1EF6,
  27076. Yiarmenian: 0x0545,
  27077. Yicyrillic: 0x0407,
  27078. Yiwnarmenian: 0x0552,
  27079. Ymonospace: 0xFF39,
  27080. Ysmall: 0xF779,
  27081. Ytilde: 0x1EF8,
  27082. Yusbigcyrillic: 0x046A,
  27083. Yusbigiotifiedcyrillic: 0x046C,
  27084. Yuslittlecyrillic: 0x0466,
  27085. Yuslittleiotifiedcyrillic: 0x0468,
  27086. Z: 0x005A,
  27087. Zaarmenian: 0x0536,
  27088. Zacute: 0x0179,
  27089. Zcaron: 0x017D,
  27090. Zcaronsmall: 0xF6FF,
  27091. Zcircle: 0x24CF,
  27092. Zcircumflex: 0x1E90,
  27093. Zdot: 0x017B,
  27094. Zdotaccent: 0x017B,
  27095. Zdotbelow: 0x1E92,
  27096. Zecyrillic: 0x0417,
  27097. Zedescendercyrillic: 0x0498,
  27098. Zedieresiscyrillic: 0x04DE,
  27099. Zeta: 0x0396,
  27100. Zhearmenian: 0x053A,
  27101. Zhebrevecyrillic: 0x04C1,
  27102. Zhecyrillic: 0x0416,
  27103. Zhedescendercyrillic: 0x0496,
  27104. Zhedieresiscyrillic: 0x04DC,
  27105. Zlinebelow: 0x1E94,
  27106. Zmonospace: 0xFF3A,
  27107. Zsmall: 0xF77A,
  27108. Zstroke: 0x01B5,
  27109. a: 0x0061,
  27110. aabengali: 0x0986,
  27111. aacute: 0x00E1,
  27112. aadeva: 0x0906,
  27113. aagujarati: 0x0A86,
  27114. aagurmukhi: 0x0A06,
  27115. aamatragurmukhi: 0x0A3E,
  27116. aarusquare: 0x3303,
  27117. aavowelsignbengali: 0x09BE,
  27118. aavowelsigndeva: 0x093E,
  27119. aavowelsigngujarati: 0x0ABE,
  27120. abbreviationmarkarmenian: 0x055F,
  27121. abbreviationsigndeva: 0x0970,
  27122. abengali: 0x0985,
  27123. abopomofo: 0x311A,
  27124. abreve: 0x0103,
  27125. abreveacute: 0x1EAF,
  27126. abrevecyrillic: 0x04D1,
  27127. abrevedotbelow: 0x1EB7,
  27128. abrevegrave: 0x1EB1,
  27129. abrevehookabove: 0x1EB3,
  27130. abrevetilde: 0x1EB5,
  27131. acaron: 0x01CE,
  27132. acircle: 0x24D0,
  27133. acircumflex: 0x00E2,
  27134. acircumflexacute: 0x1EA5,
  27135. acircumflexdotbelow: 0x1EAD,
  27136. acircumflexgrave: 0x1EA7,
  27137. acircumflexhookabove: 0x1EA9,
  27138. acircumflextilde: 0x1EAB,
  27139. acute: 0x00B4,
  27140. acutebelowcmb: 0x0317,
  27141. acutecmb: 0x0301,
  27142. acutecomb: 0x0301,
  27143. acutedeva: 0x0954,
  27144. acutelowmod: 0x02CF,
  27145. acutetonecmb: 0x0341,
  27146. acyrillic: 0x0430,
  27147. adblgrave: 0x0201,
  27148. addakgurmukhi: 0x0A71,
  27149. adeva: 0x0905,
  27150. adieresis: 0x00E4,
  27151. adieresiscyrillic: 0x04D3,
  27152. adieresismacron: 0x01DF,
  27153. adotbelow: 0x1EA1,
  27154. adotmacron: 0x01E1,
  27155. ae: 0x00E6,
  27156. aeacute: 0x01FD,
  27157. aekorean: 0x3150,
  27158. aemacron: 0x01E3,
  27159. afii00208: 0x2015,
  27160. afii08941: 0x20A4,
  27161. afii10017: 0x0410,
  27162. afii10018: 0x0411,
  27163. afii10019: 0x0412,
  27164. afii10020: 0x0413,
  27165. afii10021: 0x0414,
  27166. afii10022: 0x0415,
  27167. afii10023: 0x0401,
  27168. afii10024: 0x0416,
  27169. afii10025: 0x0417,
  27170. afii10026: 0x0418,
  27171. afii10027: 0x0419,
  27172. afii10028: 0x041A,
  27173. afii10029: 0x041B,
  27174. afii10030: 0x041C,
  27175. afii10031: 0x041D,
  27176. afii10032: 0x041E,
  27177. afii10033: 0x041F,
  27178. afii10034: 0x0420,
  27179. afii10035: 0x0421,
  27180. afii10036: 0x0422,
  27181. afii10037: 0x0423,
  27182. afii10038: 0x0424,
  27183. afii10039: 0x0425,
  27184. afii10040: 0x0426,
  27185. afii10041: 0x0427,
  27186. afii10042: 0x0428,
  27187. afii10043: 0x0429,
  27188. afii10044: 0x042A,
  27189. afii10045: 0x042B,
  27190. afii10046: 0x042C,
  27191. afii10047: 0x042D,
  27192. afii10048: 0x042E,
  27193. afii10049: 0x042F,
  27194. afii10050: 0x0490,
  27195. afii10051: 0x0402,
  27196. afii10052: 0x0403,
  27197. afii10053: 0x0404,
  27198. afii10054: 0x0405,
  27199. afii10055: 0x0406,
  27200. afii10056: 0x0407,
  27201. afii10057: 0x0408,
  27202. afii10058: 0x0409,
  27203. afii10059: 0x040A,
  27204. afii10060: 0x040B,
  27205. afii10061: 0x040C,
  27206. afii10062: 0x040E,
  27207. afii10063: 0xF6C4,
  27208. afii10064: 0xF6C5,
  27209. afii10065: 0x0430,
  27210. afii10066: 0x0431,
  27211. afii10067: 0x0432,
  27212. afii10068: 0x0433,
  27213. afii10069: 0x0434,
  27214. afii10070: 0x0435,
  27215. afii10071: 0x0451,
  27216. afii10072: 0x0436,
  27217. afii10073: 0x0437,
  27218. afii10074: 0x0438,
  27219. afii10075: 0x0439,
  27220. afii10076: 0x043A,
  27221. afii10077: 0x043B,
  27222. afii10078: 0x043C,
  27223. afii10079: 0x043D,
  27224. afii10080: 0x043E,
  27225. afii10081: 0x043F,
  27226. afii10082: 0x0440,
  27227. afii10083: 0x0441,
  27228. afii10084: 0x0442,
  27229. afii10085: 0x0443,
  27230. afii10086: 0x0444,
  27231. afii10087: 0x0445,
  27232. afii10088: 0x0446,
  27233. afii10089: 0x0447,
  27234. afii10090: 0x0448,
  27235. afii10091: 0x0449,
  27236. afii10092: 0x044A,
  27237. afii10093: 0x044B,
  27238. afii10094: 0x044C,
  27239. afii10095: 0x044D,
  27240. afii10096: 0x044E,
  27241. afii10097: 0x044F,
  27242. afii10098: 0x0491,
  27243. afii10099: 0x0452,
  27244. afii10100: 0x0453,
  27245. afii10101: 0x0454,
  27246. afii10102: 0x0455,
  27247. afii10103: 0x0456,
  27248. afii10104: 0x0457,
  27249. afii10105: 0x0458,
  27250. afii10106: 0x0459,
  27251. afii10107: 0x045A,
  27252. afii10108: 0x045B,
  27253. afii10109: 0x045C,
  27254. afii10110: 0x045E,
  27255. afii10145: 0x040F,
  27256. afii10146: 0x0462,
  27257. afii10147: 0x0472,
  27258. afii10148: 0x0474,
  27259. afii10192: 0xF6C6,
  27260. afii10193: 0x045F,
  27261. afii10194: 0x0463,
  27262. afii10195: 0x0473,
  27263. afii10196: 0x0475,
  27264. afii10831: 0xF6C7,
  27265. afii10832: 0xF6C8,
  27266. afii10846: 0x04D9,
  27267. afii299: 0x200E,
  27268. afii300: 0x200F,
  27269. afii301: 0x200D,
  27270. afii57381: 0x066A,
  27271. afii57388: 0x060C,
  27272. afii57392: 0x0660,
  27273. afii57393: 0x0661,
  27274. afii57394: 0x0662,
  27275. afii57395: 0x0663,
  27276. afii57396: 0x0664,
  27277. afii57397: 0x0665,
  27278. afii57398: 0x0666,
  27279. afii57399: 0x0667,
  27280. afii57400: 0x0668,
  27281. afii57401: 0x0669,
  27282. afii57403: 0x061B,
  27283. afii57407: 0x061F,
  27284. afii57409: 0x0621,
  27285. afii57410: 0x0622,
  27286. afii57411: 0x0623,
  27287. afii57412: 0x0624,
  27288. afii57413: 0x0625,
  27289. afii57414: 0x0626,
  27290. afii57415: 0x0627,
  27291. afii57416: 0x0628,
  27292. afii57417: 0x0629,
  27293. afii57418: 0x062A,
  27294. afii57419: 0x062B,
  27295. afii57420: 0x062C,
  27296. afii57421: 0x062D,
  27297. afii57422: 0x062E,
  27298. afii57423: 0x062F,
  27299. afii57424: 0x0630,
  27300. afii57425: 0x0631,
  27301. afii57426: 0x0632,
  27302. afii57427: 0x0633,
  27303. afii57428: 0x0634,
  27304. afii57429: 0x0635,
  27305. afii57430: 0x0636,
  27306. afii57431: 0x0637,
  27307. afii57432: 0x0638,
  27308. afii57433: 0x0639,
  27309. afii57434: 0x063A,
  27310. afii57440: 0x0640,
  27311. afii57441: 0x0641,
  27312. afii57442: 0x0642,
  27313. afii57443: 0x0643,
  27314. afii57444: 0x0644,
  27315. afii57445: 0x0645,
  27316. afii57446: 0x0646,
  27317. afii57448: 0x0648,
  27318. afii57449: 0x0649,
  27319. afii57450: 0x064A,
  27320. afii57451: 0x064B,
  27321. afii57452: 0x064C,
  27322. afii57453: 0x064D,
  27323. afii57454: 0x064E,
  27324. afii57455: 0x064F,
  27325. afii57456: 0x0650,
  27326. afii57457: 0x0651,
  27327. afii57458: 0x0652,
  27328. afii57470: 0x0647,
  27329. afii57505: 0x06A4,
  27330. afii57506: 0x067E,
  27331. afii57507: 0x0686,
  27332. afii57508: 0x0698,
  27333. afii57509: 0x06AF,
  27334. afii57511: 0x0679,
  27335. afii57512: 0x0688,
  27336. afii57513: 0x0691,
  27337. afii57514: 0x06BA,
  27338. afii57519: 0x06D2,
  27339. afii57534: 0x06D5,
  27340. afii57636: 0x20AA,
  27341. afii57645: 0x05BE,
  27342. afii57658: 0x05C3,
  27343. afii57664: 0x05D0,
  27344. afii57665: 0x05D1,
  27345. afii57666: 0x05D2,
  27346. afii57667: 0x05D3,
  27347. afii57668: 0x05D4,
  27348. afii57669: 0x05D5,
  27349. afii57670: 0x05D6,
  27350. afii57671: 0x05D7,
  27351. afii57672: 0x05D8,
  27352. afii57673: 0x05D9,
  27353. afii57674: 0x05DA,
  27354. afii57675: 0x05DB,
  27355. afii57676: 0x05DC,
  27356. afii57677: 0x05DD,
  27357. afii57678: 0x05DE,
  27358. afii57679: 0x05DF,
  27359. afii57680: 0x05E0,
  27360. afii57681: 0x05E1,
  27361. afii57682: 0x05E2,
  27362. afii57683: 0x05E3,
  27363. afii57684: 0x05E4,
  27364. afii57685: 0x05E5,
  27365. afii57686: 0x05E6,
  27366. afii57687: 0x05E7,
  27367. afii57688: 0x05E8,
  27368. afii57689: 0x05E9,
  27369. afii57690: 0x05EA,
  27370. afii57694: 0xFB2A,
  27371. afii57695: 0xFB2B,
  27372. afii57700: 0xFB4B,
  27373. afii57705: 0xFB1F,
  27374. afii57716: 0x05F0,
  27375. afii57717: 0x05F1,
  27376. afii57718: 0x05F2,
  27377. afii57723: 0xFB35,
  27378. afii57793: 0x05B4,
  27379. afii57794: 0x05B5,
  27380. afii57795: 0x05B6,
  27381. afii57796: 0x05BB,
  27382. afii57797: 0x05B8,
  27383. afii57798: 0x05B7,
  27384. afii57799: 0x05B0,
  27385. afii57800: 0x05B2,
  27386. afii57801: 0x05B1,
  27387. afii57802: 0x05B3,
  27388. afii57803: 0x05C2,
  27389. afii57804: 0x05C1,
  27390. afii57806: 0x05B9,
  27391. afii57807: 0x05BC,
  27392. afii57839: 0x05BD,
  27393. afii57841: 0x05BF,
  27394. afii57842: 0x05C0,
  27395. afii57929: 0x02BC,
  27396. afii61248: 0x2105,
  27397. afii61289: 0x2113,
  27398. afii61352: 0x2116,
  27399. afii61573: 0x202C,
  27400. afii61574: 0x202D,
  27401. afii61575: 0x202E,
  27402. afii61664: 0x200C,
  27403. afii63167: 0x066D,
  27404. afii64937: 0x02BD,
  27405. agrave: 0x00E0,
  27406. agujarati: 0x0A85,
  27407. agurmukhi: 0x0A05,
  27408. ahiragana: 0x3042,
  27409. ahookabove: 0x1EA3,
  27410. aibengali: 0x0990,
  27411. aibopomofo: 0x311E,
  27412. aideva: 0x0910,
  27413. aiecyrillic: 0x04D5,
  27414. aigujarati: 0x0A90,
  27415. aigurmukhi: 0x0A10,
  27416. aimatragurmukhi: 0x0A48,
  27417. ainarabic: 0x0639,
  27418. ainfinalarabic: 0xFECA,
  27419. aininitialarabic: 0xFECB,
  27420. ainmedialarabic: 0xFECC,
  27421. ainvertedbreve: 0x0203,
  27422. aivowelsignbengali: 0x09C8,
  27423. aivowelsigndeva: 0x0948,
  27424. aivowelsigngujarati: 0x0AC8,
  27425. akatakana: 0x30A2,
  27426. akatakanahalfwidth: 0xFF71,
  27427. akorean: 0x314F,
  27428. alef: 0x05D0,
  27429. alefarabic: 0x0627,
  27430. alefdageshhebrew: 0xFB30,
  27431. aleffinalarabic: 0xFE8E,
  27432. alefhamzaabovearabic: 0x0623,
  27433. alefhamzaabovefinalarabic: 0xFE84,
  27434. alefhamzabelowarabic: 0x0625,
  27435. alefhamzabelowfinalarabic: 0xFE88,
  27436. alefhebrew: 0x05D0,
  27437. aleflamedhebrew: 0xFB4F,
  27438. alefmaddaabovearabic: 0x0622,
  27439. alefmaddaabovefinalarabic: 0xFE82,
  27440. alefmaksuraarabic: 0x0649,
  27441. alefmaksurafinalarabic: 0xFEF0,
  27442. alefmaksurainitialarabic: 0xFEF3,
  27443. alefmaksuramedialarabic: 0xFEF4,
  27444. alefpatahhebrew: 0xFB2E,
  27445. alefqamatshebrew: 0xFB2F,
  27446. aleph: 0x2135,
  27447. allequal: 0x224C,
  27448. alpha: 0x03B1,
  27449. alphatonos: 0x03AC,
  27450. amacron: 0x0101,
  27451. amonospace: 0xFF41,
  27452. ampersand: 0x0026,
  27453. ampersandmonospace: 0xFF06,
  27454. ampersandsmall: 0xF726,
  27455. amsquare: 0x33C2,
  27456. anbopomofo: 0x3122,
  27457. angbopomofo: 0x3124,
  27458. angbracketleft: 0x3008, // This glyph is missing from Adobe's original list.
  27459. angbracketright: 0x3009, // This glyph is missing from Adobe's original list.
  27460. angkhankhuthai: 0x0E5A,
  27461. angle: 0x2220,
  27462. anglebracketleft: 0x3008,
  27463. anglebracketleftvertical: 0xFE3F,
  27464. anglebracketright: 0x3009,
  27465. anglebracketrightvertical: 0xFE40,
  27466. angleleft: 0x2329,
  27467. angleright: 0x232A,
  27468. angstrom: 0x212B,
  27469. anoteleia: 0x0387,
  27470. anudattadeva: 0x0952,
  27471. anusvarabengali: 0x0982,
  27472. anusvaradeva: 0x0902,
  27473. anusvaragujarati: 0x0A82,
  27474. aogonek: 0x0105,
  27475. apaatosquare: 0x3300,
  27476. aparen: 0x249C,
  27477. apostrophearmenian: 0x055A,
  27478. apostrophemod: 0x02BC,
  27479. apple: 0xF8FF,
  27480. approaches: 0x2250,
  27481. approxequal: 0x2248,
  27482. approxequalorimage: 0x2252,
  27483. approximatelyequal: 0x2245,
  27484. araeaekorean: 0x318E,
  27485. araeakorean: 0x318D,
  27486. arc: 0x2312,
  27487. arighthalfring: 0x1E9A,
  27488. aring: 0x00E5,
  27489. aringacute: 0x01FB,
  27490. aringbelow: 0x1E01,
  27491. arrowboth: 0x2194,
  27492. arrowdashdown: 0x21E3,
  27493. arrowdashleft: 0x21E0,
  27494. arrowdashright: 0x21E2,
  27495. arrowdashup: 0x21E1,
  27496. arrowdblboth: 0x21D4,
  27497. arrowdbldown: 0x21D3,
  27498. arrowdblleft: 0x21D0,
  27499. arrowdblright: 0x21D2,
  27500. arrowdblup: 0x21D1,
  27501. arrowdown: 0x2193,
  27502. arrowdownleft: 0x2199,
  27503. arrowdownright: 0x2198,
  27504. arrowdownwhite: 0x21E9,
  27505. arrowheaddownmod: 0x02C5,
  27506. arrowheadleftmod: 0x02C2,
  27507. arrowheadrightmod: 0x02C3,
  27508. arrowheadupmod: 0x02C4,
  27509. arrowhorizex: 0xF8E7,
  27510. arrowleft: 0x2190,
  27511. arrowleftdbl: 0x21D0,
  27512. arrowleftdblstroke: 0x21CD,
  27513. arrowleftoverright: 0x21C6,
  27514. arrowleftwhite: 0x21E6,
  27515. arrowright: 0x2192,
  27516. arrowrightdblstroke: 0x21CF,
  27517. arrowrightheavy: 0x279E,
  27518. arrowrightoverleft: 0x21C4,
  27519. arrowrightwhite: 0x21E8,
  27520. arrowtableft: 0x21E4,
  27521. arrowtabright: 0x21E5,
  27522. arrowup: 0x2191,
  27523. arrowupdn: 0x2195,
  27524. arrowupdnbse: 0x21A8,
  27525. arrowupdownbase: 0x21A8,
  27526. arrowupleft: 0x2196,
  27527. arrowupleftofdown: 0x21C5,
  27528. arrowupright: 0x2197,
  27529. arrowupwhite: 0x21E7,
  27530. arrowvertex: 0xF8E6,
  27531. asciicircum: 0x005E,
  27532. asciicircummonospace: 0xFF3E,
  27533. asciitilde: 0x007E,
  27534. asciitildemonospace: 0xFF5E,
  27535. ascript: 0x0251,
  27536. ascriptturned: 0x0252,
  27537. asmallhiragana: 0x3041,
  27538. asmallkatakana: 0x30A1,
  27539. asmallkatakanahalfwidth: 0xFF67,
  27540. asterisk: 0x002A,
  27541. asteriskaltonearabic: 0x066D,
  27542. asteriskarabic: 0x066D,
  27543. asteriskmath: 0x2217,
  27544. asteriskmonospace: 0xFF0A,
  27545. asterisksmall: 0xFE61,
  27546. asterism: 0x2042,
  27547. asuperior: 0xF6E9,
  27548. asymptoticallyequal: 0x2243,
  27549. at: 0x0040,
  27550. atilde: 0x00E3,
  27551. atmonospace: 0xFF20,
  27552. atsmall: 0xFE6B,
  27553. aturned: 0x0250,
  27554. aubengali: 0x0994,
  27555. aubopomofo: 0x3120,
  27556. audeva: 0x0914,
  27557. augujarati: 0x0A94,
  27558. augurmukhi: 0x0A14,
  27559. aulengthmarkbengali: 0x09D7,
  27560. aumatragurmukhi: 0x0A4C,
  27561. auvowelsignbengali: 0x09CC,
  27562. auvowelsigndeva: 0x094C,
  27563. auvowelsigngujarati: 0x0ACC,
  27564. avagrahadeva: 0x093D,
  27565. aybarmenian: 0x0561,
  27566. ayin: 0x05E2,
  27567. ayinaltonehebrew: 0xFB20,
  27568. ayinhebrew: 0x05E2,
  27569. b: 0x0062,
  27570. babengali: 0x09AC,
  27571. backslash: 0x005C,
  27572. backslashmonospace: 0xFF3C,
  27573. badeva: 0x092C,
  27574. bagujarati: 0x0AAC,
  27575. bagurmukhi: 0x0A2C,
  27576. bahiragana: 0x3070,
  27577. bahtthai: 0x0E3F,
  27578. bakatakana: 0x30D0,
  27579. bar: 0x007C,
  27580. barmonospace: 0xFF5C,
  27581. bbopomofo: 0x3105,
  27582. bcircle: 0x24D1,
  27583. bdotaccent: 0x1E03,
  27584. bdotbelow: 0x1E05,
  27585. beamedsixteenthnotes: 0x266C,
  27586. because: 0x2235,
  27587. becyrillic: 0x0431,
  27588. beharabic: 0x0628,
  27589. behfinalarabic: 0xFE90,
  27590. behinitialarabic: 0xFE91,
  27591. behiragana: 0x3079,
  27592. behmedialarabic: 0xFE92,
  27593. behmeeminitialarabic: 0xFC9F,
  27594. behmeemisolatedarabic: 0xFC08,
  27595. behnoonfinalarabic: 0xFC6D,
  27596. bekatakana: 0x30D9,
  27597. benarmenian: 0x0562,
  27598. bet: 0x05D1,
  27599. beta: 0x03B2,
  27600. betasymbolgreek: 0x03D0,
  27601. betdagesh: 0xFB31,
  27602. betdageshhebrew: 0xFB31,
  27603. bethebrew: 0x05D1,
  27604. betrafehebrew: 0xFB4C,
  27605. bhabengali: 0x09AD,
  27606. bhadeva: 0x092D,
  27607. bhagujarati: 0x0AAD,
  27608. bhagurmukhi: 0x0A2D,
  27609. bhook: 0x0253,
  27610. bihiragana: 0x3073,
  27611. bikatakana: 0x30D3,
  27612. bilabialclick: 0x0298,
  27613. bindigurmukhi: 0x0A02,
  27614. birusquare: 0x3331,
  27615. blackcircle: 0x25CF,
  27616. blackdiamond: 0x25C6,
  27617. blackdownpointingtriangle: 0x25BC,
  27618. blackleftpointingpointer: 0x25C4,
  27619. blackleftpointingtriangle: 0x25C0,
  27620. blacklenticularbracketleft: 0x3010,
  27621. blacklenticularbracketleftvertical: 0xFE3B,
  27622. blacklenticularbracketright: 0x3011,
  27623. blacklenticularbracketrightvertical: 0xFE3C,
  27624. blacklowerlefttriangle: 0x25E3,
  27625. blacklowerrighttriangle: 0x25E2,
  27626. blackrectangle: 0x25AC,
  27627. blackrightpointingpointer: 0x25BA,
  27628. blackrightpointingtriangle: 0x25B6,
  27629. blacksmallsquare: 0x25AA,
  27630. blacksmilingface: 0x263B,
  27631. blacksquare: 0x25A0,
  27632. blackstar: 0x2605,
  27633. blackupperlefttriangle: 0x25E4,
  27634. blackupperrighttriangle: 0x25E5,
  27635. blackuppointingsmalltriangle: 0x25B4,
  27636. blackuppointingtriangle: 0x25B2,
  27637. blank: 0x2423,
  27638. blinebelow: 0x1E07,
  27639. block: 0x2588,
  27640. bmonospace: 0xFF42,
  27641. bobaimaithai: 0x0E1A,
  27642. bohiragana: 0x307C,
  27643. bokatakana: 0x30DC,
  27644. bparen: 0x249D,
  27645. bqsquare: 0x33C3,
  27646. braceex: 0xF8F4,
  27647. braceleft: 0x007B,
  27648. braceleftbt: 0xF8F3,
  27649. braceleftmid: 0xF8F2,
  27650. braceleftmonospace: 0xFF5B,
  27651. braceleftsmall: 0xFE5B,
  27652. bracelefttp: 0xF8F1,
  27653. braceleftvertical: 0xFE37,
  27654. braceright: 0x007D,
  27655. bracerightbt: 0xF8FE,
  27656. bracerightmid: 0xF8FD,
  27657. bracerightmonospace: 0xFF5D,
  27658. bracerightsmall: 0xFE5C,
  27659. bracerighttp: 0xF8FC,
  27660. bracerightvertical: 0xFE38,
  27661. bracketleft: 0x005B,
  27662. bracketleftbt: 0xF8F0,
  27663. bracketleftex: 0xF8EF,
  27664. bracketleftmonospace: 0xFF3B,
  27665. bracketlefttp: 0xF8EE,
  27666. bracketright: 0x005D,
  27667. bracketrightbt: 0xF8FB,
  27668. bracketrightex: 0xF8FA,
  27669. bracketrightmonospace: 0xFF3D,
  27670. bracketrighttp: 0xF8F9,
  27671. breve: 0x02D8,
  27672. brevebelowcmb: 0x032E,
  27673. brevecmb: 0x0306,
  27674. breveinvertedbelowcmb: 0x032F,
  27675. breveinvertedcmb: 0x0311,
  27676. breveinverteddoublecmb: 0x0361,
  27677. bridgebelowcmb: 0x032A,
  27678. bridgeinvertedbelowcmb: 0x033A,
  27679. brokenbar: 0x00A6,
  27680. bstroke: 0x0180,
  27681. bsuperior: 0xF6EA,
  27682. btopbar: 0x0183,
  27683. buhiragana: 0x3076,
  27684. bukatakana: 0x30D6,
  27685. bullet: 0x2022,
  27686. bulletinverse: 0x25D8,
  27687. bulletoperator: 0x2219,
  27688. bullseye: 0x25CE,
  27689. c: 0x0063,
  27690. caarmenian: 0x056E,
  27691. cabengali: 0x099A,
  27692. cacute: 0x0107,
  27693. cadeva: 0x091A,
  27694. cagujarati: 0x0A9A,
  27695. cagurmukhi: 0x0A1A,
  27696. calsquare: 0x3388,
  27697. candrabindubengali: 0x0981,
  27698. candrabinducmb: 0x0310,
  27699. candrabindudeva: 0x0901,
  27700. candrabindugujarati: 0x0A81,
  27701. capslock: 0x21EA,
  27702. careof: 0x2105,
  27703. caron: 0x02C7,
  27704. caronbelowcmb: 0x032C,
  27705. caroncmb: 0x030C,
  27706. carriagereturn: 0x21B5,
  27707. cbopomofo: 0x3118,
  27708. ccaron: 0x010D,
  27709. ccedilla: 0x00E7,
  27710. ccedillaacute: 0x1E09,
  27711. ccircle: 0x24D2,
  27712. ccircumflex: 0x0109,
  27713. ccurl: 0x0255,
  27714. cdot: 0x010B,
  27715. cdotaccent: 0x010B,
  27716. cdsquare: 0x33C5,
  27717. cedilla: 0x00B8,
  27718. cedillacmb: 0x0327,
  27719. cent: 0x00A2,
  27720. centigrade: 0x2103,
  27721. centinferior: 0xF6DF,
  27722. centmonospace: 0xFFE0,
  27723. centoldstyle: 0xF7A2,
  27724. centsuperior: 0xF6E0,
  27725. chaarmenian: 0x0579,
  27726. chabengali: 0x099B,
  27727. chadeva: 0x091B,
  27728. chagujarati: 0x0A9B,
  27729. chagurmukhi: 0x0A1B,
  27730. chbopomofo: 0x3114,
  27731. cheabkhasiancyrillic: 0x04BD,
  27732. checkmark: 0x2713,
  27733. checyrillic: 0x0447,
  27734. chedescenderabkhasiancyrillic: 0x04BF,
  27735. chedescendercyrillic: 0x04B7,
  27736. chedieresiscyrillic: 0x04F5,
  27737. cheharmenian: 0x0573,
  27738. chekhakassiancyrillic: 0x04CC,
  27739. cheverticalstrokecyrillic: 0x04B9,
  27740. chi: 0x03C7,
  27741. chieuchacirclekorean: 0x3277,
  27742. chieuchaparenkorean: 0x3217,
  27743. chieuchcirclekorean: 0x3269,
  27744. chieuchkorean: 0x314A,
  27745. chieuchparenkorean: 0x3209,
  27746. chochangthai: 0x0E0A,
  27747. chochanthai: 0x0E08,
  27748. chochingthai: 0x0E09,
  27749. chochoethai: 0x0E0C,
  27750. chook: 0x0188,
  27751. cieucacirclekorean: 0x3276,
  27752. cieucaparenkorean: 0x3216,
  27753. cieuccirclekorean: 0x3268,
  27754. cieuckorean: 0x3148,
  27755. cieucparenkorean: 0x3208,
  27756. cieucuparenkorean: 0x321C,
  27757. circle: 0x25CB,
  27758. circlecopyrt: 0x00A9, // This glyph is missing from Adobe's original list.
  27759. circlemultiply: 0x2297,
  27760. circleot: 0x2299,
  27761. circleplus: 0x2295,
  27762. circlepostalmark: 0x3036,
  27763. circlewithlefthalfblack: 0x25D0,
  27764. circlewithrighthalfblack: 0x25D1,
  27765. circumflex: 0x02C6,
  27766. circumflexbelowcmb: 0x032D,
  27767. circumflexcmb: 0x0302,
  27768. clear: 0x2327,
  27769. clickalveolar: 0x01C2,
  27770. clickdental: 0x01C0,
  27771. clicklateral: 0x01C1,
  27772. clickretroflex: 0x01C3,
  27773. club: 0x2663,
  27774. clubsuitblack: 0x2663,
  27775. clubsuitwhite: 0x2667,
  27776. cmcubedsquare: 0x33A4,
  27777. cmonospace: 0xFF43,
  27778. cmsquaredsquare: 0x33A0,
  27779. coarmenian: 0x0581,
  27780. colon: 0x003A,
  27781. colonmonetary: 0x20A1,
  27782. colonmonospace: 0xFF1A,
  27783. colonsign: 0x20A1,
  27784. colonsmall: 0xFE55,
  27785. colontriangularhalfmod: 0x02D1,
  27786. colontriangularmod: 0x02D0,
  27787. comma: 0x002C,
  27788. commaabovecmb: 0x0313,
  27789. commaaboverightcmb: 0x0315,
  27790. commaaccent: 0xF6C3,
  27791. commaarabic: 0x060C,
  27792. commaarmenian: 0x055D,
  27793. commainferior: 0xF6E1,
  27794. commamonospace: 0xFF0C,
  27795. commareversedabovecmb: 0x0314,
  27796. commareversedmod: 0x02BD,
  27797. commasmall: 0xFE50,
  27798. commasuperior: 0xF6E2,
  27799. commaturnedabovecmb: 0x0312,
  27800. commaturnedmod: 0x02BB,
  27801. compass: 0x263C,
  27802. congruent: 0x2245,
  27803. contourintegral: 0x222E,
  27804. control: 0x2303,
  27805. controlACK: 0x0006,
  27806. controlBEL: 0x0007,
  27807. controlBS: 0x0008,
  27808. controlCAN: 0x0018,
  27809. controlCR: 0x000D,
  27810. controlDC1: 0x0011,
  27811. controlDC2: 0x0012,
  27812. controlDC3: 0x0013,
  27813. controlDC4: 0x0014,
  27814. controlDEL: 0x007F,
  27815. controlDLE: 0x0010,
  27816. controlEM: 0x0019,
  27817. controlENQ: 0x0005,
  27818. controlEOT: 0x0004,
  27819. controlESC: 0x001B,
  27820. controlETB: 0x0017,
  27821. controlETX: 0x0003,
  27822. controlFF: 0x000C,
  27823. controlFS: 0x001C,
  27824. controlGS: 0x001D,
  27825. controlHT: 0x0009,
  27826. controlLF: 0x000A,
  27827. controlNAK: 0x0015,
  27828. controlRS: 0x001E,
  27829. controlSI: 0x000F,
  27830. controlSO: 0x000E,
  27831. controlSOT: 0x0002,
  27832. controlSTX: 0x0001,
  27833. controlSUB: 0x001A,
  27834. controlSYN: 0x0016,
  27835. controlUS: 0x001F,
  27836. controlVT: 0x000B,
  27837. copyright: 0x00A9,
  27838. copyrightsans: 0xF8E9,
  27839. copyrightserif: 0xF6D9,
  27840. cornerbracketleft: 0x300C,
  27841. cornerbracketlefthalfwidth: 0xFF62,
  27842. cornerbracketleftvertical: 0xFE41,
  27843. cornerbracketright: 0x300D,
  27844. cornerbracketrighthalfwidth: 0xFF63,
  27845. cornerbracketrightvertical: 0xFE42,
  27846. corporationsquare: 0x337F,
  27847. cosquare: 0x33C7,
  27848. coverkgsquare: 0x33C6,
  27849. cparen: 0x249E,
  27850. cruzeiro: 0x20A2,
  27851. cstretched: 0x0297,
  27852. curlyand: 0x22CF,
  27853. curlyor: 0x22CE,
  27854. currency: 0x00A4,
  27855. cyrBreve: 0xF6D1,
  27856. cyrFlex: 0xF6D2,
  27857. cyrbreve: 0xF6D4,
  27858. cyrflex: 0xF6D5,
  27859. d: 0x0064,
  27860. daarmenian: 0x0564,
  27861. dabengali: 0x09A6,
  27862. dadarabic: 0x0636,
  27863. dadeva: 0x0926,
  27864. dadfinalarabic: 0xFEBE,
  27865. dadinitialarabic: 0xFEBF,
  27866. dadmedialarabic: 0xFEC0,
  27867. dagesh: 0x05BC,
  27868. dageshhebrew: 0x05BC,
  27869. dagger: 0x2020,
  27870. daggerdbl: 0x2021,
  27871. dagujarati: 0x0AA6,
  27872. dagurmukhi: 0x0A26,
  27873. dahiragana: 0x3060,
  27874. dakatakana: 0x30C0,
  27875. dalarabic: 0x062F,
  27876. dalet: 0x05D3,
  27877. daletdagesh: 0xFB33,
  27878. daletdageshhebrew: 0xFB33,
  27879. dalethebrew: 0x05D3,
  27880. dalfinalarabic: 0xFEAA,
  27881. dammaarabic: 0x064F,
  27882. dammalowarabic: 0x064F,
  27883. dammatanaltonearabic: 0x064C,
  27884. dammatanarabic: 0x064C,
  27885. danda: 0x0964,
  27886. dargahebrew: 0x05A7,
  27887. dargalefthebrew: 0x05A7,
  27888. dasiapneumatacyrilliccmb: 0x0485,
  27889. dblGrave: 0xF6D3,
  27890. dblanglebracketleft: 0x300A,
  27891. dblanglebracketleftvertical: 0xFE3D,
  27892. dblanglebracketright: 0x300B,
  27893. dblanglebracketrightvertical: 0xFE3E,
  27894. dblarchinvertedbelowcmb: 0x032B,
  27895. dblarrowleft: 0x21D4,
  27896. dblarrowright: 0x21D2,
  27897. dbldanda: 0x0965,
  27898. dblgrave: 0xF6D6,
  27899. dblgravecmb: 0x030F,
  27900. dblintegral: 0x222C,
  27901. dbllowline: 0x2017,
  27902. dbllowlinecmb: 0x0333,
  27903. dbloverlinecmb: 0x033F,
  27904. dblprimemod: 0x02BA,
  27905. dblverticalbar: 0x2016,
  27906. dblverticallineabovecmb: 0x030E,
  27907. dbopomofo: 0x3109,
  27908. dbsquare: 0x33C8,
  27909. dcaron: 0x010F,
  27910. dcedilla: 0x1E11,
  27911. dcircle: 0x24D3,
  27912. dcircumflexbelow: 0x1E13,
  27913. dcroat: 0x0111,
  27914. ddabengali: 0x09A1,
  27915. ddadeva: 0x0921,
  27916. ddagujarati: 0x0AA1,
  27917. ddagurmukhi: 0x0A21,
  27918. ddalarabic: 0x0688,
  27919. ddalfinalarabic: 0xFB89,
  27920. dddhadeva: 0x095C,
  27921. ddhabengali: 0x09A2,
  27922. ddhadeva: 0x0922,
  27923. ddhagujarati: 0x0AA2,
  27924. ddhagurmukhi: 0x0A22,
  27925. ddotaccent: 0x1E0B,
  27926. ddotbelow: 0x1E0D,
  27927. decimalseparatorarabic: 0x066B,
  27928. decimalseparatorpersian: 0x066B,
  27929. decyrillic: 0x0434,
  27930. degree: 0x00B0,
  27931. dehihebrew: 0x05AD,
  27932. dehiragana: 0x3067,
  27933. deicoptic: 0x03EF,
  27934. dekatakana: 0x30C7,
  27935. deleteleft: 0x232B,
  27936. deleteright: 0x2326,
  27937. delta: 0x03B4,
  27938. deltaturned: 0x018D,
  27939. denominatorminusonenumeratorbengali: 0x09F8,
  27940. dezh: 0x02A4,
  27941. dhabengali: 0x09A7,
  27942. dhadeva: 0x0927,
  27943. dhagujarati: 0x0AA7,
  27944. dhagurmukhi: 0x0A27,
  27945. dhook: 0x0257,
  27946. dialytikatonos: 0x0385,
  27947. dialytikatonoscmb: 0x0344,
  27948. diamond: 0x2666,
  27949. diamondsuitwhite: 0x2662,
  27950. dieresis: 0x00A8,
  27951. dieresisacute: 0xF6D7,
  27952. dieresisbelowcmb: 0x0324,
  27953. dieresiscmb: 0x0308,
  27954. dieresisgrave: 0xF6D8,
  27955. dieresistonos: 0x0385,
  27956. dihiragana: 0x3062,
  27957. dikatakana: 0x30C2,
  27958. dittomark: 0x3003,
  27959. divide: 0x00F7,
  27960. divides: 0x2223,
  27961. divisionslash: 0x2215,
  27962. djecyrillic: 0x0452,
  27963. dkshade: 0x2593,
  27964. dlinebelow: 0x1E0F,
  27965. dlsquare: 0x3397,
  27966. dmacron: 0x0111,
  27967. dmonospace: 0xFF44,
  27968. dnblock: 0x2584,
  27969. dochadathai: 0x0E0E,
  27970. dodekthai: 0x0E14,
  27971. dohiragana: 0x3069,
  27972. dokatakana: 0x30C9,
  27973. dollar: 0x0024,
  27974. dollarinferior: 0xF6E3,
  27975. dollarmonospace: 0xFF04,
  27976. dollaroldstyle: 0xF724,
  27977. dollarsmall: 0xFE69,
  27978. dollarsuperior: 0xF6E4,
  27979. dong: 0x20AB,
  27980. dorusquare: 0x3326,
  27981. dotaccent: 0x02D9,
  27982. dotaccentcmb: 0x0307,
  27983. dotbelowcmb: 0x0323,
  27984. dotbelowcomb: 0x0323,
  27985. dotkatakana: 0x30FB,
  27986. dotlessi: 0x0131,
  27987. dotlessj: 0xF6BE,
  27988. dotlessjstrokehook: 0x0284,
  27989. dotmath: 0x22C5,
  27990. dottedcircle: 0x25CC,
  27991. doubleyodpatah: 0xFB1F,
  27992. doubleyodpatahhebrew: 0xFB1F,
  27993. downtackbelowcmb: 0x031E,
  27994. downtackmod: 0x02D5,
  27995. dparen: 0x249F,
  27996. dsuperior: 0xF6EB,
  27997. dtail: 0x0256,
  27998. dtopbar: 0x018C,
  27999. duhiragana: 0x3065,
  28000. dukatakana: 0x30C5,
  28001. dz: 0x01F3,
  28002. dzaltone: 0x02A3,
  28003. dzcaron: 0x01C6,
  28004. dzcurl: 0x02A5,
  28005. dzeabkhasiancyrillic: 0x04E1,
  28006. dzecyrillic: 0x0455,
  28007. dzhecyrillic: 0x045F,
  28008. e: 0x0065,
  28009. eacute: 0x00E9,
  28010. earth: 0x2641,
  28011. ebengali: 0x098F,
  28012. ebopomofo: 0x311C,
  28013. ebreve: 0x0115,
  28014. ecandradeva: 0x090D,
  28015. ecandragujarati: 0x0A8D,
  28016. ecandravowelsigndeva: 0x0945,
  28017. ecandravowelsigngujarati: 0x0AC5,
  28018. ecaron: 0x011B,
  28019. ecedillabreve: 0x1E1D,
  28020. echarmenian: 0x0565,
  28021. echyiwnarmenian: 0x0587,
  28022. ecircle: 0x24D4,
  28023. ecircumflex: 0x00EA,
  28024. ecircumflexacute: 0x1EBF,
  28025. ecircumflexbelow: 0x1E19,
  28026. ecircumflexdotbelow: 0x1EC7,
  28027. ecircumflexgrave: 0x1EC1,
  28028. ecircumflexhookabove: 0x1EC3,
  28029. ecircumflextilde: 0x1EC5,
  28030. ecyrillic: 0x0454,
  28031. edblgrave: 0x0205,
  28032. edeva: 0x090F,
  28033. edieresis: 0x00EB,
  28034. edot: 0x0117,
  28035. edotaccent: 0x0117,
  28036. edotbelow: 0x1EB9,
  28037. eegurmukhi: 0x0A0F,
  28038. eematragurmukhi: 0x0A47,
  28039. efcyrillic: 0x0444,
  28040. egrave: 0x00E8,
  28041. egujarati: 0x0A8F,
  28042. eharmenian: 0x0567,
  28043. ehbopomofo: 0x311D,
  28044. ehiragana: 0x3048,
  28045. ehookabove: 0x1EBB,
  28046. eibopomofo: 0x311F,
  28047. eight: 0x0038,
  28048. eightarabic: 0x0668,
  28049. eightbengali: 0x09EE,
  28050. eightcircle: 0x2467,
  28051. eightcircleinversesansserif: 0x2791,
  28052. eightdeva: 0x096E,
  28053. eighteencircle: 0x2471,
  28054. eighteenparen: 0x2485,
  28055. eighteenperiod: 0x2499,
  28056. eightgujarati: 0x0AEE,
  28057. eightgurmukhi: 0x0A6E,
  28058. eighthackarabic: 0x0668,
  28059. eighthangzhou: 0x3028,
  28060. eighthnotebeamed: 0x266B,
  28061. eightideographicparen: 0x3227,
  28062. eightinferior: 0x2088,
  28063. eightmonospace: 0xFF18,
  28064. eightoldstyle: 0xF738,
  28065. eightparen: 0x247B,
  28066. eightperiod: 0x248F,
  28067. eightpersian: 0x06F8,
  28068. eightroman: 0x2177,
  28069. eightsuperior: 0x2078,
  28070. eightthai: 0x0E58,
  28071. einvertedbreve: 0x0207,
  28072. eiotifiedcyrillic: 0x0465,
  28073. ekatakana: 0x30A8,
  28074. ekatakanahalfwidth: 0xFF74,
  28075. ekonkargurmukhi: 0x0A74,
  28076. ekorean: 0x3154,
  28077. elcyrillic: 0x043B,
  28078. element: 0x2208,
  28079. elevencircle: 0x246A,
  28080. elevenparen: 0x247E,
  28081. elevenperiod: 0x2492,
  28082. elevenroman: 0x217A,
  28083. ellipsis: 0x2026,
  28084. ellipsisvertical: 0x22EE,
  28085. emacron: 0x0113,
  28086. emacronacute: 0x1E17,
  28087. emacrongrave: 0x1E15,
  28088. emcyrillic: 0x043C,
  28089. emdash: 0x2014,
  28090. emdashvertical: 0xFE31,
  28091. emonospace: 0xFF45,
  28092. emphasismarkarmenian: 0x055B,
  28093. emptyset: 0x2205,
  28094. enbopomofo: 0x3123,
  28095. encyrillic: 0x043D,
  28096. endash: 0x2013,
  28097. endashvertical: 0xFE32,
  28098. endescendercyrillic: 0x04A3,
  28099. eng: 0x014B,
  28100. engbopomofo: 0x3125,
  28101. enghecyrillic: 0x04A5,
  28102. enhookcyrillic: 0x04C8,
  28103. enspace: 0x2002,
  28104. eogonek: 0x0119,
  28105. eokorean: 0x3153,
  28106. eopen: 0x025B,
  28107. eopenclosed: 0x029A,
  28108. eopenreversed: 0x025C,
  28109. eopenreversedclosed: 0x025E,
  28110. eopenreversedhook: 0x025D,
  28111. eparen: 0x24A0,
  28112. epsilon: 0x03B5,
  28113. epsilontonos: 0x03AD,
  28114. equal: 0x003D,
  28115. equalmonospace: 0xFF1D,
  28116. equalsmall: 0xFE66,
  28117. equalsuperior: 0x207C,
  28118. equivalence: 0x2261,
  28119. erbopomofo: 0x3126,
  28120. ercyrillic: 0x0440,
  28121. ereversed: 0x0258,
  28122. ereversedcyrillic: 0x044D,
  28123. escyrillic: 0x0441,
  28124. esdescendercyrillic: 0x04AB,
  28125. esh: 0x0283,
  28126. eshcurl: 0x0286,
  28127. eshortdeva: 0x090E,
  28128. eshortvowelsigndeva: 0x0946,
  28129. eshreversedloop: 0x01AA,
  28130. eshsquatreversed: 0x0285,
  28131. esmallhiragana: 0x3047,
  28132. esmallkatakana: 0x30A7,
  28133. esmallkatakanahalfwidth: 0xFF6A,
  28134. estimated: 0x212E,
  28135. esuperior: 0xF6EC,
  28136. eta: 0x03B7,
  28137. etarmenian: 0x0568,
  28138. etatonos: 0x03AE,
  28139. eth: 0x00F0,
  28140. etilde: 0x1EBD,
  28141. etildebelow: 0x1E1B,
  28142. etnahtafoukhhebrew: 0x0591,
  28143. etnahtafoukhlefthebrew: 0x0591,
  28144. etnahtahebrew: 0x0591,
  28145. etnahtalefthebrew: 0x0591,
  28146. eturned: 0x01DD,
  28147. eukorean: 0x3161,
  28148. euro: 0x20AC,
  28149. evowelsignbengali: 0x09C7,
  28150. evowelsigndeva: 0x0947,
  28151. evowelsigngujarati: 0x0AC7,
  28152. exclam: 0x0021,
  28153. exclamarmenian: 0x055C,
  28154. exclamdbl: 0x203C,
  28155. exclamdown: 0x00A1,
  28156. exclamdownsmall: 0xF7A1,
  28157. exclammonospace: 0xFF01,
  28158. exclamsmall: 0xF721,
  28159. existential: 0x2203,
  28160. ezh: 0x0292,
  28161. ezhcaron: 0x01EF,
  28162. ezhcurl: 0x0293,
  28163. ezhreversed: 0x01B9,
  28164. ezhtail: 0x01BA,
  28165. f: 0x0066,
  28166. fadeva: 0x095E,
  28167. fagurmukhi: 0x0A5E,
  28168. fahrenheit: 0x2109,
  28169. fathaarabic: 0x064E,
  28170. fathalowarabic: 0x064E,
  28171. fathatanarabic: 0x064B,
  28172. fbopomofo: 0x3108,
  28173. fcircle: 0x24D5,
  28174. fdotaccent: 0x1E1F,
  28175. feharabic: 0x0641,
  28176. feharmenian: 0x0586,
  28177. fehfinalarabic: 0xFED2,
  28178. fehinitialarabic: 0xFED3,
  28179. fehmedialarabic: 0xFED4,
  28180. feicoptic: 0x03E5,
  28181. female: 0x2640,
  28182. ff: 0xFB00,
  28183. ffi: 0xFB03,
  28184. ffl: 0xFB04,
  28185. fi: 0xFB01,
  28186. fifteencircle: 0x246E,
  28187. fifteenparen: 0x2482,
  28188. fifteenperiod: 0x2496,
  28189. figuredash: 0x2012,
  28190. filledbox: 0x25A0,
  28191. filledrect: 0x25AC,
  28192. finalkaf: 0x05DA,
  28193. finalkafdagesh: 0xFB3A,
  28194. finalkafdageshhebrew: 0xFB3A,
  28195. finalkafhebrew: 0x05DA,
  28196. finalmem: 0x05DD,
  28197. finalmemhebrew: 0x05DD,
  28198. finalnun: 0x05DF,
  28199. finalnunhebrew: 0x05DF,
  28200. finalpe: 0x05E3,
  28201. finalpehebrew: 0x05E3,
  28202. finaltsadi: 0x05E5,
  28203. finaltsadihebrew: 0x05E5,
  28204. firsttonechinese: 0x02C9,
  28205. fisheye: 0x25C9,
  28206. fitacyrillic: 0x0473,
  28207. five: 0x0035,
  28208. fivearabic: 0x0665,
  28209. fivebengali: 0x09EB,
  28210. fivecircle: 0x2464,
  28211. fivecircleinversesansserif: 0x278E,
  28212. fivedeva: 0x096B,
  28213. fiveeighths: 0x215D,
  28214. fivegujarati: 0x0AEB,
  28215. fivegurmukhi: 0x0A6B,
  28216. fivehackarabic: 0x0665,
  28217. fivehangzhou: 0x3025,
  28218. fiveideographicparen: 0x3224,
  28219. fiveinferior: 0x2085,
  28220. fivemonospace: 0xFF15,
  28221. fiveoldstyle: 0xF735,
  28222. fiveparen: 0x2478,
  28223. fiveperiod: 0x248C,
  28224. fivepersian: 0x06F5,
  28225. fiveroman: 0x2174,
  28226. fivesuperior: 0x2075,
  28227. fivethai: 0x0E55,
  28228. fl: 0xFB02,
  28229. florin: 0x0192,
  28230. fmonospace: 0xFF46,
  28231. fmsquare: 0x3399,
  28232. fofanthai: 0x0E1F,
  28233. fofathai: 0x0E1D,
  28234. fongmanthai: 0x0E4F,
  28235. forall: 0x2200,
  28236. four: 0x0034,
  28237. fourarabic: 0x0664,
  28238. fourbengali: 0x09EA,
  28239. fourcircle: 0x2463,
  28240. fourcircleinversesansserif: 0x278D,
  28241. fourdeva: 0x096A,
  28242. fourgujarati: 0x0AEA,
  28243. fourgurmukhi: 0x0A6A,
  28244. fourhackarabic: 0x0664,
  28245. fourhangzhou: 0x3024,
  28246. fourideographicparen: 0x3223,
  28247. fourinferior: 0x2084,
  28248. fourmonospace: 0xFF14,
  28249. fournumeratorbengali: 0x09F7,
  28250. fouroldstyle: 0xF734,
  28251. fourparen: 0x2477,
  28252. fourperiod: 0x248B,
  28253. fourpersian: 0x06F4,
  28254. fourroman: 0x2173,
  28255. foursuperior: 0x2074,
  28256. fourteencircle: 0x246D,
  28257. fourteenparen: 0x2481,
  28258. fourteenperiod: 0x2495,
  28259. fourthai: 0x0E54,
  28260. fourthtonechinese: 0x02CB,
  28261. fparen: 0x24A1,
  28262. fraction: 0x2044,
  28263. franc: 0x20A3,
  28264. g: 0x0067,
  28265. gabengali: 0x0997,
  28266. gacute: 0x01F5,
  28267. gadeva: 0x0917,
  28268. gafarabic: 0x06AF,
  28269. gaffinalarabic: 0xFB93,
  28270. gafinitialarabic: 0xFB94,
  28271. gafmedialarabic: 0xFB95,
  28272. gagujarati: 0x0A97,
  28273. gagurmukhi: 0x0A17,
  28274. gahiragana: 0x304C,
  28275. gakatakana: 0x30AC,
  28276. gamma: 0x03B3,
  28277. gammalatinsmall: 0x0263,
  28278. gammasuperior: 0x02E0,
  28279. gangiacoptic: 0x03EB,
  28280. gbopomofo: 0x310D,
  28281. gbreve: 0x011F,
  28282. gcaron: 0x01E7,
  28283. gcedilla: 0x0123,
  28284. gcircle: 0x24D6,
  28285. gcircumflex: 0x011D,
  28286. gcommaaccent: 0x0123,
  28287. gdot: 0x0121,
  28288. gdotaccent: 0x0121,
  28289. gecyrillic: 0x0433,
  28290. gehiragana: 0x3052,
  28291. gekatakana: 0x30B2,
  28292. geometricallyequal: 0x2251,
  28293. gereshaccenthebrew: 0x059C,
  28294. gereshhebrew: 0x05F3,
  28295. gereshmuqdamhebrew: 0x059D,
  28296. germandbls: 0x00DF,
  28297. gershayimaccenthebrew: 0x059E,
  28298. gershayimhebrew: 0x05F4,
  28299. getamark: 0x3013,
  28300. ghabengali: 0x0998,
  28301. ghadarmenian: 0x0572,
  28302. ghadeva: 0x0918,
  28303. ghagujarati: 0x0A98,
  28304. ghagurmukhi: 0x0A18,
  28305. ghainarabic: 0x063A,
  28306. ghainfinalarabic: 0xFECE,
  28307. ghaininitialarabic: 0xFECF,
  28308. ghainmedialarabic: 0xFED0,
  28309. ghemiddlehookcyrillic: 0x0495,
  28310. ghestrokecyrillic: 0x0493,
  28311. gheupturncyrillic: 0x0491,
  28312. ghhadeva: 0x095A,
  28313. ghhagurmukhi: 0x0A5A,
  28314. ghook: 0x0260,
  28315. ghzsquare: 0x3393,
  28316. gihiragana: 0x304E,
  28317. gikatakana: 0x30AE,
  28318. gimarmenian: 0x0563,
  28319. gimel: 0x05D2,
  28320. gimeldagesh: 0xFB32,
  28321. gimeldageshhebrew: 0xFB32,
  28322. gimelhebrew: 0x05D2,
  28323. gjecyrillic: 0x0453,
  28324. glottalinvertedstroke: 0x01BE,
  28325. glottalstop: 0x0294,
  28326. glottalstopinverted: 0x0296,
  28327. glottalstopmod: 0x02C0,
  28328. glottalstopreversed: 0x0295,
  28329. glottalstopreversedmod: 0x02C1,
  28330. glottalstopreversedsuperior: 0x02E4,
  28331. glottalstopstroke: 0x02A1,
  28332. glottalstopstrokereversed: 0x02A2,
  28333. gmacron: 0x1E21,
  28334. gmonospace: 0xFF47,
  28335. gohiragana: 0x3054,
  28336. gokatakana: 0x30B4,
  28337. gparen: 0x24A2,
  28338. gpasquare: 0x33AC,
  28339. gradient: 0x2207,
  28340. grave: 0x0060,
  28341. gravebelowcmb: 0x0316,
  28342. gravecmb: 0x0300,
  28343. gravecomb: 0x0300,
  28344. gravedeva: 0x0953,
  28345. gravelowmod: 0x02CE,
  28346. gravemonospace: 0xFF40,
  28347. gravetonecmb: 0x0340,
  28348. greater: 0x003E,
  28349. greaterequal: 0x2265,
  28350. greaterequalorless: 0x22DB,
  28351. greatermonospace: 0xFF1E,
  28352. greaterorequivalent: 0x2273,
  28353. greaterorless: 0x2277,
  28354. greateroverequal: 0x2267,
  28355. greatersmall: 0xFE65,
  28356. gscript: 0x0261,
  28357. gstroke: 0x01E5,
  28358. guhiragana: 0x3050,
  28359. guillemotleft: 0x00AB,
  28360. guillemotright: 0x00BB,
  28361. guilsinglleft: 0x2039,
  28362. guilsinglright: 0x203A,
  28363. gukatakana: 0x30B0,
  28364. guramusquare: 0x3318,
  28365. gysquare: 0x33C9,
  28366. h: 0x0068,
  28367. haabkhasiancyrillic: 0x04A9,
  28368. haaltonearabic: 0x06C1,
  28369. habengali: 0x09B9,
  28370. hadescendercyrillic: 0x04B3,
  28371. hadeva: 0x0939,
  28372. hagujarati: 0x0AB9,
  28373. hagurmukhi: 0x0A39,
  28374. haharabic: 0x062D,
  28375. hahfinalarabic: 0xFEA2,
  28376. hahinitialarabic: 0xFEA3,
  28377. hahiragana: 0x306F,
  28378. hahmedialarabic: 0xFEA4,
  28379. haitusquare: 0x332A,
  28380. hakatakana: 0x30CF,
  28381. hakatakanahalfwidth: 0xFF8A,
  28382. halantgurmukhi: 0x0A4D,
  28383. hamzaarabic: 0x0621,
  28384. hamzalowarabic: 0x0621,
  28385. hangulfiller: 0x3164,
  28386. hardsigncyrillic: 0x044A,
  28387. harpoonleftbarbup: 0x21BC,
  28388. harpoonrightbarbup: 0x21C0,
  28389. hasquare: 0x33CA,
  28390. hatafpatah: 0x05B2,
  28391. hatafpatah16: 0x05B2,
  28392. hatafpatah23: 0x05B2,
  28393. hatafpatah2f: 0x05B2,
  28394. hatafpatahhebrew: 0x05B2,
  28395. hatafpatahnarrowhebrew: 0x05B2,
  28396. hatafpatahquarterhebrew: 0x05B2,
  28397. hatafpatahwidehebrew: 0x05B2,
  28398. hatafqamats: 0x05B3,
  28399. hatafqamats1b: 0x05B3,
  28400. hatafqamats28: 0x05B3,
  28401. hatafqamats34: 0x05B3,
  28402. hatafqamatshebrew: 0x05B3,
  28403. hatafqamatsnarrowhebrew: 0x05B3,
  28404. hatafqamatsquarterhebrew: 0x05B3,
  28405. hatafqamatswidehebrew: 0x05B3,
  28406. hatafsegol: 0x05B1,
  28407. hatafsegol17: 0x05B1,
  28408. hatafsegol24: 0x05B1,
  28409. hatafsegol30: 0x05B1,
  28410. hatafsegolhebrew: 0x05B1,
  28411. hatafsegolnarrowhebrew: 0x05B1,
  28412. hatafsegolquarterhebrew: 0x05B1,
  28413. hatafsegolwidehebrew: 0x05B1,
  28414. hbar: 0x0127,
  28415. hbopomofo: 0x310F,
  28416. hbrevebelow: 0x1E2B,
  28417. hcedilla: 0x1E29,
  28418. hcircle: 0x24D7,
  28419. hcircumflex: 0x0125,
  28420. hdieresis: 0x1E27,
  28421. hdotaccent: 0x1E23,
  28422. hdotbelow: 0x1E25,
  28423. he: 0x05D4,
  28424. heart: 0x2665,
  28425. heartsuitblack: 0x2665,
  28426. heartsuitwhite: 0x2661,
  28427. hedagesh: 0xFB34,
  28428. hedageshhebrew: 0xFB34,
  28429. hehaltonearabic: 0x06C1,
  28430. heharabic: 0x0647,
  28431. hehebrew: 0x05D4,
  28432. hehfinalaltonearabic: 0xFBA7,
  28433. hehfinalalttwoarabic: 0xFEEA,
  28434. hehfinalarabic: 0xFEEA,
  28435. hehhamzaabovefinalarabic: 0xFBA5,
  28436. hehhamzaaboveisolatedarabic: 0xFBA4,
  28437. hehinitialaltonearabic: 0xFBA8,
  28438. hehinitialarabic: 0xFEEB,
  28439. hehiragana: 0x3078,
  28440. hehmedialaltonearabic: 0xFBA9,
  28441. hehmedialarabic: 0xFEEC,
  28442. heiseierasquare: 0x337B,
  28443. hekatakana: 0x30D8,
  28444. hekatakanahalfwidth: 0xFF8D,
  28445. hekutaarusquare: 0x3336,
  28446. henghook: 0x0267,
  28447. herutusquare: 0x3339,
  28448. het: 0x05D7,
  28449. hethebrew: 0x05D7,
  28450. hhook: 0x0266,
  28451. hhooksuperior: 0x02B1,
  28452. hieuhacirclekorean: 0x327B,
  28453. hieuhaparenkorean: 0x321B,
  28454. hieuhcirclekorean: 0x326D,
  28455. hieuhkorean: 0x314E,
  28456. hieuhparenkorean: 0x320D,
  28457. hihiragana: 0x3072,
  28458. hikatakana: 0x30D2,
  28459. hikatakanahalfwidth: 0xFF8B,
  28460. hiriq: 0x05B4,
  28461. hiriq14: 0x05B4,
  28462. hiriq21: 0x05B4,
  28463. hiriq2d: 0x05B4,
  28464. hiriqhebrew: 0x05B4,
  28465. hiriqnarrowhebrew: 0x05B4,
  28466. hiriqquarterhebrew: 0x05B4,
  28467. hiriqwidehebrew: 0x05B4,
  28468. hlinebelow: 0x1E96,
  28469. hmonospace: 0xFF48,
  28470. hoarmenian: 0x0570,
  28471. hohipthai: 0x0E2B,
  28472. hohiragana: 0x307B,
  28473. hokatakana: 0x30DB,
  28474. hokatakanahalfwidth: 0xFF8E,
  28475. holam: 0x05B9,
  28476. holam19: 0x05B9,
  28477. holam26: 0x05B9,
  28478. holam32: 0x05B9,
  28479. holamhebrew: 0x05B9,
  28480. holamnarrowhebrew: 0x05B9,
  28481. holamquarterhebrew: 0x05B9,
  28482. holamwidehebrew: 0x05B9,
  28483. honokhukthai: 0x0E2E,
  28484. hookabovecomb: 0x0309,
  28485. hookcmb: 0x0309,
  28486. hookpalatalizedbelowcmb: 0x0321,
  28487. hookretroflexbelowcmb: 0x0322,
  28488. hoonsquare: 0x3342,
  28489. horicoptic: 0x03E9,
  28490. horizontalbar: 0x2015,
  28491. horncmb: 0x031B,
  28492. hotsprings: 0x2668,
  28493. house: 0x2302,
  28494. hparen: 0x24A3,
  28495. hsuperior: 0x02B0,
  28496. hturned: 0x0265,
  28497. huhiragana: 0x3075,
  28498. huiitosquare: 0x3333,
  28499. hukatakana: 0x30D5,
  28500. hukatakanahalfwidth: 0xFF8C,
  28501. hungarumlaut: 0x02DD,
  28502. hungarumlautcmb: 0x030B,
  28503. hv: 0x0195,
  28504. hyphen: 0x002D,
  28505. hypheninferior: 0xF6E5,
  28506. hyphenmonospace: 0xFF0D,
  28507. hyphensmall: 0xFE63,
  28508. hyphensuperior: 0xF6E6,
  28509. hyphentwo: 0x2010,
  28510. i: 0x0069,
  28511. iacute: 0x00ED,
  28512. iacyrillic: 0x044F,
  28513. ibengali: 0x0987,
  28514. ibopomofo: 0x3127,
  28515. ibreve: 0x012D,
  28516. icaron: 0x01D0,
  28517. icircle: 0x24D8,
  28518. icircumflex: 0x00EE,
  28519. icyrillic: 0x0456,
  28520. idblgrave: 0x0209,
  28521. ideographearthcircle: 0x328F,
  28522. ideographfirecircle: 0x328B,
  28523. ideographicallianceparen: 0x323F,
  28524. ideographiccallparen: 0x323A,
  28525. ideographiccentrecircle: 0x32A5,
  28526. ideographicclose: 0x3006,
  28527. ideographiccomma: 0x3001,
  28528. ideographiccommaleft: 0xFF64,
  28529. ideographiccongratulationparen: 0x3237,
  28530. ideographiccorrectcircle: 0x32A3,
  28531. ideographicearthparen: 0x322F,
  28532. ideographicenterpriseparen: 0x323D,
  28533. ideographicexcellentcircle: 0x329D,
  28534. ideographicfestivalparen: 0x3240,
  28535. ideographicfinancialcircle: 0x3296,
  28536. ideographicfinancialparen: 0x3236,
  28537. ideographicfireparen: 0x322B,
  28538. ideographichaveparen: 0x3232,
  28539. ideographichighcircle: 0x32A4,
  28540. ideographiciterationmark: 0x3005,
  28541. ideographiclaborcircle: 0x3298,
  28542. ideographiclaborparen: 0x3238,
  28543. ideographicleftcircle: 0x32A7,
  28544. ideographiclowcircle: 0x32A6,
  28545. ideographicmedicinecircle: 0x32A9,
  28546. ideographicmetalparen: 0x322E,
  28547. ideographicmoonparen: 0x322A,
  28548. ideographicnameparen: 0x3234,
  28549. ideographicperiod: 0x3002,
  28550. ideographicprintcircle: 0x329E,
  28551. ideographicreachparen: 0x3243,
  28552. ideographicrepresentparen: 0x3239,
  28553. ideographicresourceparen: 0x323E,
  28554. ideographicrightcircle: 0x32A8,
  28555. ideographicsecretcircle: 0x3299,
  28556. ideographicselfparen: 0x3242,
  28557. ideographicsocietyparen: 0x3233,
  28558. ideographicspace: 0x3000,
  28559. ideographicspecialparen: 0x3235,
  28560. ideographicstockparen: 0x3231,
  28561. ideographicstudyparen: 0x323B,
  28562. ideographicsunparen: 0x3230,
  28563. ideographicsuperviseparen: 0x323C,
  28564. ideographicwaterparen: 0x322C,
  28565. ideographicwoodparen: 0x322D,
  28566. ideographiczero: 0x3007,
  28567. ideographmetalcircle: 0x328E,
  28568. ideographmooncircle: 0x328A,
  28569. ideographnamecircle: 0x3294,
  28570. ideographsuncircle: 0x3290,
  28571. ideographwatercircle: 0x328C,
  28572. ideographwoodcircle: 0x328D,
  28573. ideva: 0x0907,
  28574. idieresis: 0x00EF,
  28575. idieresisacute: 0x1E2F,
  28576. idieresiscyrillic: 0x04E5,
  28577. idotbelow: 0x1ECB,
  28578. iebrevecyrillic: 0x04D7,
  28579. iecyrillic: 0x0435,
  28580. ieungacirclekorean: 0x3275,
  28581. ieungaparenkorean: 0x3215,
  28582. ieungcirclekorean: 0x3267,
  28583. ieungkorean: 0x3147,
  28584. ieungparenkorean: 0x3207,
  28585. igrave: 0x00EC,
  28586. igujarati: 0x0A87,
  28587. igurmukhi: 0x0A07,
  28588. ihiragana: 0x3044,
  28589. ihookabove: 0x1EC9,
  28590. iibengali: 0x0988,
  28591. iicyrillic: 0x0438,
  28592. iideva: 0x0908,
  28593. iigujarati: 0x0A88,
  28594. iigurmukhi: 0x0A08,
  28595. iimatragurmukhi: 0x0A40,
  28596. iinvertedbreve: 0x020B,
  28597. iishortcyrillic: 0x0439,
  28598. iivowelsignbengali: 0x09C0,
  28599. iivowelsigndeva: 0x0940,
  28600. iivowelsigngujarati: 0x0AC0,
  28601. ij: 0x0133,
  28602. ikatakana: 0x30A4,
  28603. ikatakanahalfwidth: 0xFF72,
  28604. ikorean: 0x3163,
  28605. ilde: 0x02DC,
  28606. iluyhebrew: 0x05AC,
  28607. imacron: 0x012B,
  28608. imacroncyrillic: 0x04E3,
  28609. imageorapproximatelyequal: 0x2253,
  28610. imatragurmukhi: 0x0A3F,
  28611. imonospace: 0xFF49,
  28612. increment: 0x2206,
  28613. infinity: 0x221E,
  28614. iniarmenian: 0x056B,
  28615. integral: 0x222B,
  28616. integralbottom: 0x2321,
  28617. integralbt: 0x2321,
  28618. integralex: 0xF8F5,
  28619. integraltop: 0x2320,
  28620. integraltp: 0x2320,
  28621. intersection: 0x2229,
  28622. intisquare: 0x3305,
  28623. invbullet: 0x25D8,
  28624. invcircle: 0x25D9,
  28625. invsmileface: 0x263B,
  28626. iocyrillic: 0x0451,
  28627. iogonek: 0x012F,
  28628. iota: 0x03B9,
  28629. iotadieresis: 0x03CA,
  28630. iotadieresistonos: 0x0390,
  28631. iotalatin: 0x0269,
  28632. iotatonos: 0x03AF,
  28633. iparen: 0x24A4,
  28634. irigurmukhi: 0x0A72,
  28635. ismallhiragana: 0x3043,
  28636. ismallkatakana: 0x30A3,
  28637. ismallkatakanahalfwidth: 0xFF68,
  28638. issharbengali: 0x09FA,
  28639. istroke: 0x0268,
  28640. isuperior: 0xF6ED,
  28641. iterationhiragana: 0x309D,
  28642. iterationkatakana: 0x30FD,
  28643. itilde: 0x0129,
  28644. itildebelow: 0x1E2D,
  28645. iubopomofo: 0x3129,
  28646. iucyrillic: 0x044E,
  28647. ivowelsignbengali: 0x09BF,
  28648. ivowelsigndeva: 0x093F,
  28649. ivowelsigngujarati: 0x0ABF,
  28650. izhitsacyrillic: 0x0475,
  28651. izhitsadblgravecyrillic: 0x0477,
  28652. j: 0x006A,
  28653. jaarmenian: 0x0571,
  28654. jabengali: 0x099C,
  28655. jadeva: 0x091C,
  28656. jagujarati: 0x0A9C,
  28657. jagurmukhi: 0x0A1C,
  28658. jbopomofo: 0x3110,
  28659. jcaron: 0x01F0,
  28660. jcircle: 0x24D9,
  28661. jcircumflex: 0x0135,
  28662. jcrossedtail: 0x029D,
  28663. jdotlessstroke: 0x025F,
  28664. jecyrillic: 0x0458,
  28665. jeemarabic: 0x062C,
  28666. jeemfinalarabic: 0xFE9E,
  28667. jeeminitialarabic: 0xFE9F,
  28668. jeemmedialarabic: 0xFEA0,
  28669. jeharabic: 0x0698,
  28670. jehfinalarabic: 0xFB8B,
  28671. jhabengali: 0x099D,
  28672. jhadeva: 0x091D,
  28673. jhagujarati: 0x0A9D,
  28674. jhagurmukhi: 0x0A1D,
  28675. jheharmenian: 0x057B,
  28676. jis: 0x3004,
  28677. jmonospace: 0xFF4A,
  28678. jparen: 0x24A5,
  28679. jsuperior: 0x02B2,
  28680. k: 0x006B,
  28681. kabashkircyrillic: 0x04A1,
  28682. kabengali: 0x0995,
  28683. kacute: 0x1E31,
  28684. kacyrillic: 0x043A,
  28685. kadescendercyrillic: 0x049B,
  28686. kadeva: 0x0915,
  28687. kaf: 0x05DB,
  28688. kafarabic: 0x0643,
  28689. kafdagesh: 0xFB3B,
  28690. kafdageshhebrew: 0xFB3B,
  28691. kaffinalarabic: 0xFEDA,
  28692. kafhebrew: 0x05DB,
  28693. kafinitialarabic: 0xFEDB,
  28694. kafmedialarabic: 0xFEDC,
  28695. kafrafehebrew: 0xFB4D,
  28696. kagujarati: 0x0A95,
  28697. kagurmukhi: 0x0A15,
  28698. kahiragana: 0x304B,
  28699. kahookcyrillic: 0x04C4,
  28700. kakatakana: 0x30AB,
  28701. kakatakanahalfwidth: 0xFF76,
  28702. kappa: 0x03BA,
  28703. kappasymbolgreek: 0x03F0,
  28704. kapyeounmieumkorean: 0x3171,
  28705. kapyeounphieuphkorean: 0x3184,
  28706. kapyeounpieupkorean: 0x3178,
  28707. kapyeounssangpieupkorean: 0x3179,
  28708. karoriisquare: 0x330D,
  28709. kashidaautoarabic: 0x0640,
  28710. kashidaautonosidebearingarabic: 0x0640,
  28711. kasmallkatakana: 0x30F5,
  28712. kasquare: 0x3384,
  28713. kasraarabic: 0x0650,
  28714. kasratanarabic: 0x064D,
  28715. kastrokecyrillic: 0x049F,
  28716. katahiraprolongmarkhalfwidth: 0xFF70,
  28717. kaverticalstrokecyrillic: 0x049D,
  28718. kbopomofo: 0x310E,
  28719. kcalsquare: 0x3389,
  28720. kcaron: 0x01E9,
  28721. kcedilla: 0x0137,
  28722. kcircle: 0x24DA,
  28723. kcommaaccent: 0x0137,
  28724. kdotbelow: 0x1E33,
  28725. keharmenian: 0x0584,
  28726. kehiragana: 0x3051,
  28727. kekatakana: 0x30B1,
  28728. kekatakanahalfwidth: 0xFF79,
  28729. kenarmenian: 0x056F,
  28730. kesmallkatakana: 0x30F6,
  28731. kgreenlandic: 0x0138,
  28732. khabengali: 0x0996,
  28733. khacyrillic: 0x0445,
  28734. khadeva: 0x0916,
  28735. khagujarati: 0x0A96,
  28736. khagurmukhi: 0x0A16,
  28737. khaharabic: 0x062E,
  28738. khahfinalarabic: 0xFEA6,
  28739. khahinitialarabic: 0xFEA7,
  28740. khahmedialarabic: 0xFEA8,
  28741. kheicoptic: 0x03E7,
  28742. khhadeva: 0x0959,
  28743. khhagurmukhi: 0x0A59,
  28744. khieukhacirclekorean: 0x3278,
  28745. khieukhaparenkorean: 0x3218,
  28746. khieukhcirclekorean: 0x326A,
  28747. khieukhkorean: 0x314B,
  28748. khieukhparenkorean: 0x320A,
  28749. khokhaithai: 0x0E02,
  28750. khokhonthai: 0x0E05,
  28751. khokhuatthai: 0x0E03,
  28752. khokhwaithai: 0x0E04,
  28753. khomutthai: 0x0E5B,
  28754. khook: 0x0199,
  28755. khorakhangthai: 0x0E06,
  28756. khzsquare: 0x3391,
  28757. kihiragana: 0x304D,
  28758. kikatakana: 0x30AD,
  28759. kikatakanahalfwidth: 0xFF77,
  28760. kiroguramusquare: 0x3315,
  28761. kiromeetorusquare: 0x3316,
  28762. kirosquare: 0x3314,
  28763. kiyeokacirclekorean: 0x326E,
  28764. kiyeokaparenkorean: 0x320E,
  28765. kiyeokcirclekorean: 0x3260,
  28766. kiyeokkorean: 0x3131,
  28767. kiyeokparenkorean: 0x3200,
  28768. kiyeoksioskorean: 0x3133,
  28769. kjecyrillic: 0x045C,
  28770. klinebelow: 0x1E35,
  28771. klsquare: 0x3398,
  28772. kmcubedsquare: 0x33A6,
  28773. kmonospace: 0xFF4B,
  28774. kmsquaredsquare: 0x33A2,
  28775. kohiragana: 0x3053,
  28776. kohmsquare: 0x33C0,
  28777. kokaithai: 0x0E01,
  28778. kokatakana: 0x30B3,
  28779. kokatakanahalfwidth: 0xFF7A,
  28780. kooposquare: 0x331E,
  28781. koppacyrillic: 0x0481,
  28782. koreanstandardsymbol: 0x327F,
  28783. koroniscmb: 0x0343,
  28784. kparen: 0x24A6,
  28785. kpasquare: 0x33AA,
  28786. ksicyrillic: 0x046F,
  28787. ktsquare: 0x33CF,
  28788. kturned: 0x029E,
  28789. kuhiragana: 0x304F,
  28790. kukatakana: 0x30AF,
  28791. kukatakanahalfwidth: 0xFF78,
  28792. kvsquare: 0x33B8,
  28793. kwsquare: 0x33BE,
  28794. l: 0x006C,
  28795. labengali: 0x09B2,
  28796. lacute: 0x013A,
  28797. ladeva: 0x0932,
  28798. lagujarati: 0x0AB2,
  28799. lagurmukhi: 0x0A32,
  28800. lakkhangyaothai: 0x0E45,
  28801. lamaleffinalarabic: 0xFEFC,
  28802. lamalefhamzaabovefinalarabic: 0xFEF8,
  28803. lamalefhamzaaboveisolatedarabic: 0xFEF7,
  28804. lamalefhamzabelowfinalarabic: 0xFEFA,
  28805. lamalefhamzabelowisolatedarabic: 0xFEF9,
  28806. lamalefisolatedarabic: 0xFEFB,
  28807. lamalefmaddaabovefinalarabic: 0xFEF6,
  28808. lamalefmaddaaboveisolatedarabic: 0xFEF5,
  28809. lamarabic: 0x0644,
  28810. lambda: 0x03BB,
  28811. lambdastroke: 0x019B,
  28812. lamed: 0x05DC,
  28813. lameddagesh: 0xFB3C,
  28814. lameddageshhebrew: 0xFB3C,
  28815. lamedhebrew: 0x05DC,
  28816. lamfinalarabic: 0xFEDE,
  28817. lamhahinitialarabic: 0xFCCA,
  28818. laminitialarabic: 0xFEDF,
  28819. lamjeeminitialarabic: 0xFCC9,
  28820. lamkhahinitialarabic: 0xFCCB,
  28821. lamlamhehisolatedarabic: 0xFDF2,
  28822. lammedialarabic: 0xFEE0,
  28823. lammeemhahinitialarabic: 0xFD88,
  28824. lammeeminitialarabic: 0xFCCC,
  28825. largecircle: 0x25EF,
  28826. lbar: 0x019A,
  28827. lbelt: 0x026C,
  28828. lbopomofo: 0x310C,
  28829. lcaron: 0x013E,
  28830. lcedilla: 0x013C,
  28831. lcircle: 0x24DB,
  28832. lcircumflexbelow: 0x1E3D,
  28833. lcommaaccent: 0x013C,
  28834. ldot: 0x0140,
  28835. ldotaccent: 0x0140,
  28836. ldotbelow: 0x1E37,
  28837. ldotbelowmacron: 0x1E39,
  28838. leftangleabovecmb: 0x031A,
  28839. lefttackbelowcmb: 0x0318,
  28840. less: 0x003C,
  28841. lessequal: 0x2264,
  28842. lessequalorgreater: 0x22DA,
  28843. lessmonospace: 0xFF1C,
  28844. lessorequivalent: 0x2272,
  28845. lessorgreater: 0x2276,
  28846. lessoverequal: 0x2266,
  28847. lesssmall: 0xFE64,
  28848. lezh: 0x026E,
  28849. lfblock: 0x258C,
  28850. lhookretroflex: 0x026D,
  28851. lira: 0x20A4,
  28852. liwnarmenian: 0x056C,
  28853. lj: 0x01C9,
  28854. ljecyrillic: 0x0459,
  28855. ll: 0xF6C0,
  28856. lladeva: 0x0933,
  28857. llagujarati: 0x0AB3,
  28858. llinebelow: 0x1E3B,
  28859. llladeva: 0x0934,
  28860. llvocalicbengali: 0x09E1,
  28861. llvocalicdeva: 0x0961,
  28862. llvocalicvowelsignbengali: 0x09E3,
  28863. llvocalicvowelsigndeva: 0x0963,
  28864. lmiddletilde: 0x026B,
  28865. lmonospace: 0xFF4C,
  28866. lmsquare: 0x33D0,
  28867. lochulathai: 0x0E2C,
  28868. logicaland: 0x2227,
  28869. logicalnot: 0x00AC,
  28870. logicalnotreversed: 0x2310,
  28871. logicalor: 0x2228,
  28872. lolingthai: 0x0E25,
  28873. longs: 0x017F,
  28874. lowlinecenterline: 0xFE4E,
  28875. lowlinecmb: 0x0332,
  28876. lowlinedashed: 0xFE4D,
  28877. lozenge: 0x25CA,
  28878. lparen: 0x24A7,
  28879. lslash: 0x0142,
  28880. lsquare: 0x2113,
  28881. lsuperior: 0xF6EE,
  28882. ltshade: 0x2591,
  28883. luthai: 0x0E26,
  28884. lvocalicbengali: 0x098C,
  28885. lvocalicdeva: 0x090C,
  28886. lvocalicvowelsignbengali: 0x09E2,
  28887. lvocalicvowelsigndeva: 0x0962,
  28888. lxsquare: 0x33D3,
  28889. m: 0x006D,
  28890. mabengali: 0x09AE,
  28891. macron: 0x00AF,
  28892. macronbelowcmb: 0x0331,
  28893. macroncmb: 0x0304,
  28894. macronlowmod: 0x02CD,
  28895. macronmonospace: 0xFFE3,
  28896. macute: 0x1E3F,
  28897. madeva: 0x092E,
  28898. magujarati: 0x0AAE,
  28899. magurmukhi: 0x0A2E,
  28900. mahapakhhebrew: 0x05A4,
  28901. mahapakhlefthebrew: 0x05A4,
  28902. mahiragana: 0x307E,
  28903. maichattawalowleftthai: 0xF895,
  28904. maichattawalowrightthai: 0xF894,
  28905. maichattawathai: 0x0E4B,
  28906. maichattawaupperleftthai: 0xF893,
  28907. maieklowleftthai: 0xF88C,
  28908. maieklowrightthai: 0xF88B,
  28909. maiekthai: 0x0E48,
  28910. maiekupperleftthai: 0xF88A,
  28911. maihanakatleftthai: 0xF884,
  28912. maihanakatthai: 0x0E31,
  28913. maitaikhuleftthai: 0xF889,
  28914. maitaikhuthai: 0x0E47,
  28915. maitholowleftthai: 0xF88F,
  28916. maitholowrightthai: 0xF88E,
  28917. maithothai: 0x0E49,
  28918. maithoupperleftthai: 0xF88D,
  28919. maitrilowleftthai: 0xF892,
  28920. maitrilowrightthai: 0xF891,
  28921. maitrithai: 0x0E4A,
  28922. maitriupperleftthai: 0xF890,
  28923. maiyamokthai: 0x0E46,
  28924. makatakana: 0x30DE,
  28925. makatakanahalfwidth: 0xFF8F,
  28926. male: 0x2642,
  28927. mansyonsquare: 0x3347,
  28928. maqafhebrew: 0x05BE,
  28929. mars: 0x2642,
  28930. masoracirclehebrew: 0x05AF,
  28931. masquare: 0x3383,
  28932. mbopomofo: 0x3107,
  28933. mbsquare: 0x33D4,
  28934. mcircle: 0x24DC,
  28935. mcubedsquare: 0x33A5,
  28936. mdotaccent: 0x1E41,
  28937. mdotbelow: 0x1E43,
  28938. meemarabic: 0x0645,
  28939. meemfinalarabic: 0xFEE2,
  28940. meeminitialarabic: 0xFEE3,
  28941. meemmedialarabic: 0xFEE4,
  28942. meemmeeminitialarabic: 0xFCD1,
  28943. meemmeemisolatedarabic: 0xFC48,
  28944. meetorusquare: 0x334D,
  28945. mehiragana: 0x3081,
  28946. meizierasquare: 0x337E,
  28947. mekatakana: 0x30E1,
  28948. mekatakanahalfwidth: 0xFF92,
  28949. mem: 0x05DE,
  28950. memdagesh: 0xFB3E,
  28951. memdageshhebrew: 0xFB3E,
  28952. memhebrew: 0x05DE,
  28953. menarmenian: 0x0574,
  28954. merkhahebrew: 0x05A5,
  28955. merkhakefulahebrew: 0x05A6,
  28956. merkhakefulalefthebrew: 0x05A6,
  28957. merkhalefthebrew: 0x05A5,
  28958. mhook: 0x0271,
  28959. mhzsquare: 0x3392,
  28960. middledotkatakanahalfwidth: 0xFF65,
  28961. middot: 0x00B7,
  28962. mieumacirclekorean: 0x3272,
  28963. mieumaparenkorean: 0x3212,
  28964. mieumcirclekorean: 0x3264,
  28965. mieumkorean: 0x3141,
  28966. mieumpansioskorean: 0x3170,
  28967. mieumparenkorean: 0x3204,
  28968. mieumpieupkorean: 0x316E,
  28969. mieumsioskorean: 0x316F,
  28970. mihiragana: 0x307F,
  28971. mikatakana: 0x30DF,
  28972. mikatakanahalfwidth: 0xFF90,
  28973. minus: 0x2212,
  28974. minusbelowcmb: 0x0320,
  28975. minuscircle: 0x2296,
  28976. minusmod: 0x02D7,
  28977. minusplus: 0x2213,
  28978. minute: 0x2032,
  28979. miribaarusquare: 0x334A,
  28980. mirisquare: 0x3349,
  28981. mlonglegturned: 0x0270,
  28982. mlsquare: 0x3396,
  28983. mmcubedsquare: 0x33A3,
  28984. mmonospace: 0xFF4D,
  28985. mmsquaredsquare: 0x339F,
  28986. mohiragana: 0x3082,
  28987. mohmsquare: 0x33C1,
  28988. mokatakana: 0x30E2,
  28989. mokatakanahalfwidth: 0xFF93,
  28990. molsquare: 0x33D6,
  28991. momathai: 0x0E21,
  28992. moverssquare: 0x33A7,
  28993. moverssquaredsquare: 0x33A8,
  28994. mparen: 0x24A8,
  28995. mpasquare: 0x33AB,
  28996. mssquare: 0x33B3,
  28997. msuperior: 0xF6EF,
  28998. mturned: 0x026F,
  28999. mu: 0x00B5,
  29000. mu1: 0x00B5,
  29001. muasquare: 0x3382,
  29002. muchgreater: 0x226B,
  29003. muchless: 0x226A,
  29004. mufsquare: 0x338C,
  29005. mugreek: 0x03BC,
  29006. mugsquare: 0x338D,
  29007. muhiragana: 0x3080,
  29008. mukatakana: 0x30E0,
  29009. mukatakanahalfwidth: 0xFF91,
  29010. mulsquare: 0x3395,
  29011. multiply: 0x00D7,
  29012. mumsquare: 0x339B,
  29013. munahhebrew: 0x05A3,
  29014. munahlefthebrew: 0x05A3,
  29015. musicalnote: 0x266A,
  29016. musicalnotedbl: 0x266B,
  29017. musicflatsign: 0x266D,
  29018. musicsharpsign: 0x266F,
  29019. mussquare: 0x33B2,
  29020. muvsquare: 0x33B6,
  29021. muwsquare: 0x33BC,
  29022. mvmegasquare: 0x33B9,
  29023. mvsquare: 0x33B7,
  29024. mwmegasquare: 0x33BF,
  29025. mwsquare: 0x33BD,
  29026. n: 0x006E,
  29027. nabengali: 0x09A8,
  29028. nabla: 0x2207,
  29029. nacute: 0x0144,
  29030. nadeva: 0x0928,
  29031. nagujarati: 0x0AA8,
  29032. nagurmukhi: 0x0A28,
  29033. nahiragana: 0x306A,
  29034. nakatakana: 0x30CA,
  29035. nakatakanahalfwidth: 0xFF85,
  29036. napostrophe: 0x0149,
  29037. nasquare: 0x3381,
  29038. nbopomofo: 0x310B,
  29039. nbspace: 0x00A0,
  29040. ncaron: 0x0148,
  29041. ncedilla: 0x0146,
  29042. ncircle: 0x24DD,
  29043. ncircumflexbelow: 0x1E4B,
  29044. ncommaaccent: 0x0146,
  29045. ndotaccent: 0x1E45,
  29046. ndotbelow: 0x1E47,
  29047. nehiragana: 0x306D,
  29048. nekatakana: 0x30CD,
  29049. nekatakanahalfwidth: 0xFF88,
  29050. newsheqelsign: 0x20AA,
  29051. nfsquare: 0x338B,
  29052. ngabengali: 0x0999,
  29053. ngadeva: 0x0919,
  29054. ngagujarati: 0x0A99,
  29055. ngagurmukhi: 0x0A19,
  29056. ngonguthai: 0x0E07,
  29057. nhiragana: 0x3093,
  29058. nhookleft: 0x0272,
  29059. nhookretroflex: 0x0273,
  29060. nieunacirclekorean: 0x326F,
  29061. nieunaparenkorean: 0x320F,
  29062. nieuncieuckorean: 0x3135,
  29063. nieuncirclekorean: 0x3261,
  29064. nieunhieuhkorean: 0x3136,
  29065. nieunkorean: 0x3134,
  29066. nieunpansioskorean: 0x3168,
  29067. nieunparenkorean: 0x3201,
  29068. nieunsioskorean: 0x3167,
  29069. nieuntikeutkorean: 0x3166,
  29070. nihiragana: 0x306B,
  29071. nikatakana: 0x30CB,
  29072. nikatakanahalfwidth: 0xFF86,
  29073. nikhahitleftthai: 0xF899,
  29074. nikhahitthai: 0x0E4D,
  29075. nine: 0x0039,
  29076. ninearabic: 0x0669,
  29077. ninebengali: 0x09EF,
  29078. ninecircle: 0x2468,
  29079. ninecircleinversesansserif: 0x2792,
  29080. ninedeva: 0x096F,
  29081. ninegujarati: 0x0AEF,
  29082. ninegurmukhi: 0x0A6F,
  29083. ninehackarabic: 0x0669,
  29084. ninehangzhou: 0x3029,
  29085. nineideographicparen: 0x3228,
  29086. nineinferior: 0x2089,
  29087. ninemonospace: 0xFF19,
  29088. nineoldstyle: 0xF739,
  29089. nineparen: 0x247C,
  29090. nineperiod: 0x2490,
  29091. ninepersian: 0x06F9,
  29092. nineroman: 0x2178,
  29093. ninesuperior: 0x2079,
  29094. nineteencircle: 0x2472,
  29095. nineteenparen: 0x2486,
  29096. nineteenperiod: 0x249A,
  29097. ninethai: 0x0E59,
  29098. nj: 0x01CC,
  29099. njecyrillic: 0x045A,
  29100. nkatakana: 0x30F3,
  29101. nkatakanahalfwidth: 0xFF9D,
  29102. nlegrightlong: 0x019E,
  29103. nlinebelow: 0x1E49,
  29104. nmonospace: 0xFF4E,
  29105. nmsquare: 0x339A,
  29106. nnabengali: 0x09A3,
  29107. nnadeva: 0x0923,
  29108. nnagujarati: 0x0AA3,
  29109. nnagurmukhi: 0x0A23,
  29110. nnnadeva: 0x0929,
  29111. nohiragana: 0x306E,
  29112. nokatakana: 0x30CE,
  29113. nokatakanahalfwidth: 0xFF89,
  29114. nonbreakingspace: 0x00A0,
  29115. nonenthai: 0x0E13,
  29116. nonuthai: 0x0E19,
  29117. noonarabic: 0x0646,
  29118. noonfinalarabic: 0xFEE6,
  29119. noonghunnaarabic: 0x06BA,
  29120. noonghunnafinalarabic: 0xFB9F,
  29121. nooninitialarabic: 0xFEE7,
  29122. noonjeeminitialarabic: 0xFCD2,
  29123. noonjeemisolatedarabic: 0xFC4B,
  29124. noonmedialarabic: 0xFEE8,
  29125. noonmeeminitialarabic: 0xFCD5,
  29126. noonmeemisolatedarabic: 0xFC4E,
  29127. noonnoonfinalarabic: 0xFC8D,
  29128. notcontains: 0x220C,
  29129. notelement: 0x2209,
  29130. notelementof: 0x2209,
  29131. notequal: 0x2260,
  29132. notgreater: 0x226F,
  29133. notgreaternorequal: 0x2271,
  29134. notgreaternorless: 0x2279,
  29135. notidentical: 0x2262,
  29136. notless: 0x226E,
  29137. notlessnorequal: 0x2270,
  29138. notparallel: 0x2226,
  29139. notprecedes: 0x2280,
  29140. notsubset: 0x2284,
  29141. notsucceeds: 0x2281,
  29142. notsuperset: 0x2285,
  29143. nowarmenian: 0x0576,
  29144. nparen: 0x24A9,
  29145. nssquare: 0x33B1,
  29146. nsuperior: 0x207F,
  29147. ntilde: 0x00F1,
  29148. nu: 0x03BD,
  29149. nuhiragana: 0x306C,
  29150. nukatakana: 0x30CC,
  29151. nukatakanahalfwidth: 0xFF87,
  29152. nuktabengali: 0x09BC,
  29153. nuktadeva: 0x093C,
  29154. nuktagujarati: 0x0ABC,
  29155. nuktagurmukhi: 0x0A3C,
  29156. numbersign: 0x0023,
  29157. numbersignmonospace: 0xFF03,
  29158. numbersignsmall: 0xFE5F,
  29159. numeralsigngreek: 0x0374,
  29160. numeralsignlowergreek: 0x0375,
  29161. numero: 0x2116,
  29162. nun: 0x05E0,
  29163. nundagesh: 0xFB40,
  29164. nundageshhebrew: 0xFB40,
  29165. nunhebrew: 0x05E0,
  29166. nvsquare: 0x33B5,
  29167. nwsquare: 0x33BB,
  29168. nyabengali: 0x099E,
  29169. nyadeva: 0x091E,
  29170. nyagujarati: 0x0A9E,
  29171. nyagurmukhi: 0x0A1E,
  29172. o: 0x006F,
  29173. oacute: 0x00F3,
  29174. oangthai: 0x0E2D,
  29175. obarred: 0x0275,
  29176. obarredcyrillic: 0x04E9,
  29177. obarreddieresiscyrillic: 0x04EB,
  29178. obengali: 0x0993,
  29179. obopomofo: 0x311B,
  29180. obreve: 0x014F,
  29181. ocandradeva: 0x0911,
  29182. ocandragujarati: 0x0A91,
  29183. ocandravowelsigndeva: 0x0949,
  29184. ocandravowelsigngujarati: 0x0AC9,
  29185. ocaron: 0x01D2,
  29186. ocircle: 0x24DE,
  29187. ocircumflex: 0x00F4,
  29188. ocircumflexacute: 0x1ED1,
  29189. ocircumflexdotbelow: 0x1ED9,
  29190. ocircumflexgrave: 0x1ED3,
  29191. ocircumflexhookabove: 0x1ED5,
  29192. ocircumflextilde: 0x1ED7,
  29193. ocyrillic: 0x043E,
  29194. odblacute: 0x0151,
  29195. odblgrave: 0x020D,
  29196. odeva: 0x0913,
  29197. odieresis: 0x00F6,
  29198. odieresiscyrillic: 0x04E7,
  29199. odotbelow: 0x1ECD,
  29200. oe: 0x0153,
  29201. oekorean: 0x315A,
  29202. ogonek: 0x02DB,
  29203. ogonekcmb: 0x0328,
  29204. ograve: 0x00F2,
  29205. ogujarati: 0x0A93,
  29206. oharmenian: 0x0585,
  29207. ohiragana: 0x304A,
  29208. ohookabove: 0x1ECF,
  29209. ohorn: 0x01A1,
  29210. ohornacute: 0x1EDB,
  29211. ohorndotbelow: 0x1EE3,
  29212. ohorngrave: 0x1EDD,
  29213. ohornhookabove: 0x1EDF,
  29214. ohorntilde: 0x1EE1,
  29215. ohungarumlaut: 0x0151,
  29216. oi: 0x01A3,
  29217. oinvertedbreve: 0x020F,
  29218. okatakana: 0x30AA,
  29219. okatakanahalfwidth: 0xFF75,
  29220. okorean: 0x3157,
  29221. olehebrew: 0x05AB,
  29222. omacron: 0x014D,
  29223. omacronacute: 0x1E53,
  29224. omacrongrave: 0x1E51,
  29225. omdeva: 0x0950,
  29226. omega: 0x03C9,
  29227. omega1: 0x03D6,
  29228. omegacyrillic: 0x0461,
  29229. omegalatinclosed: 0x0277,
  29230. omegaroundcyrillic: 0x047B,
  29231. omegatitlocyrillic: 0x047D,
  29232. omegatonos: 0x03CE,
  29233. omgujarati: 0x0AD0,
  29234. omicron: 0x03BF,
  29235. omicrontonos: 0x03CC,
  29236. omonospace: 0xFF4F,
  29237. one: 0x0031,
  29238. onearabic: 0x0661,
  29239. onebengali: 0x09E7,
  29240. onecircle: 0x2460,
  29241. onecircleinversesansserif: 0x278A,
  29242. onedeva: 0x0967,
  29243. onedotenleader: 0x2024,
  29244. oneeighth: 0x215B,
  29245. onefitted: 0xF6DC,
  29246. onegujarati: 0x0AE7,
  29247. onegurmukhi: 0x0A67,
  29248. onehackarabic: 0x0661,
  29249. onehalf: 0x00BD,
  29250. onehangzhou: 0x3021,
  29251. oneideographicparen: 0x3220,
  29252. oneinferior: 0x2081,
  29253. onemonospace: 0xFF11,
  29254. onenumeratorbengali: 0x09F4,
  29255. oneoldstyle: 0xF731,
  29256. oneparen: 0x2474,
  29257. oneperiod: 0x2488,
  29258. onepersian: 0x06F1,
  29259. onequarter: 0x00BC,
  29260. oneroman: 0x2170,
  29261. onesuperior: 0x00B9,
  29262. onethai: 0x0E51,
  29263. onethird: 0x2153,
  29264. oogonek: 0x01EB,
  29265. oogonekmacron: 0x01ED,
  29266. oogurmukhi: 0x0A13,
  29267. oomatragurmukhi: 0x0A4B,
  29268. oopen: 0x0254,
  29269. oparen: 0x24AA,
  29270. openbullet: 0x25E6,
  29271. option: 0x2325,
  29272. ordfeminine: 0x00AA,
  29273. ordmasculine: 0x00BA,
  29274. orthogonal: 0x221F,
  29275. oshortdeva: 0x0912,
  29276. oshortvowelsigndeva: 0x094A,
  29277. oslash: 0x00F8,
  29278. oslashacute: 0x01FF,
  29279. osmallhiragana: 0x3049,
  29280. osmallkatakana: 0x30A9,
  29281. osmallkatakanahalfwidth: 0xFF6B,
  29282. ostrokeacute: 0x01FF,
  29283. osuperior: 0xF6F0,
  29284. otcyrillic: 0x047F,
  29285. otilde: 0x00F5,
  29286. otildeacute: 0x1E4D,
  29287. otildedieresis: 0x1E4F,
  29288. oubopomofo: 0x3121,
  29289. overline: 0x203E,
  29290. overlinecenterline: 0xFE4A,
  29291. overlinecmb: 0x0305,
  29292. overlinedashed: 0xFE49,
  29293. overlinedblwavy: 0xFE4C,
  29294. overlinewavy: 0xFE4B,
  29295. overscore: 0x00AF,
  29296. ovowelsignbengali: 0x09CB,
  29297. ovowelsigndeva: 0x094B,
  29298. ovowelsigngujarati: 0x0ACB,
  29299. p: 0x0070,
  29300. paampssquare: 0x3380,
  29301. paasentosquare: 0x332B,
  29302. pabengali: 0x09AA,
  29303. pacute: 0x1E55,
  29304. padeva: 0x092A,
  29305. pagedown: 0x21DF,
  29306. pageup: 0x21DE,
  29307. pagujarati: 0x0AAA,
  29308. pagurmukhi: 0x0A2A,
  29309. pahiragana: 0x3071,
  29310. paiyannoithai: 0x0E2F,
  29311. pakatakana: 0x30D1,
  29312. palatalizationcyrilliccmb: 0x0484,
  29313. palochkacyrillic: 0x04C0,
  29314. pansioskorean: 0x317F,
  29315. paragraph: 0x00B6,
  29316. parallel: 0x2225,
  29317. parenleft: 0x0028,
  29318. parenleftaltonearabic: 0xFD3E,
  29319. parenleftbt: 0xF8ED,
  29320. parenleftex: 0xF8EC,
  29321. parenleftinferior: 0x208D,
  29322. parenleftmonospace: 0xFF08,
  29323. parenleftsmall: 0xFE59,
  29324. parenleftsuperior: 0x207D,
  29325. parenlefttp: 0xF8EB,
  29326. parenleftvertical: 0xFE35,
  29327. parenright: 0x0029,
  29328. parenrightaltonearabic: 0xFD3F,
  29329. parenrightbt: 0xF8F8,
  29330. parenrightex: 0xF8F7,
  29331. parenrightinferior: 0x208E,
  29332. parenrightmonospace: 0xFF09,
  29333. parenrightsmall: 0xFE5A,
  29334. parenrightsuperior: 0x207E,
  29335. parenrighttp: 0xF8F6,
  29336. parenrightvertical: 0xFE36,
  29337. partialdiff: 0x2202,
  29338. paseqhebrew: 0x05C0,
  29339. pashtahebrew: 0x0599,
  29340. pasquare: 0x33A9,
  29341. patah: 0x05B7,
  29342. patah11: 0x05B7,
  29343. patah1d: 0x05B7,
  29344. patah2a: 0x05B7,
  29345. patahhebrew: 0x05B7,
  29346. patahnarrowhebrew: 0x05B7,
  29347. patahquarterhebrew: 0x05B7,
  29348. patahwidehebrew: 0x05B7,
  29349. pazerhebrew: 0x05A1,
  29350. pbopomofo: 0x3106,
  29351. pcircle: 0x24DF,
  29352. pdotaccent: 0x1E57,
  29353. pe: 0x05E4,
  29354. pecyrillic: 0x043F,
  29355. pedagesh: 0xFB44,
  29356. pedageshhebrew: 0xFB44,
  29357. peezisquare: 0x333B,
  29358. pefinaldageshhebrew: 0xFB43,
  29359. peharabic: 0x067E,
  29360. peharmenian: 0x057A,
  29361. pehebrew: 0x05E4,
  29362. pehfinalarabic: 0xFB57,
  29363. pehinitialarabic: 0xFB58,
  29364. pehiragana: 0x307A,
  29365. pehmedialarabic: 0xFB59,
  29366. pekatakana: 0x30DA,
  29367. pemiddlehookcyrillic: 0x04A7,
  29368. perafehebrew: 0xFB4E,
  29369. percent: 0x0025,
  29370. percentarabic: 0x066A,
  29371. percentmonospace: 0xFF05,
  29372. percentsmall: 0xFE6A,
  29373. period: 0x002E,
  29374. periodarmenian: 0x0589,
  29375. periodcentered: 0x00B7,
  29376. periodhalfwidth: 0xFF61,
  29377. periodinferior: 0xF6E7,
  29378. periodmonospace: 0xFF0E,
  29379. periodsmall: 0xFE52,
  29380. periodsuperior: 0xF6E8,
  29381. perispomenigreekcmb: 0x0342,
  29382. perpendicular: 0x22A5,
  29383. perthousand: 0x2030,
  29384. peseta: 0x20A7,
  29385. pfsquare: 0x338A,
  29386. phabengali: 0x09AB,
  29387. phadeva: 0x092B,
  29388. phagujarati: 0x0AAB,
  29389. phagurmukhi: 0x0A2B,
  29390. phi: 0x03C6,
  29391. phi1: 0x03D5,
  29392. phieuphacirclekorean: 0x327A,
  29393. phieuphaparenkorean: 0x321A,
  29394. phieuphcirclekorean: 0x326C,
  29395. phieuphkorean: 0x314D,
  29396. phieuphparenkorean: 0x320C,
  29397. philatin: 0x0278,
  29398. phinthuthai: 0x0E3A,
  29399. phisymbolgreek: 0x03D5,
  29400. phook: 0x01A5,
  29401. phophanthai: 0x0E1E,
  29402. phophungthai: 0x0E1C,
  29403. phosamphaothai: 0x0E20,
  29404. pi: 0x03C0,
  29405. pieupacirclekorean: 0x3273,
  29406. pieupaparenkorean: 0x3213,
  29407. pieupcieuckorean: 0x3176,
  29408. pieupcirclekorean: 0x3265,
  29409. pieupkiyeokkorean: 0x3172,
  29410. pieupkorean: 0x3142,
  29411. pieupparenkorean: 0x3205,
  29412. pieupsioskiyeokkorean: 0x3174,
  29413. pieupsioskorean: 0x3144,
  29414. pieupsiostikeutkorean: 0x3175,
  29415. pieupthieuthkorean: 0x3177,
  29416. pieuptikeutkorean: 0x3173,
  29417. pihiragana: 0x3074,
  29418. pikatakana: 0x30D4,
  29419. pisymbolgreek: 0x03D6,
  29420. piwrarmenian: 0x0583,
  29421. plus: 0x002B,
  29422. plusbelowcmb: 0x031F,
  29423. pluscircle: 0x2295,
  29424. plusminus: 0x00B1,
  29425. plusmod: 0x02D6,
  29426. plusmonospace: 0xFF0B,
  29427. plussmall: 0xFE62,
  29428. plussuperior: 0x207A,
  29429. pmonospace: 0xFF50,
  29430. pmsquare: 0x33D8,
  29431. pohiragana: 0x307D,
  29432. pointingindexdownwhite: 0x261F,
  29433. pointingindexleftwhite: 0x261C,
  29434. pointingindexrightwhite: 0x261E,
  29435. pointingindexupwhite: 0x261D,
  29436. pokatakana: 0x30DD,
  29437. poplathai: 0x0E1B,
  29438. postalmark: 0x3012,
  29439. postalmarkface: 0x3020,
  29440. pparen: 0x24AB,
  29441. precedes: 0x227A,
  29442. prescription: 0x211E,
  29443. primemod: 0x02B9,
  29444. primereversed: 0x2035,
  29445. product: 0x220F,
  29446. projective: 0x2305,
  29447. prolongedkana: 0x30FC,
  29448. propellor: 0x2318,
  29449. propersubset: 0x2282,
  29450. propersuperset: 0x2283,
  29451. proportion: 0x2237,
  29452. proportional: 0x221D,
  29453. psi: 0x03C8,
  29454. psicyrillic: 0x0471,
  29455. psilipneumatacyrilliccmb: 0x0486,
  29456. pssquare: 0x33B0,
  29457. puhiragana: 0x3077,
  29458. pukatakana: 0x30D7,
  29459. pvsquare: 0x33B4,
  29460. pwsquare: 0x33BA,
  29461. q: 0x0071,
  29462. qadeva: 0x0958,
  29463. qadmahebrew: 0x05A8,
  29464. qafarabic: 0x0642,
  29465. qaffinalarabic: 0xFED6,
  29466. qafinitialarabic: 0xFED7,
  29467. qafmedialarabic: 0xFED8,
  29468. qamats: 0x05B8,
  29469. qamats10: 0x05B8,
  29470. qamats1a: 0x05B8,
  29471. qamats1c: 0x05B8,
  29472. qamats27: 0x05B8,
  29473. qamats29: 0x05B8,
  29474. qamats33: 0x05B8,
  29475. qamatsde: 0x05B8,
  29476. qamatshebrew: 0x05B8,
  29477. qamatsnarrowhebrew: 0x05B8,
  29478. qamatsqatanhebrew: 0x05B8,
  29479. qamatsqatannarrowhebrew: 0x05B8,
  29480. qamatsqatanquarterhebrew: 0x05B8,
  29481. qamatsqatanwidehebrew: 0x05B8,
  29482. qamatsquarterhebrew: 0x05B8,
  29483. qamatswidehebrew: 0x05B8,
  29484. qarneyparahebrew: 0x059F,
  29485. qbopomofo: 0x3111,
  29486. qcircle: 0x24E0,
  29487. qhook: 0x02A0,
  29488. qmonospace: 0xFF51,
  29489. qof: 0x05E7,
  29490. qofdagesh: 0xFB47,
  29491. qofdageshhebrew: 0xFB47,
  29492. qofhebrew: 0x05E7,
  29493. qparen: 0x24AC,
  29494. quarternote: 0x2669,
  29495. qubuts: 0x05BB,
  29496. qubuts18: 0x05BB,
  29497. qubuts25: 0x05BB,
  29498. qubuts31: 0x05BB,
  29499. qubutshebrew: 0x05BB,
  29500. qubutsnarrowhebrew: 0x05BB,
  29501. qubutsquarterhebrew: 0x05BB,
  29502. qubutswidehebrew: 0x05BB,
  29503. question: 0x003F,
  29504. questionarabic: 0x061F,
  29505. questionarmenian: 0x055E,
  29506. questiondown: 0x00BF,
  29507. questiondownsmall: 0xF7BF,
  29508. questiongreek: 0x037E,
  29509. questionmonospace: 0xFF1F,
  29510. questionsmall: 0xF73F,
  29511. quotedbl: 0x0022,
  29512. quotedblbase: 0x201E,
  29513. quotedblleft: 0x201C,
  29514. quotedblmonospace: 0xFF02,
  29515. quotedblprime: 0x301E,
  29516. quotedblprimereversed: 0x301D,
  29517. quotedblright: 0x201D,
  29518. quoteleft: 0x2018,
  29519. quoteleftreversed: 0x201B,
  29520. quotereversed: 0x201B,
  29521. quoteright: 0x2019,
  29522. quoterightn: 0x0149,
  29523. quotesinglbase: 0x201A,
  29524. quotesingle: 0x0027,
  29525. quotesinglemonospace: 0xFF07,
  29526. r: 0x0072,
  29527. raarmenian: 0x057C,
  29528. rabengali: 0x09B0,
  29529. racute: 0x0155,
  29530. radeva: 0x0930,
  29531. radical: 0x221A,
  29532. radicalex: 0xF8E5,
  29533. radoverssquare: 0x33AE,
  29534. radoverssquaredsquare: 0x33AF,
  29535. radsquare: 0x33AD,
  29536. rafe: 0x05BF,
  29537. rafehebrew: 0x05BF,
  29538. ragujarati: 0x0AB0,
  29539. ragurmukhi: 0x0A30,
  29540. rahiragana: 0x3089,
  29541. rakatakana: 0x30E9,
  29542. rakatakanahalfwidth: 0xFF97,
  29543. ralowerdiagonalbengali: 0x09F1,
  29544. ramiddlediagonalbengali: 0x09F0,
  29545. ramshorn: 0x0264,
  29546. ratio: 0x2236,
  29547. rbopomofo: 0x3116,
  29548. rcaron: 0x0159,
  29549. rcedilla: 0x0157,
  29550. rcircle: 0x24E1,
  29551. rcommaaccent: 0x0157,
  29552. rdblgrave: 0x0211,
  29553. rdotaccent: 0x1E59,
  29554. rdotbelow: 0x1E5B,
  29555. rdotbelowmacron: 0x1E5D,
  29556. referencemark: 0x203B,
  29557. reflexsubset: 0x2286,
  29558. reflexsuperset: 0x2287,
  29559. registered: 0x00AE,
  29560. registersans: 0xF8E8,
  29561. registerserif: 0xF6DA,
  29562. reharabic: 0x0631,
  29563. reharmenian: 0x0580,
  29564. rehfinalarabic: 0xFEAE,
  29565. rehiragana: 0x308C,
  29566. rekatakana: 0x30EC,
  29567. rekatakanahalfwidth: 0xFF9A,
  29568. resh: 0x05E8,
  29569. reshdageshhebrew: 0xFB48,
  29570. reshhebrew: 0x05E8,
  29571. reversedtilde: 0x223D,
  29572. reviahebrew: 0x0597,
  29573. reviamugrashhebrew: 0x0597,
  29574. revlogicalnot: 0x2310,
  29575. rfishhook: 0x027E,
  29576. rfishhookreversed: 0x027F,
  29577. rhabengali: 0x09DD,
  29578. rhadeva: 0x095D,
  29579. rho: 0x03C1,
  29580. rhook: 0x027D,
  29581. rhookturned: 0x027B,
  29582. rhookturnedsuperior: 0x02B5,
  29583. rhosymbolgreek: 0x03F1,
  29584. rhotichookmod: 0x02DE,
  29585. rieulacirclekorean: 0x3271,
  29586. rieulaparenkorean: 0x3211,
  29587. rieulcirclekorean: 0x3263,
  29588. rieulhieuhkorean: 0x3140,
  29589. rieulkiyeokkorean: 0x313A,
  29590. rieulkiyeoksioskorean: 0x3169,
  29591. rieulkorean: 0x3139,
  29592. rieulmieumkorean: 0x313B,
  29593. rieulpansioskorean: 0x316C,
  29594. rieulparenkorean: 0x3203,
  29595. rieulphieuphkorean: 0x313F,
  29596. rieulpieupkorean: 0x313C,
  29597. rieulpieupsioskorean: 0x316B,
  29598. rieulsioskorean: 0x313D,
  29599. rieulthieuthkorean: 0x313E,
  29600. rieultikeutkorean: 0x316A,
  29601. rieulyeorinhieuhkorean: 0x316D,
  29602. rightangle: 0x221F,
  29603. righttackbelowcmb: 0x0319,
  29604. righttriangle: 0x22BF,
  29605. rihiragana: 0x308A,
  29606. rikatakana: 0x30EA,
  29607. rikatakanahalfwidth: 0xFF98,
  29608. ring: 0x02DA,
  29609. ringbelowcmb: 0x0325,
  29610. ringcmb: 0x030A,
  29611. ringhalfleft: 0x02BF,
  29612. ringhalfleftarmenian: 0x0559,
  29613. ringhalfleftbelowcmb: 0x031C,
  29614. ringhalfleftcentered: 0x02D3,
  29615. ringhalfright: 0x02BE,
  29616. ringhalfrightbelowcmb: 0x0339,
  29617. ringhalfrightcentered: 0x02D2,
  29618. rinvertedbreve: 0x0213,
  29619. rittorusquare: 0x3351,
  29620. rlinebelow: 0x1E5F,
  29621. rlongleg: 0x027C,
  29622. rlonglegturned: 0x027A,
  29623. rmonospace: 0xFF52,
  29624. rohiragana: 0x308D,
  29625. rokatakana: 0x30ED,
  29626. rokatakanahalfwidth: 0xFF9B,
  29627. roruathai: 0x0E23,
  29628. rparen: 0x24AD,
  29629. rrabengali: 0x09DC,
  29630. rradeva: 0x0931,
  29631. rragurmukhi: 0x0A5C,
  29632. rreharabic: 0x0691,
  29633. rrehfinalarabic: 0xFB8D,
  29634. rrvocalicbengali: 0x09E0,
  29635. rrvocalicdeva: 0x0960,
  29636. rrvocalicgujarati: 0x0AE0,
  29637. rrvocalicvowelsignbengali: 0x09C4,
  29638. rrvocalicvowelsigndeva: 0x0944,
  29639. rrvocalicvowelsigngujarati: 0x0AC4,
  29640. rsuperior: 0xF6F1,
  29641. rtblock: 0x2590,
  29642. rturned: 0x0279,
  29643. rturnedsuperior: 0x02B4,
  29644. ruhiragana: 0x308B,
  29645. rukatakana: 0x30EB,
  29646. rukatakanahalfwidth: 0xFF99,
  29647. rupeemarkbengali: 0x09F2,
  29648. rupeesignbengali: 0x09F3,
  29649. rupiah: 0xF6DD,
  29650. ruthai: 0x0E24,
  29651. rvocalicbengali: 0x098B,
  29652. rvocalicdeva: 0x090B,
  29653. rvocalicgujarati: 0x0A8B,
  29654. rvocalicvowelsignbengali: 0x09C3,
  29655. rvocalicvowelsigndeva: 0x0943,
  29656. rvocalicvowelsigngujarati: 0x0AC3,
  29657. s: 0x0073,
  29658. sabengali: 0x09B8,
  29659. sacute: 0x015B,
  29660. sacutedotaccent: 0x1E65,
  29661. sadarabic: 0x0635,
  29662. sadeva: 0x0938,
  29663. sadfinalarabic: 0xFEBA,
  29664. sadinitialarabic: 0xFEBB,
  29665. sadmedialarabic: 0xFEBC,
  29666. sagujarati: 0x0AB8,
  29667. sagurmukhi: 0x0A38,
  29668. sahiragana: 0x3055,
  29669. sakatakana: 0x30B5,
  29670. sakatakanahalfwidth: 0xFF7B,
  29671. sallallahoualayhewasallamarabic: 0xFDFA,
  29672. samekh: 0x05E1,
  29673. samekhdagesh: 0xFB41,
  29674. samekhdageshhebrew: 0xFB41,
  29675. samekhhebrew: 0x05E1,
  29676. saraaathai: 0x0E32,
  29677. saraaethai: 0x0E41,
  29678. saraaimaimalaithai: 0x0E44,
  29679. saraaimaimuanthai: 0x0E43,
  29680. saraamthai: 0x0E33,
  29681. saraathai: 0x0E30,
  29682. saraethai: 0x0E40,
  29683. saraiileftthai: 0xF886,
  29684. saraiithai: 0x0E35,
  29685. saraileftthai: 0xF885,
  29686. saraithai: 0x0E34,
  29687. saraothai: 0x0E42,
  29688. saraueeleftthai: 0xF888,
  29689. saraueethai: 0x0E37,
  29690. saraueleftthai: 0xF887,
  29691. sarauethai: 0x0E36,
  29692. sarauthai: 0x0E38,
  29693. sarauuthai: 0x0E39,
  29694. sbopomofo: 0x3119,
  29695. scaron: 0x0161,
  29696. scarondotaccent: 0x1E67,
  29697. scedilla: 0x015F,
  29698. schwa: 0x0259,
  29699. schwacyrillic: 0x04D9,
  29700. schwadieresiscyrillic: 0x04DB,
  29701. schwahook: 0x025A,
  29702. scircle: 0x24E2,
  29703. scircumflex: 0x015D,
  29704. scommaaccent: 0x0219,
  29705. sdotaccent: 0x1E61,
  29706. sdotbelow: 0x1E63,
  29707. sdotbelowdotaccent: 0x1E69,
  29708. seagullbelowcmb: 0x033C,
  29709. second: 0x2033,
  29710. secondtonechinese: 0x02CA,
  29711. section: 0x00A7,
  29712. seenarabic: 0x0633,
  29713. seenfinalarabic: 0xFEB2,
  29714. seeninitialarabic: 0xFEB3,
  29715. seenmedialarabic: 0xFEB4,
  29716. segol: 0x05B6,
  29717. segol13: 0x05B6,
  29718. segol1f: 0x05B6,
  29719. segol2c: 0x05B6,
  29720. segolhebrew: 0x05B6,
  29721. segolnarrowhebrew: 0x05B6,
  29722. segolquarterhebrew: 0x05B6,
  29723. segoltahebrew: 0x0592,
  29724. segolwidehebrew: 0x05B6,
  29725. seharmenian: 0x057D,
  29726. sehiragana: 0x305B,
  29727. sekatakana: 0x30BB,
  29728. sekatakanahalfwidth: 0xFF7E,
  29729. semicolon: 0x003B,
  29730. semicolonarabic: 0x061B,
  29731. semicolonmonospace: 0xFF1B,
  29732. semicolonsmall: 0xFE54,
  29733. semivoicedmarkkana: 0x309C,
  29734. semivoicedmarkkanahalfwidth: 0xFF9F,
  29735. sentisquare: 0x3322,
  29736. sentosquare: 0x3323,
  29737. seven: 0x0037,
  29738. sevenarabic: 0x0667,
  29739. sevenbengali: 0x09ED,
  29740. sevencircle: 0x2466,
  29741. sevencircleinversesansserif: 0x2790,
  29742. sevendeva: 0x096D,
  29743. seveneighths: 0x215E,
  29744. sevengujarati: 0x0AED,
  29745. sevengurmukhi: 0x0A6D,
  29746. sevenhackarabic: 0x0667,
  29747. sevenhangzhou: 0x3027,
  29748. sevenideographicparen: 0x3226,
  29749. seveninferior: 0x2087,
  29750. sevenmonospace: 0xFF17,
  29751. sevenoldstyle: 0xF737,
  29752. sevenparen: 0x247A,
  29753. sevenperiod: 0x248E,
  29754. sevenpersian: 0x06F7,
  29755. sevenroman: 0x2176,
  29756. sevensuperior: 0x2077,
  29757. seventeencircle: 0x2470,
  29758. seventeenparen: 0x2484,
  29759. seventeenperiod: 0x2498,
  29760. seventhai: 0x0E57,
  29761. sfthyphen: 0x00AD,
  29762. shaarmenian: 0x0577,
  29763. shabengali: 0x09B6,
  29764. shacyrillic: 0x0448,
  29765. shaddaarabic: 0x0651,
  29766. shaddadammaarabic: 0xFC61,
  29767. shaddadammatanarabic: 0xFC5E,
  29768. shaddafathaarabic: 0xFC60,
  29769. shaddakasraarabic: 0xFC62,
  29770. shaddakasratanarabic: 0xFC5F,
  29771. shade: 0x2592,
  29772. shadedark: 0x2593,
  29773. shadelight: 0x2591,
  29774. shademedium: 0x2592,
  29775. shadeva: 0x0936,
  29776. shagujarati: 0x0AB6,
  29777. shagurmukhi: 0x0A36,
  29778. shalshelethebrew: 0x0593,
  29779. shbopomofo: 0x3115,
  29780. shchacyrillic: 0x0449,
  29781. sheenarabic: 0x0634,
  29782. sheenfinalarabic: 0xFEB6,
  29783. sheeninitialarabic: 0xFEB7,
  29784. sheenmedialarabic: 0xFEB8,
  29785. sheicoptic: 0x03E3,
  29786. sheqel: 0x20AA,
  29787. sheqelhebrew: 0x20AA,
  29788. sheva: 0x05B0,
  29789. sheva115: 0x05B0,
  29790. sheva15: 0x05B0,
  29791. sheva22: 0x05B0,
  29792. sheva2e: 0x05B0,
  29793. shevahebrew: 0x05B0,
  29794. shevanarrowhebrew: 0x05B0,
  29795. shevaquarterhebrew: 0x05B0,
  29796. shevawidehebrew: 0x05B0,
  29797. shhacyrillic: 0x04BB,
  29798. shimacoptic: 0x03ED,
  29799. shin: 0x05E9,
  29800. shindagesh: 0xFB49,
  29801. shindageshhebrew: 0xFB49,
  29802. shindageshshindot: 0xFB2C,
  29803. shindageshshindothebrew: 0xFB2C,
  29804. shindageshsindot: 0xFB2D,
  29805. shindageshsindothebrew: 0xFB2D,
  29806. shindothebrew: 0x05C1,
  29807. shinhebrew: 0x05E9,
  29808. shinshindot: 0xFB2A,
  29809. shinshindothebrew: 0xFB2A,
  29810. shinsindot: 0xFB2B,
  29811. shinsindothebrew: 0xFB2B,
  29812. shook: 0x0282,
  29813. sigma: 0x03C3,
  29814. sigma1: 0x03C2,
  29815. sigmafinal: 0x03C2,
  29816. sigmalunatesymbolgreek: 0x03F2,
  29817. sihiragana: 0x3057,
  29818. sikatakana: 0x30B7,
  29819. sikatakanahalfwidth: 0xFF7C,
  29820. siluqhebrew: 0x05BD,
  29821. siluqlefthebrew: 0x05BD,
  29822. similar: 0x223C,
  29823. sindothebrew: 0x05C2,
  29824. siosacirclekorean: 0x3274,
  29825. siosaparenkorean: 0x3214,
  29826. sioscieuckorean: 0x317E,
  29827. sioscirclekorean: 0x3266,
  29828. sioskiyeokkorean: 0x317A,
  29829. sioskorean: 0x3145,
  29830. siosnieunkorean: 0x317B,
  29831. siosparenkorean: 0x3206,
  29832. siospieupkorean: 0x317D,
  29833. siostikeutkorean: 0x317C,
  29834. six: 0x0036,
  29835. sixarabic: 0x0666,
  29836. sixbengali: 0x09EC,
  29837. sixcircle: 0x2465,
  29838. sixcircleinversesansserif: 0x278F,
  29839. sixdeva: 0x096C,
  29840. sixgujarati: 0x0AEC,
  29841. sixgurmukhi: 0x0A6C,
  29842. sixhackarabic: 0x0666,
  29843. sixhangzhou: 0x3026,
  29844. sixideographicparen: 0x3225,
  29845. sixinferior: 0x2086,
  29846. sixmonospace: 0xFF16,
  29847. sixoldstyle: 0xF736,
  29848. sixparen: 0x2479,
  29849. sixperiod: 0x248D,
  29850. sixpersian: 0x06F6,
  29851. sixroman: 0x2175,
  29852. sixsuperior: 0x2076,
  29853. sixteencircle: 0x246F,
  29854. sixteencurrencydenominatorbengali: 0x09F9,
  29855. sixteenparen: 0x2483,
  29856. sixteenperiod: 0x2497,
  29857. sixthai: 0x0E56,
  29858. slash: 0x002F,
  29859. slashmonospace: 0xFF0F,
  29860. slong: 0x017F,
  29861. slongdotaccent: 0x1E9B,
  29862. smileface: 0x263A,
  29863. smonospace: 0xFF53,
  29864. sofpasuqhebrew: 0x05C3,
  29865. softhyphen: 0x00AD,
  29866. softsigncyrillic: 0x044C,
  29867. sohiragana: 0x305D,
  29868. sokatakana: 0x30BD,
  29869. sokatakanahalfwidth: 0xFF7F,
  29870. soliduslongoverlaycmb: 0x0338,
  29871. solidusshortoverlaycmb: 0x0337,
  29872. sorusithai: 0x0E29,
  29873. sosalathai: 0x0E28,
  29874. sosothai: 0x0E0B,
  29875. sosuathai: 0x0E2A,
  29876. space: 0x0020,
  29877. spacehackarabic: 0x0020,
  29878. spade: 0x2660,
  29879. spadesuitblack: 0x2660,
  29880. spadesuitwhite: 0x2664,
  29881. sparen: 0x24AE,
  29882. squarebelowcmb: 0x033B,
  29883. squarecc: 0x33C4,
  29884. squarecm: 0x339D,
  29885. squarediagonalcrosshatchfill: 0x25A9,
  29886. squarehorizontalfill: 0x25A4,
  29887. squarekg: 0x338F,
  29888. squarekm: 0x339E,
  29889. squarekmcapital: 0x33CE,
  29890. squareln: 0x33D1,
  29891. squarelog: 0x33D2,
  29892. squaremg: 0x338E,
  29893. squaremil: 0x33D5,
  29894. squaremm: 0x339C,
  29895. squaremsquared: 0x33A1,
  29896. squareorthogonalcrosshatchfill: 0x25A6,
  29897. squareupperlefttolowerrightfill: 0x25A7,
  29898. squareupperrighttolowerleftfill: 0x25A8,
  29899. squareverticalfill: 0x25A5,
  29900. squarewhitewithsmallblack: 0x25A3,
  29901. srsquare: 0x33DB,
  29902. ssabengali: 0x09B7,
  29903. ssadeva: 0x0937,
  29904. ssagujarati: 0x0AB7,
  29905. ssangcieuckorean: 0x3149,
  29906. ssanghieuhkorean: 0x3185,
  29907. ssangieungkorean: 0x3180,
  29908. ssangkiyeokkorean: 0x3132,
  29909. ssangnieunkorean: 0x3165,
  29910. ssangpieupkorean: 0x3143,
  29911. ssangsioskorean: 0x3146,
  29912. ssangtikeutkorean: 0x3138,
  29913. ssuperior: 0xF6F2,
  29914. sterling: 0x00A3,
  29915. sterlingmonospace: 0xFFE1,
  29916. strokelongoverlaycmb: 0x0336,
  29917. strokeshortoverlaycmb: 0x0335,
  29918. subset: 0x2282,
  29919. subsetnotequal: 0x228A,
  29920. subsetorequal: 0x2286,
  29921. succeeds: 0x227B,
  29922. suchthat: 0x220B,
  29923. suhiragana: 0x3059,
  29924. sukatakana: 0x30B9,
  29925. sukatakanahalfwidth: 0xFF7D,
  29926. sukunarabic: 0x0652,
  29927. summation: 0x2211,
  29928. sun: 0x263C,
  29929. superset: 0x2283,
  29930. supersetnotequal: 0x228B,
  29931. supersetorequal: 0x2287,
  29932. svsquare: 0x33DC,
  29933. syouwaerasquare: 0x337C,
  29934. t: 0x0074,
  29935. tabengali: 0x09A4,
  29936. tackdown: 0x22A4,
  29937. tackleft: 0x22A3,
  29938. tadeva: 0x0924,
  29939. tagujarati: 0x0AA4,
  29940. tagurmukhi: 0x0A24,
  29941. taharabic: 0x0637,
  29942. tahfinalarabic: 0xFEC2,
  29943. tahinitialarabic: 0xFEC3,
  29944. tahiragana: 0x305F,
  29945. tahmedialarabic: 0xFEC4,
  29946. taisyouerasquare: 0x337D,
  29947. takatakana: 0x30BF,
  29948. takatakanahalfwidth: 0xFF80,
  29949. tatweelarabic: 0x0640,
  29950. tau: 0x03C4,
  29951. tav: 0x05EA,
  29952. tavdages: 0xFB4A,
  29953. tavdagesh: 0xFB4A,
  29954. tavdageshhebrew: 0xFB4A,
  29955. tavhebrew: 0x05EA,
  29956. tbar: 0x0167,
  29957. tbopomofo: 0x310A,
  29958. tcaron: 0x0165,
  29959. tccurl: 0x02A8,
  29960. tcedilla: 0x0163,
  29961. tcheharabic: 0x0686,
  29962. tchehfinalarabic: 0xFB7B,
  29963. tchehinitialarabic: 0xFB7C,
  29964. tchehmedialarabic: 0xFB7D,
  29965. tcircle: 0x24E3,
  29966. tcircumflexbelow: 0x1E71,
  29967. tcommaaccent: 0x0163,
  29968. tdieresis: 0x1E97,
  29969. tdotaccent: 0x1E6B,
  29970. tdotbelow: 0x1E6D,
  29971. tecyrillic: 0x0442,
  29972. tedescendercyrillic: 0x04AD,
  29973. teharabic: 0x062A,
  29974. tehfinalarabic: 0xFE96,
  29975. tehhahinitialarabic: 0xFCA2,
  29976. tehhahisolatedarabic: 0xFC0C,
  29977. tehinitialarabic: 0xFE97,
  29978. tehiragana: 0x3066,
  29979. tehjeeminitialarabic: 0xFCA1,
  29980. tehjeemisolatedarabic: 0xFC0B,
  29981. tehmarbutaarabic: 0x0629,
  29982. tehmarbutafinalarabic: 0xFE94,
  29983. tehmedialarabic: 0xFE98,
  29984. tehmeeminitialarabic: 0xFCA4,
  29985. tehmeemisolatedarabic: 0xFC0E,
  29986. tehnoonfinalarabic: 0xFC73,
  29987. tekatakana: 0x30C6,
  29988. tekatakanahalfwidth: 0xFF83,
  29989. telephone: 0x2121,
  29990. telephoneblack: 0x260E,
  29991. telishagedolahebrew: 0x05A0,
  29992. telishaqetanahebrew: 0x05A9,
  29993. tencircle: 0x2469,
  29994. tenideographicparen: 0x3229,
  29995. tenparen: 0x247D,
  29996. tenperiod: 0x2491,
  29997. tenroman: 0x2179,
  29998. tesh: 0x02A7,
  29999. tet: 0x05D8,
  30000. tetdagesh: 0xFB38,
  30001. tetdageshhebrew: 0xFB38,
  30002. tethebrew: 0x05D8,
  30003. tetsecyrillic: 0x04B5,
  30004. tevirhebrew: 0x059B,
  30005. tevirlefthebrew: 0x059B,
  30006. thabengali: 0x09A5,
  30007. thadeva: 0x0925,
  30008. thagujarati: 0x0AA5,
  30009. thagurmukhi: 0x0A25,
  30010. thalarabic: 0x0630,
  30011. thalfinalarabic: 0xFEAC,
  30012. thanthakhatlowleftthai: 0xF898,
  30013. thanthakhatlowrightthai: 0xF897,
  30014. thanthakhatthai: 0x0E4C,
  30015. thanthakhatupperleftthai: 0xF896,
  30016. theharabic: 0x062B,
  30017. thehfinalarabic: 0xFE9A,
  30018. thehinitialarabic: 0xFE9B,
  30019. thehmedialarabic: 0xFE9C,
  30020. thereexists: 0x2203,
  30021. therefore: 0x2234,
  30022. theta: 0x03B8,
  30023. theta1: 0x03D1,
  30024. thetasymbolgreek: 0x03D1,
  30025. thieuthacirclekorean: 0x3279,
  30026. thieuthaparenkorean: 0x3219,
  30027. thieuthcirclekorean: 0x326B,
  30028. thieuthkorean: 0x314C,
  30029. thieuthparenkorean: 0x320B,
  30030. thirteencircle: 0x246C,
  30031. thirteenparen: 0x2480,
  30032. thirteenperiod: 0x2494,
  30033. thonangmonthothai: 0x0E11,
  30034. thook: 0x01AD,
  30035. thophuthaothai: 0x0E12,
  30036. thorn: 0x00FE,
  30037. thothahanthai: 0x0E17,
  30038. thothanthai: 0x0E10,
  30039. thothongthai: 0x0E18,
  30040. thothungthai: 0x0E16,
  30041. thousandcyrillic: 0x0482,
  30042. thousandsseparatorarabic: 0x066C,
  30043. thousandsseparatorpersian: 0x066C,
  30044. three: 0x0033,
  30045. threearabic: 0x0663,
  30046. threebengali: 0x09E9,
  30047. threecircle: 0x2462,
  30048. threecircleinversesansserif: 0x278C,
  30049. threedeva: 0x0969,
  30050. threeeighths: 0x215C,
  30051. threegujarati: 0x0AE9,
  30052. threegurmukhi: 0x0A69,
  30053. threehackarabic: 0x0663,
  30054. threehangzhou: 0x3023,
  30055. threeideographicparen: 0x3222,
  30056. threeinferior: 0x2083,
  30057. threemonospace: 0xFF13,
  30058. threenumeratorbengali: 0x09F6,
  30059. threeoldstyle: 0xF733,
  30060. threeparen: 0x2476,
  30061. threeperiod: 0x248A,
  30062. threepersian: 0x06F3,
  30063. threequarters: 0x00BE,
  30064. threequartersemdash: 0xF6DE,
  30065. threeroman: 0x2172,
  30066. threesuperior: 0x00B3,
  30067. threethai: 0x0E53,
  30068. thzsquare: 0x3394,
  30069. tihiragana: 0x3061,
  30070. tikatakana: 0x30C1,
  30071. tikatakanahalfwidth: 0xFF81,
  30072. tikeutacirclekorean: 0x3270,
  30073. tikeutaparenkorean: 0x3210,
  30074. tikeutcirclekorean: 0x3262,
  30075. tikeutkorean: 0x3137,
  30076. tikeutparenkorean: 0x3202,
  30077. tilde: 0x02DC,
  30078. tildebelowcmb: 0x0330,
  30079. tildecmb: 0x0303,
  30080. tildecomb: 0x0303,
  30081. tildedoublecmb: 0x0360,
  30082. tildeoperator: 0x223C,
  30083. tildeoverlaycmb: 0x0334,
  30084. tildeverticalcmb: 0x033E,
  30085. timescircle: 0x2297,
  30086. tipehahebrew: 0x0596,
  30087. tipehalefthebrew: 0x0596,
  30088. tippigurmukhi: 0x0A70,
  30089. titlocyrilliccmb: 0x0483,
  30090. tiwnarmenian: 0x057F,
  30091. tlinebelow: 0x1E6F,
  30092. tmonospace: 0xFF54,
  30093. toarmenian: 0x0569,
  30094. tohiragana: 0x3068,
  30095. tokatakana: 0x30C8,
  30096. tokatakanahalfwidth: 0xFF84,
  30097. tonebarextrahighmod: 0x02E5,
  30098. tonebarextralowmod: 0x02E9,
  30099. tonebarhighmod: 0x02E6,
  30100. tonebarlowmod: 0x02E8,
  30101. tonebarmidmod: 0x02E7,
  30102. tonefive: 0x01BD,
  30103. tonesix: 0x0185,
  30104. tonetwo: 0x01A8,
  30105. tonos: 0x0384,
  30106. tonsquare: 0x3327,
  30107. topatakthai: 0x0E0F,
  30108. tortoiseshellbracketleft: 0x3014,
  30109. tortoiseshellbracketleftsmall: 0xFE5D,
  30110. tortoiseshellbracketleftvertical: 0xFE39,
  30111. tortoiseshellbracketright: 0x3015,
  30112. tortoiseshellbracketrightsmall: 0xFE5E,
  30113. tortoiseshellbracketrightvertical: 0xFE3A,
  30114. totaothai: 0x0E15,
  30115. tpalatalhook: 0x01AB,
  30116. tparen: 0x24AF,
  30117. trademark: 0x2122,
  30118. trademarksans: 0xF8EA,
  30119. trademarkserif: 0xF6DB,
  30120. tretroflexhook: 0x0288,
  30121. triagdn: 0x25BC,
  30122. triaglf: 0x25C4,
  30123. triagrt: 0x25BA,
  30124. triagup: 0x25B2,
  30125. ts: 0x02A6,
  30126. tsadi: 0x05E6,
  30127. tsadidagesh: 0xFB46,
  30128. tsadidageshhebrew: 0xFB46,
  30129. tsadihebrew: 0x05E6,
  30130. tsecyrillic: 0x0446,
  30131. tsere: 0x05B5,
  30132. tsere12: 0x05B5,
  30133. tsere1e: 0x05B5,
  30134. tsere2b: 0x05B5,
  30135. tserehebrew: 0x05B5,
  30136. tserenarrowhebrew: 0x05B5,
  30137. tserequarterhebrew: 0x05B5,
  30138. tserewidehebrew: 0x05B5,
  30139. tshecyrillic: 0x045B,
  30140. tsuperior: 0xF6F3,
  30141. ttabengali: 0x099F,
  30142. ttadeva: 0x091F,
  30143. ttagujarati: 0x0A9F,
  30144. ttagurmukhi: 0x0A1F,
  30145. tteharabic: 0x0679,
  30146. ttehfinalarabic: 0xFB67,
  30147. ttehinitialarabic: 0xFB68,
  30148. ttehmedialarabic: 0xFB69,
  30149. tthabengali: 0x09A0,
  30150. tthadeva: 0x0920,
  30151. tthagujarati: 0x0AA0,
  30152. tthagurmukhi: 0x0A20,
  30153. tturned: 0x0287,
  30154. tuhiragana: 0x3064,
  30155. tukatakana: 0x30C4,
  30156. tukatakanahalfwidth: 0xFF82,
  30157. tusmallhiragana: 0x3063,
  30158. tusmallkatakana: 0x30C3,
  30159. tusmallkatakanahalfwidth: 0xFF6F,
  30160. twelvecircle: 0x246B,
  30161. twelveparen: 0x247F,
  30162. twelveperiod: 0x2493,
  30163. twelveroman: 0x217B,
  30164. twentycircle: 0x2473,
  30165. twentyhangzhou: 0x5344,
  30166. twentyparen: 0x2487,
  30167. twentyperiod: 0x249B,
  30168. two: 0x0032,
  30169. twoarabic: 0x0662,
  30170. twobengali: 0x09E8,
  30171. twocircle: 0x2461,
  30172. twocircleinversesansserif: 0x278B,
  30173. twodeva: 0x0968,
  30174. twodotenleader: 0x2025,
  30175. twodotleader: 0x2025,
  30176. twodotleadervertical: 0xFE30,
  30177. twogujarati: 0x0AE8,
  30178. twogurmukhi: 0x0A68,
  30179. twohackarabic: 0x0662,
  30180. twohangzhou: 0x3022,
  30181. twoideographicparen: 0x3221,
  30182. twoinferior: 0x2082,
  30183. twomonospace: 0xFF12,
  30184. twonumeratorbengali: 0x09F5,
  30185. twooldstyle: 0xF732,
  30186. twoparen: 0x2475,
  30187. twoperiod: 0x2489,
  30188. twopersian: 0x06F2,
  30189. tworoman: 0x2171,
  30190. twostroke: 0x01BB,
  30191. twosuperior: 0x00B2,
  30192. twothai: 0x0E52,
  30193. twothirds: 0x2154,
  30194. u: 0x0075,
  30195. uacute: 0x00FA,
  30196. ubar: 0x0289,
  30197. ubengali: 0x0989,
  30198. ubopomofo: 0x3128,
  30199. ubreve: 0x016D,
  30200. ucaron: 0x01D4,
  30201. ucircle: 0x24E4,
  30202. ucircumflex: 0x00FB,
  30203. ucircumflexbelow: 0x1E77,
  30204. ucyrillic: 0x0443,
  30205. udattadeva: 0x0951,
  30206. udblacute: 0x0171,
  30207. udblgrave: 0x0215,
  30208. udeva: 0x0909,
  30209. udieresis: 0x00FC,
  30210. udieresisacute: 0x01D8,
  30211. udieresisbelow: 0x1E73,
  30212. udieresiscaron: 0x01DA,
  30213. udieresiscyrillic: 0x04F1,
  30214. udieresisgrave: 0x01DC,
  30215. udieresismacron: 0x01D6,
  30216. udotbelow: 0x1EE5,
  30217. ugrave: 0x00F9,
  30218. ugujarati: 0x0A89,
  30219. ugurmukhi: 0x0A09,
  30220. uhiragana: 0x3046,
  30221. uhookabove: 0x1EE7,
  30222. uhorn: 0x01B0,
  30223. uhornacute: 0x1EE9,
  30224. uhorndotbelow: 0x1EF1,
  30225. uhorngrave: 0x1EEB,
  30226. uhornhookabove: 0x1EED,
  30227. uhorntilde: 0x1EEF,
  30228. uhungarumlaut: 0x0171,
  30229. uhungarumlautcyrillic: 0x04F3,
  30230. uinvertedbreve: 0x0217,
  30231. ukatakana: 0x30A6,
  30232. ukatakanahalfwidth: 0xFF73,
  30233. ukcyrillic: 0x0479,
  30234. ukorean: 0x315C,
  30235. umacron: 0x016B,
  30236. umacroncyrillic: 0x04EF,
  30237. umacrondieresis: 0x1E7B,
  30238. umatragurmukhi: 0x0A41,
  30239. umonospace: 0xFF55,
  30240. underscore: 0x005F,
  30241. underscoredbl: 0x2017,
  30242. underscoremonospace: 0xFF3F,
  30243. underscorevertical: 0xFE33,
  30244. underscorewavy: 0xFE4F,
  30245. union: 0x222A,
  30246. universal: 0x2200,
  30247. uogonek: 0x0173,
  30248. uparen: 0x24B0,
  30249. upblock: 0x2580,
  30250. upperdothebrew: 0x05C4,
  30251. upsilon: 0x03C5,
  30252. upsilondieresis: 0x03CB,
  30253. upsilondieresistonos: 0x03B0,
  30254. upsilonlatin: 0x028A,
  30255. upsilontonos: 0x03CD,
  30256. uptackbelowcmb: 0x031D,
  30257. uptackmod: 0x02D4,
  30258. uragurmukhi: 0x0A73,
  30259. uring: 0x016F,
  30260. ushortcyrillic: 0x045E,
  30261. usmallhiragana: 0x3045,
  30262. usmallkatakana: 0x30A5,
  30263. usmallkatakanahalfwidth: 0xFF69,
  30264. ustraightcyrillic: 0x04AF,
  30265. ustraightstrokecyrillic: 0x04B1,
  30266. utilde: 0x0169,
  30267. utildeacute: 0x1E79,
  30268. utildebelow: 0x1E75,
  30269. uubengali: 0x098A,
  30270. uudeva: 0x090A,
  30271. uugujarati: 0x0A8A,
  30272. uugurmukhi: 0x0A0A,
  30273. uumatragurmukhi: 0x0A42,
  30274. uuvowelsignbengali: 0x09C2,
  30275. uuvowelsigndeva: 0x0942,
  30276. uuvowelsigngujarati: 0x0AC2,
  30277. uvowelsignbengali: 0x09C1,
  30278. uvowelsigndeva: 0x0941,
  30279. uvowelsigngujarati: 0x0AC1,
  30280. v: 0x0076,
  30281. vadeva: 0x0935,
  30282. vagujarati: 0x0AB5,
  30283. vagurmukhi: 0x0A35,
  30284. vakatakana: 0x30F7,
  30285. vav: 0x05D5,
  30286. vavdagesh: 0xFB35,
  30287. vavdagesh65: 0xFB35,
  30288. vavdageshhebrew: 0xFB35,
  30289. vavhebrew: 0x05D5,
  30290. vavholam: 0xFB4B,
  30291. vavholamhebrew: 0xFB4B,
  30292. vavvavhebrew: 0x05F0,
  30293. vavyodhebrew: 0x05F1,
  30294. vcircle: 0x24E5,
  30295. vdotbelow: 0x1E7F,
  30296. vecyrillic: 0x0432,
  30297. veharabic: 0x06A4,
  30298. vehfinalarabic: 0xFB6B,
  30299. vehinitialarabic: 0xFB6C,
  30300. vehmedialarabic: 0xFB6D,
  30301. vekatakana: 0x30F9,
  30302. venus: 0x2640,
  30303. verticalbar: 0x007C,
  30304. verticallineabovecmb: 0x030D,
  30305. verticallinebelowcmb: 0x0329,
  30306. verticallinelowmod: 0x02CC,
  30307. verticallinemod: 0x02C8,
  30308. vewarmenian: 0x057E,
  30309. vhook: 0x028B,
  30310. vikatakana: 0x30F8,
  30311. viramabengali: 0x09CD,
  30312. viramadeva: 0x094D,
  30313. viramagujarati: 0x0ACD,
  30314. visargabengali: 0x0983,
  30315. visargadeva: 0x0903,
  30316. visargagujarati: 0x0A83,
  30317. vmonospace: 0xFF56,
  30318. voarmenian: 0x0578,
  30319. voicediterationhiragana: 0x309E,
  30320. voicediterationkatakana: 0x30FE,
  30321. voicedmarkkana: 0x309B,
  30322. voicedmarkkanahalfwidth: 0xFF9E,
  30323. vokatakana: 0x30FA,
  30324. vparen: 0x24B1,
  30325. vtilde: 0x1E7D,
  30326. vturned: 0x028C,
  30327. vuhiragana: 0x3094,
  30328. vukatakana: 0x30F4,
  30329. w: 0x0077,
  30330. wacute: 0x1E83,
  30331. waekorean: 0x3159,
  30332. wahiragana: 0x308F,
  30333. wakatakana: 0x30EF,
  30334. wakatakanahalfwidth: 0xFF9C,
  30335. wakorean: 0x3158,
  30336. wasmallhiragana: 0x308E,
  30337. wasmallkatakana: 0x30EE,
  30338. wattosquare: 0x3357,
  30339. wavedash: 0x301C,
  30340. wavyunderscorevertical: 0xFE34,
  30341. wawarabic: 0x0648,
  30342. wawfinalarabic: 0xFEEE,
  30343. wawhamzaabovearabic: 0x0624,
  30344. wawhamzaabovefinalarabic: 0xFE86,
  30345. wbsquare: 0x33DD,
  30346. wcircle: 0x24E6,
  30347. wcircumflex: 0x0175,
  30348. wdieresis: 0x1E85,
  30349. wdotaccent: 0x1E87,
  30350. wdotbelow: 0x1E89,
  30351. wehiragana: 0x3091,
  30352. weierstrass: 0x2118,
  30353. wekatakana: 0x30F1,
  30354. wekorean: 0x315E,
  30355. weokorean: 0x315D,
  30356. wgrave: 0x1E81,
  30357. whitebullet: 0x25E6,
  30358. whitecircle: 0x25CB,
  30359. whitecircleinverse: 0x25D9,
  30360. whitecornerbracketleft: 0x300E,
  30361. whitecornerbracketleftvertical: 0xFE43,
  30362. whitecornerbracketright: 0x300F,
  30363. whitecornerbracketrightvertical: 0xFE44,
  30364. whitediamond: 0x25C7,
  30365. whitediamondcontainingblacksmalldiamond: 0x25C8,
  30366. whitedownpointingsmalltriangle: 0x25BF,
  30367. whitedownpointingtriangle: 0x25BD,
  30368. whiteleftpointingsmalltriangle: 0x25C3,
  30369. whiteleftpointingtriangle: 0x25C1,
  30370. whitelenticularbracketleft: 0x3016,
  30371. whitelenticularbracketright: 0x3017,
  30372. whiterightpointingsmalltriangle: 0x25B9,
  30373. whiterightpointingtriangle: 0x25B7,
  30374. whitesmallsquare: 0x25AB,
  30375. whitesmilingface: 0x263A,
  30376. whitesquare: 0x25A1,
  30377. whitestar: 0x2606,
  30378. whitetelephone: 0x260F,
  30379. whitetortoiseshellbracketleft: 0x3018,
  30380. whitetortoiseshellbracketright: 0x3019,
  30381. whiteuppointingsmalltriangle: 0x25B5,
  30382. whiteuppointingtriangle: 0x25B3,
  30383. wihiragana: 0x3090,
  30384. wikatakana: 0x30F0,
  30385. wikorean: 0x315F,
  30386. wmonospace: 0xFF57,
  30387. wohiragana: 0x3092,
  30388. wokatakana: 0x30F2,
  30389. wokatakanahalfwidth: 0xFF66,
  30390. won: 0x20A9,
  30391. wonmonospace: 0xFFE6,
  30392. wowaenthai: 0x0E27,
  30393. wparen: 0x24B2,
  30394. wring: 0x1E98,
  30395. wsuperior: 0x02B7,
  30396. wturned: 0x028D,
  30397. wynn: 0x01BF,
  30398. x: 0x0078,
  30399. xabovecmb: 0x033D,
  30400. xbopomofo: 0x3112,
  30401. xcircle: 0x24E7,
  30402. xdieresis: 0x1E8D,
  30403. xdotaccent: 0x1E8B,
  30404. xeharmenian: 0x056D,
  30405. xi: 0x03BE,
  30406. xmonospace: 0xFF58,
  30407. xparen: 0x24B3,
  30408. xsuperior: 0x02E3,
  30409. y: 0x0079,
  30410. yaadosquare: 0x334E,
  30411. yabengali: 0x09AF,
  30412. yacute: 0x00FD,
  30413. yadeva: 0x092F,
  30414. yaekorean: 0x3152,
  30415. yagujarati: 0x0AAF,
  30416. yagurmukhi: 0x0A2F,
  30417. yahiragana: 0x3084,
  30418. yakatakana: 0x30E4,
  30419. yakatakanahalfwidth: 0xFF94,
  30420. yakorean: 0x3151,
  30421. yamakkanthai: 0x0E4E,
  30422. yasmallhiragana: 0x3083,
  30423. yasmallkatakana: 0x30E3,
  30424. yasmallkatakanahalfwidth: 0xFF6C,
  30425. yatcyrillic: 0x0463,
  30426. ycircle: 0x24E8,
  30427. ycircumflex: 0x0177,
  30428. ydieresis: 0x00FF,
  30429. ydotaccent: 0x1E8F,
  30430. ydotbelow: 0x1EF5,
  30431. yeharabic: 0x064A,
  30432. yehbarreearabic: 0x06D2,
  30433. yehbarreefinalarabic: 0xFBAF,
  30434. yehfinalarabic: 0xFEF2,
  30435. yehhamzaabovearabic: 0x0626,
  30436. yehhamzaabovefinalarabic: 0xFE8A,
  30437. yehhamzaaboveinitialarabic: 0xFE8B,
  30438. yehhamzaabovemedialarabic: 0xFE8C,
  30439. yehinitialarabic: 0xFEF3,
  30440. yehmedialarabic: 0xFEF4,
  30441. yehmeeminitialarabic: 0xFCDD,
  30442. yehmeemisolatedarabic: 0xFC58,
  30443. yehnoonfinalarabic: 0xFC94,
  30444. yehthreedotsbelowarabic: 0x06D1,
  30445. yekorean: 0x3156,
  30446. yen: 0x00A5,
  30447. yenmonospace: 0xFFE5,
  30448. yeokorean: 0x3155,
  30449. yeorinhieuhkorean: 0x3186,
  30450. yerahbenyomohebrew: 0x05AA,
  30451. yerahbenyomolefthebrew: 0x05AA,
  30452. yericyrillic: 0x044B,
  30453. yerudieresiscyrillic: 0x04F9,
  30454. yesieungkorean: 0x3181,
  30455. yesieungpansioskorean: 0x3183,
  30456. yesieungsioskorean: 0x3182,
  30457. yetivhebrew: 0x059A,
  30458. ygrave: 0x1EF3,
  30459. yhook: 0x01B4,
  30460. yhookabove: 0x1EF7,
  30461. yiarmenian: 0x0575,
  30462. yicyrillic: 0x0457,
  30463. yikorean: 0x3162,
  30464. yinyang: 0x262F,
  30465. yiwnarmenian: 0x0582,
  30466. ymonospace: 0xFF59,
  30467. yod: 0x05D9,
  30468. yoddagesh: 0xFB39,
  30469. yoddageshhebrew: 0xFB39,
  30470. yodhebrew: 0x05D9,
  30471. yodyodhebrew: 0x05F2,
  30472. yodyodpatahhebrew: 0xFB1F,
  30473. yohiragana: 0x3088,
  30474. yoikorean: 0x3189,
  30475. yokatakana: 0x30E8,
  30476. yokatakanahalfwidth: 0xFF96,
  30477. yokorean: 0x315B,
  30478. yosmallhiragana: 0x3087,
  30479. yosmallkatakana: 0x30E7,
  30480. yosmallkatakanahalfwidth: 0xFF6E,
  30481. yotgreek: 0x03F3,
  30482. yoyaekorean: 0x3188,
  30483. yoyakorean: 0x3187,
  30484. yoyakthai: 0x0E22,
  30485. yoyingthai: 0x0E0D,
  30486. yparen: 0x24B4,
  30487. ypogegrammeni: 0x037A,
  30488. ypogegrammenigreekcmb: 0x0345,
  30489. yr: 0x01A6,
  30490. yring: 0x1E99,
  30491. ysuperior: 0x02B8,
  30492. ytilde: 0x1EF9,
  30493. yturned: 0x028E,
  30494. yuhiragana: 0x3086,
  30495. yuikorean: 0x318C,
  30496. yukatakana: 0x30E6,
  30497. yukatakanahalfwidth: 0xFF95,
  30498. yukorean: 0x3160,
  30499. yusbigcyrillic: 0x046B,
  30500. yusbigiotifiedcyrillic: 0x046D,
  30501. yuslittlecyrillic: 0x0467,
  30502. yuslittleiotifiedcyrillic: 0x0469,
  30503. yusmallhiragana: 0x3085,
  30504. yusmallkatakana: 0x30E5,
  30505. yusmallkatakanahalfwidth: 0xFF6D,
  30506. yuyekorean: 0x318B,
  30507. yuyeokorean: 0x318A,
  30508. yyabengali: 0x09DF,
  30509. yyadeva: 0x095F,
  30510. z: 0x007A,
  30511. zaarmenian: 0x0566,
  30512. zacute: 0x017A,
  30513. zadeva: 0x095B,
  30514. zagurmukhi: 0x0A5B,
  30515. zaharabic: 0x0638,
  30516. zahfinalarabic: 0xFEC6,
  30517. zahinitialarabic: 0xFEC7,
  30518. zahiragana: 0x3056,
  30519. zahmedialarabic: 0xFEC8,
  30520. zainarabic: 0x0632,
  30521. zainfinalarabic: 0xFEB0,
  30522. zakatakana: 0x30B6,
  30523. zaqefgadolhebrew: 0x0595,
  30524. zaqefqatanhebrew: 0x0594,
  30525. zarqahebrew: 0x0598,
  30526. zayin: 0x05D6,
  30527. zayindagesh: 0xFB36,
  30528. zayindageshhebrew: 0xFB36,
  30529. zayinhebrew: 0x05D6,
  30530. zbopomofo: 0x3117,
  30531. zcaron: 0x017E,
  30532. zcircle: 0x24E9,
  30533. zcircumflex: 0x1E91,
  30534. zcurl: 0x0291,
  30535. zdot: 0x017C,
  30536. zdotaccent: 0x017C,
  30537. zdotbelow: 0x1E93,
  30538. zecyrillic: 0x0437,
  30539. zedescendercyrillic: 0x0499,
  30540. zedieresiscyrillic: 0x04DF,
  30541. zehiragana: 0x305C,
  30542. zekatakana: 0x30BC,
  30543. zero: 0x0030,
  30544. zeroarabic: 0x0660,
  30545. zerobengali: 0x09E6,
  30546. zerodeva: 0x0966,
  30547. zerogujarati: 0x0AE6,
  30548. zerogurmukhi: 0x0A66,
  30549. zerohackarabic: 0x0660,
  30550. zeroinferior: 0x2080,
  30551. zeromonospace: 0xFF10,
  30552. zerooldstyle: 0xF730,
  30553. zeropersian: 0x06F0,
  30554. zerosuperior: 0x2070,
  30555. zerothai: 0x0E50,
  30556. zerowidthjoiner: 0xFEFF,
  30557. zerowidthnonjoiner: 0x200C,
  30558. zerowidthspace: 0x200B,
  30559. zeta: 0x03B6,
  30560. zhbopomofo: 0x3113,
  30561. zhearmenian: 0x056A,
  30562. zhebrevecyrillic: 0x04C2,
  30563. zhecyrillic: 0x0436,
  30564. zhedescendercyrillic: 0x0497,
  30565. zhedieresiscyrillic: 0x04DD,
  30566. zihiragana: 0x3058,
  30567. zikatakana: 0x30B8,
  30568. zinorhebrew: 0x05AE,
  30569. zlinebelow: 0x1E95,
  30570. zmonospace: 0xFF5A,
  30571. zohiragana: 0x305E,
  30572. zokatakana: 0x30BE,
  30573. zparen: 0x24B5,
  30574. zretroflexhook: 0x0290,
  30575. zstroke: 0x01B6,
  30576. zuhiragana: 0x305A,
  30577. zukatakana: 0x30BA,
  30578. '.notdef': 0x0000
  30579. };
  30580. var DingbatsGlyphsUnicode = {
  30581. space: 0x0020,
  30582. a1: 0x2701,
  30583. a2: 0x2702,
  30584. a202: 0x2703,
  30585. a3: 0x2704,
  30586. a4: 0x260E,
  30587. a5: 0x2706,
  30588. a119: 0x2707,
  30589. a118: 0x2708,
  30590. a117: 0x2709,
  30591. a11: 0x261B,
  30592. a12: 0x261E,
  30593. a13: 0x270C,
  30594. a14: 0x270D,
  30595. a15: 0x270E,
  30596. a16: 0x270F,
  30597. a105: 0x2710,
  30598. a17: 0x2711,
  30599. a18: 0x2712,
  30600. a19: 0x2713,
  30601. a20: 0x2714,
  30602. a21: 0x2715,
  30603. a22: 0x2716,
  30604. a23: 0x2717,
  30605. a24: 0x2718,
  30606. a25: 0x2719,
  30607. a26: 0x271A,
  30608. a27: 0x271B,
  30609. a28: 0x271C,
  30610. a6: 0x271D,
  30611. a7: 0x271E,
  30612. a8: 0x271F,
  30613. a9: 0x2720,
  30614. a10: 0x2721,
  30615. a29: 0x2722,
  30616. a30: 0x2723,
  30617. a31: 0x2724,
  30618. a32: 0x2725,
  30619. a33: 0x2726,
  30620. a34: 0x2727,
  30621. a35: 0x2605,
  30622. a36: 0x2729,
  30623. a37: 0x272A,
  30624. a38: 0x272B,
  30625. a39: 0x272C,
  30626. a40: 0x272D,
  30627. a41: 0x272E,
  30628. a42: 0x272F,
  30629. a43: 0x2730,
  30630. a44: 0x2731,
  30631. a45: 0x2732,
  30632. a46: 0x2733,
  30633. a47: 0x2734,
  30634. a48: 0x2735,
  30635. a49: 0x2736,
  30636. a50: 0x2737,
  30637. a51: 0x2738,
  30638. a52: 0x2739,
  30639. a53: 0x273A,
  30640. a54: 0x273B,
  30641. a55: 0x273C,
  30642. a56: 0x273D,
  30643. a57: 0x273E,
  30644. a58: 0x273F,
  30645. a59: 0x2740,
  30646. a60: 0x2741,
  30647. a61: 0x2742,
  30648. a62: 0x2743,
  30649. a63: 0x2744,
  30650. a64: 0x2745,
  30651. a65: 0x2746,
  30652. a66: 0x2747,
  30653. a67: 0x2748,
  30654. a68: 0x2749,
  30655. a69: 0x274A,
  30656. a70: 0x274B,
  30657. a71: 0x25CF,
  30658. a72: 0x274D,
  30659. a73: 0x25A0,
  30660. a74: 0x274F,
  30661. a203: 0x2750,
  30662. a75: 0x2751,
  30663. a204: 0x2752,
  30664. a76: 0x25B2,
  30665. a77: 0x25BC,
  30666. a78: 0x25C6,
  30667. a79: 0x2756,
  30668. a81: 0x25D7,
  30669. a82: 0x2758,
  30670. a83: 0x2759,
  30671. a84: 0x275A,
  30672. a97: 0x275B,
  30673. a98: 0x275C,
  30674. a99: 0x275D,
  30675. a100: 0x275E,
  30676. a101: 0x2761,
  30677. a102: 0x2762,
  30678. a103: 0x2763,
  30679. a104: 0x2764,
  30680. a106: 0x2765,
  30681. a107: 0x2766,
  30682. a108: 0x2767,
  30683. a112: 0x2663,
  30684. a111: 0x2666,
  30685. a110: 0x2665,
  30686. a109: 0x2660,
  30687. a120: 0x2460,
  30688. a121: 0x2461,
  30689. a122: 0x2462,
  30690. a123: 0x2463,
  30691. a124: 0x2464,
  30692. a125: 0x2465,
  30693. a126: 0x2466,
  30694. a127: 0x2467,
  30695. a128: 0x2468,
  30696. a129: 0x2469,
  30697. a130: 0x2776,
  30698. a131: 0x2777,
  30699. a132: 0x2778,
  30700. a133: 0x2779,
  30701. a134: 0x277A,
  30702. a135: 0x277B,
  30703. a136: 0x277C,
  30704. a137: 0x277D,
  30705. a138: 0x277E,
  30706. a139: 0x277F,
  30707. a140: 0x2780,
  30708. a141: 0x2781,
  30709. a142: 0x2782,
  30710. a143: 0x2783,
  30711. a144: 0x2784,
  30712. a145: 0x2785,
  30713. a146: 0x2786,
  30714. a147: 0x2787,
  30715. a148: 0x2788,
  30716. a149: 0x2789,
  30717. a150: 0x278A,
  30718. a151: 0x278B,
  30719. a152: 0x278C,
  30720. a153: 0x278D,
  30721. a154: 0x278E,
  30722. a155: 0x278F,
  30723. a156: 0x2790,
  30724. a157: 0x2791,
  30725. a158: 0x2792,
  30726. a159: 0x2793,
  30727. a160: 0x2794,
  30728. a161: 0x2192,
  30729. a163: 0x2194,
  30730. a164: 0x2195,
  30731. a196: 0x2798,
  30732. a165: 0x2799,
  30733. a192: 0x279A,
  30734. a166: 0x279B,
  30735. a167: 0x279C,
  30736. a168: 0x279D,
  30737. a169: 0x279E,
  30738. a170: 0x279F,
  30739. a171: 0x27A0,
  30740. a172: 0x27A1,
  30741. a173: 0x27A2,
  30742. a162: 0x27A3,
  30743. a174: 0x27A4,
  30744. a175: 0x27A5,
  30745. a176: 0x27A6,
  30746. a177: 0x27A7,
  30747. a178: 0x27A8,
  30748. a179: 0x27A9,
  30749. a193: 0x27AA,
  30750. a180: 0x27AB,
  30751. a199: 0x27AC,
  30752. a181: 0x27AD,
  30753. a200: 0x27AE,
  30754. a182: 0x27AF,
  30755. a201: 0x27B1,
  30756. a183: 0x27B2,
  30757. a184: 0x27B3,
  30758. a197: 0x27B4,
  30759. a185: 0x27B5,
  30760. a194: 0x27B6,
  30761. a198: 0x27B7,
  30762. a186: 0x27B8,
  30763. a195: 0x27B9,
  30764. a187: 0x27BA,
  30765. a188: 0x27BB,
  30766. a189: 0x27BC,
  30767. a190: 0x27BD,
  30768. a191: 0x27BE,
  30769. a89: 0x2768, // 0xF8D7
  30770. a90: 0x2769, // 0xF8D8
  30771. a93: 0x276A, // 0xF8D9
  30772. a94: 0x276B, // 0xF8DA
  30773. a91: 0x276C, // 0xF8DB
  30774. a92: 0x276D, // 0xF8DC
  30775. a205: 0x276E, // 0xF8DD
  30776. a85: 0x276F, // 0xF8DE
  30777. a206: 0x2770, // 0xF8DF
  30778. a86: 0x2771, // 0xF8E0
  30779. a87: 0x2772, // 0xF8E1
  30780. a88: 0x2773, // 0xF8E2
  30781. a95: 0x2774, // 0xF8E3
  30782. a96: 0x2775, // 0xF8E4
  30783. '.notdef': 0x0000
  30784. };
  30785. var PDFImage = (function PDFImageClosure() {
  30786. /**
  30787. * Decode the image in the main thread if it supported. Resovles the promise
  30788. * when the image data is ready.
  30789. */
  30790. function handleImageData(handler, xref, res, image) {
  30791. if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {
  30792. // For natively supported jpegs send them to the main thread for decoding.
  30793. var dict = image.dict;
  30794. var colorSpace = dict.get('ColorSpace', 'CS');
  30795. colorSpace = ColorSpace.parse(colorSpace, xref, res);
  30796. var numComps = colorSpace.numComps;
  30797. var decodePromise = handler.sendWithPromise('JpegDecode',
  30798. [image.getIR(), numComps]);
  30799. return decodePromise.then(function (message) {
  30800. var data = message.data;
  30801. return new Stream(data, 0, data.length, image.dict);
  30802. });
  30803. } else {
  30804. return Promise.resolve(image);
  30805. }
  30806. }
  30807. /**
  30808. * Decode and clamp a value. The formula is different from the spec because we
  30809. * don't decode to float range [0,1], we decode it in the [0,max] range.
  30810. */
  30811. function decodeAndClamp(value, addend, coefficient, max) {
  30812. value = addend + value * coefficient;
  30813. // Clamp the value to the range
  30814. return (value < 0 ? 0 : (value > max ? max : value));
  30815. }
  30816. function PDFImage(xref, res, image, inline, smask, mask, isMask) {
  30817. this.image = image;
  30818. var dict = image.dict;
  30819. if (dict.has('Filter')) {
  30820. var filter = dict.get('Filter').name;
  30821. if (filter === 'JPXDecode') {
  30822. var jpxImage = new JpxImage();
  30823. jpxImage.parseImageProperties(image.stream);
  30824. image.stream.reset();
  30825. image.bitsPerComponent = jpxImage.bitsPerComponent;
  30826. image.numComps = jpxImage.componentsCount;
  30827. } else if (filter === 'JBIG2Decode') {
  30828. image.bitsPerComponent = 1;
  30829. image.numComps = 1;
  30830. }
  30831. }
  30832. // TODO cache rendered images?
  30833. this.width = dict.get('Width', 'W');
  30834. this.height = dict.get('Height', 'H');
  30835. if (this.width < 1 || this.height < 1) {
  30836. error('Invalid image width: ' + this.width + ' or height: ' +
  30837. this.height);
  30838. }
  30839. this.interpolate = dict.get('Interpolate', 'I') || false;
  30840. this.imageMask = dict.get('ImageMask', 'IM') || false;
  30841. this.matte = dict.get('Matte') || false;
  30842. var bitsPerComponent = image.bitsPerComponent;
  30843. if (!bitsPerComponent) {
  30844. bitsPerComponent = dict.get('BitsPerComponent', 'BPC');
  30845. if (!bitsPerComponent) {
  30846. if (this.imageMask) {
  30847. bitsPerComponent = 1;
  30848. } else {
  30849. error('Bits per component missing in image: ' + this.imageMask);
  30850. }
  30851. }
  30852. }
  30853. this.bpc = bitsPerComponent;
  30854. if (!this.imageMask) {
  30855. var colorSpace = dict.get('ColorSpace', 'CS');
  30856. if (!colorSpace) {
  30857. info('JPX images (which do not require color spaces)');
  30858. switch (image.numComps) {
  30859. case 1:
  30860. colorSpace = Name.get('DeviceGray');
  30861. break;
  30862. case 3:
  30863. colorSpace = Name.get('DeviceRGB');
  30864. break;
  30865. case 4:
  30866. colorSpace = Name.get('DeviceCMYK');
  30867. break;
  30868. default:
  30869. error('JPX images with ' + this.numComps +
  30870. ' color components not supported.');
  30871. }
  30872. }
  30873. this.colorSpace = ColorSpace.parse(colorSpace, xref, res);
  30874. this.numComps = this.colorSpace.numComps;
  30875. }
  30876. this.decode = dict.get('Decode', 'D');
  30877. this.needsDecode = false;
  30878. if (this.decode &&
  30879. ((this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode)) ||
  30880. (isMask && !ColorSpace.isDefaultDecode(this.decode, 1)))) {
  30881. this.needsDecode = true;
  30882. // Do some preprocessing to avoid more math.
  30883. var max = (1 << bitsPerComponent) - 1;
  30884. this.decodeCoefficients = [];
  30885. this.decodeAddends = [];
  30886. for (var i = 0, j = 0; i < this.decode.length; i += 2, ++j) {
  30887. var dmin = this.decode[i];
  30888. var dmax = this.decode[i + 1];
  30889. this.decodeCoefficients[j] = dmax - dmin;
  30890. this.decodeAddends[j] = max * dmin;
  30891. }
  30892. }
  30893. if (smask) {
  30894. this.smask = new PDFImage(xref, res, smask, false);
  30895. } else if (mask) {
  30896. if (isStream(mask)) {
  30897. this.mask = new PDFImage(xref, res, mask, false, null, null, true);
  30898. } else {
  30899. // Color key mask (just an array).
  30900. this.mask = mask;
  30901. }
  30902. }
  30903. }
  30904. /**
  30905. * Handles processing of image data and returns the Promise that is resolved
  30906. * with a PDFImage when the image is ready to be used.
  30907. */
  30908. PDFImage.buildImage = function PDFImage_buildImage(handler, xref,
  30909. res, image, inline) {
  30910. var imagePromise = handleImageData(handler, xref, res, image);
  30911. var smaskPromise;
  30912. var maskPromise;
  30913. var smask = image.dict.get('SMask');
  30914. var mask = image.dict.get('Mask');
  30915. if (smask) {
  30916. smaskPromise = handleImageData(handler, xref, res, smask);
  30917. maskPromise = Promise.resolve(null);
  30918. } else {
  30919. smaskPromise = Promise.resolve(null);
  30920. if (mask) {
  30921. if (isStream(mask)) {
  30922. maskPromise = handleImageData(handler, xref, res, mask);
  30923. } else if (isArray(mask)) {
  30924. maskPromise = Promise.resolve(mask);
  30925. } else {
  30926. warn('Unsupported mask format.');
  30927. maskPromise = Promise.resolve(null);
  30928. }
  30929. } else {
  30930. maskPromise = Promise.resolve(null);
  30931. }
  30932. }
  30933. return Promise.all([imagePromise, smaskPromise, maskPromise]).then(
  30934. function(results) {
  30935. var imageData = results[0];
  30936. var smaskData = results[1];
  30937. var maskData = results[2];
  30938. return new PDFImage(xref, res, imageData, inline, smaskData, maskData);
  30939. });
  30940. };
  30941. /**
  30942. * Resize an image using the nearest neighbor algorithm. Currently only
  30943. * supports one and three component images.
  30944. * @param {TypedArray} pixels The original image with one component.
  30945. * @param {Number} bpc Number of bits per component.
  30946. * @param {Number} components Number of color components, 1 or 3 is supported.
  30947. * @param {Number} w1 Original width.
  30948. * @param {Number} h1 Original height.
  30949. * @param {Number} w2 New width.
  30950. * @param {Number} h2 New height.
  30951. * @param {TypedArray} dest (Optional) The destination buffer.
  30952. * @param {Number} alpha01 (Optional) Size reserved for the alpha channel.
  30953. * @return {TypedArray} Resized image data.
  30954. */
  30955. PDFImage.resize = function PDFImage_resize(pixels, bpc, components,
  30956. w1, h1, w2, h2, dest, alpha01) {
  30957. if (components !== 1 && components !== 3) {
  30958. error('Unsupported component count for resizing.');
  30959. }
  30960. var length = w2 * h2 * components;
  30961. var temp = dest ? dest : (bpc <= 8 ? new Uint8Array(length) :
  30962. (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));
  30963. var xRatio = w1 / w2;
  30964. var yRatio = h1 / h2;
  30965. var i, j, py, newIndex = 0, oldIndex;
  30966. var xScaled = new Uint16Array(w2);
  30967. var w1Scanline = w1 * components;
  30968. if (alpha01 !== 1) {
  30969. alpha01 = 0;
  30970. }
  30971. for (j = 0; j < w2; j++) {
  30972. xScaled[j] = Math.floor(j * xRatio) * components;
  30973. }
  30974. if (components === 1) {
  30975. for (i = 0; i < h2; i++) {
  30976. py = Math.floor(i * yRatio) * w1Scanline;
  30977. for (j = 0; j < w2; j++) {
  30978. oldIndex = py + xScaled[j];
  30979. temp[newIndex++] = pixels[oldIndex];
  30980. }
  30981. }
  30982. } else if (components === 3) {
  30983. for (i = 0; i < h2; i++) {
  30984. py = Math.floor(i * yRatio) * w1Scanline;
  30985. for (j = 0; j < w2; j++) {
  30986. oldIndex = py + xScaled[j];
  30987. temp[newIndex++] = pixels[oldIndex++];
  30988. temp[newIndex++] = pixels[oldIndex++];
  30989. temp[newIndex++] = pixels[oldIndex++];
  30990. newIndex += alpha01;
  30991. }
  30992. }
  30993. }
  30994. return temp;
  30995. };
  30996. PDFImage.createMask =
  30997. function PDFImage_createMask(imgArray, width, height,
  30998. imageIsFromDecodeStream, inverseDecode) {
  30999. // |imgArray| might not contain full data for every pixel of the mask, so
  31000. // we need to distinguish between |computedLength| and |actualLength|.
  31001. // In particular, if inverseDecode is true, then the array we return must
  31002. // have a length of |computedLength|.
  31003. var computedLength = ((width + 7) >> 3) * height;
  31004. var actualLength = imgArray.byteLength;
  31005. var haveFullData = computedLength === actualLength;
  31006. var data, i;
  31007. if (imageIsFromDecodeStream && (!inverseDecode || haveFullData)) {
  31008. // imgArray came from a DecodeStream and its data is in an appropriate
  31009. // form, so we can just transfer it.
  31010. data = imgArray;
  31011. } else if (!inverseDecode) {
  31012. data = new Uint8Array(actualLength);
  31013. data.set(imgArray);
  31014. } else {
  31015. data = new Uint8Array(computedLength);
  31016. data.set(imgArray);
  31017. for (i = actualLength; i < computedLength; i++) {
  31018. data[i] = 0xff;
  31019. }
  31020. }
  31021. // If necessary, invert the original mask data (but not any extra we might
  31022. // have added above). It's safe to modify the array -- whether it's the
  31023. // original or a copy, we're about to transfer it anyway, so nothing else
  31024. // in this thread can be relying on its contents.
  31025. if (inverseDecode) {
  31026. for (i = 0; i < actualLength; i++) {
  31027. data[i] = ~data[i];
  31028. }
  31029. }
  31030. return {data: data, width: width, height: height};
  31031. };
  31032. PDFImage.prototype = {
  31033. get drawWidth() {
  31034. return Math.max(this.width,
  31035. this.smask && this.smask.width || 0,
  31036. this.mask && this.mask.width || 0);
  31037. },
  31038. get drawHeight() {
  31039. return Math.max(this.height,
  31040. this.smask && this.smask.height || 0,
  31041. this.mask && this.mask.height || 0);
  31042. },
  31043. decodeBuffer: function PDFImage_decodeBuffer(buffer) {
  31044. var bpc = this.bpc;
  31045. var numComps = this.numComps;
  31046. var decodeAddends = this.decodeAddends;
  31047. var decodeCoefficients = this.decodeCoefficients;
  31048. var max = (1 << bpc) - 1;
  31049. var i, ii;
  31050. if (bpc === 1) {
  31051. // If the buffer needed decode that means it just needs to be inverted.
  31052. for (i = 0, ii = buffer.length; i < ii; i++) {
  31053. buffer[i] = +!(buffer[i]);
  31054. }
  31055. return;
  31056. }
  31057. var index = 0;
  31058. for (i = 0, ii = this.width * this.height; i < ii; i++) {
  31059. for (var j = 0; j < numComps; j++) {
  31060. buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j],
  31061. decodeCoefficients[j], max);
  31062. index++;
  31063. }
  31064. }
  31065. },
  31066. getComponents: function PDFImage_getComponents(buffer) {
  31067. var bpc = this.bpc;
  31068. // This image doesn't require any extra work.
  31069. if (bpc === 8) {
  31070. return buffer;
  31071. }
  31072. var width = this.width;
  31073. var height = this.height;
  31074. var numComps = this.numComps;
  31075. var length = width * height * numComps;
  31076. var bufferPos = 0;
  31077. var output = (bpc <= 8 ? new Uint8Array(length) :
  31078. (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));
  31079. var rowComps = width * numComps;
  31080. var max = (1 << bpc) - 1;
  31081. var i = 0, ii, buf;
  31082. if (bpc === 1) {
  31083. // Optimization for reading 1 bpc images.
  31084. var mask, loop1End, loop2End;
  31085. for (var j = 0; j < height; j++) {
  31086. loop1End = i + (rowComps & ~7);
  31087. loop2End = i + rowComps;
  31088. // unroll loop for all full bytes
  31089. while (i < loop1End) {
  31090. buf = buffer[bufferPos++];
  31091. output[i] = (buf >> 7) & 1;
  31092. output[i + 1] = (buf >> 6) & 1;
  31093. output[i + 2] = (buf >> 5) & 1;
  31094. output[i + 3] = (buf >> 4) & 1;
  31095. output[i + 4] = (buf >> 3) & 1;
  31096. output[i + 5] = (buf >> 2) & 1;
  31097. output[i + 6] = (buf >> 1) & 1;
  31098. output[i + 7] = buf & 1;
  31099. i += 8;
  31100. }
  31101. // handle remaing bits
  31102. if (i < loop2End) {
  31103. buf = buffer[bufferPos++];
  31104. mask = 128;
  31105. while (i < loop2End) {
  31106. output[i++] = +!!(buf & mask);
  31107. mask >>= 1;
  31108. }
  31109. }
  31110. }
  31111. } else {
  31112. // The general case that handles all other bpc values.
  31113. var bits = 0;
  31114. buf = 0;
  31115. for (i = 0, ii = length; i < ii; ++i) {
  31116. if (i % rowComps === 0) {
  31117. buf = 0;
  31118. bits = 0;
  31119. }
  31120. while (bits < bpc) {
  31121. buf = (buf << 8) | buffer[bufferPos++];
  31122. bits += 8;
  31123. }
  31124. var remainingBits = bits - bpc;
  31125. var value = buf >> remainingBits;
  31126. output[i] = (value < 0 ? 0 : (value > max ? max : value));
  31127. buf = buf & ((1 << remainingBits) - 1);
  31128. bits = remainingBits;
  31129. }
  31130. }
  31131. return output;
  31132. },
  31133. fillOpacity: function PDFImage_fillOpacity(rgbaBuf, width, height,
  31134. actualHeight, image) {
  31135. var smask = this.smask;
  31136. var mask = this.mask;
  31137. var alphaBuf, sw, sh, i, ii, j;
  31138. if (smask) {
  31139. sw = smask.width;
  31140. sh = smask.height;
  31141. alphaBuf = new Uint8Array(sw * sh);
  31142. smask.fillGrayBuffer(alphaBuf);
  31143. if (sw !== width || sh !== height) {
  31144. alphaBuf = PDFImage.resize(alphaBuf, smask.bpc, 1, sw, sh, width,
  31145. height);
  31146. }
  31147. } else if (mask) {
  31148. if (mask instanceof PDFImage) {
  31149. sw = mask.width;
  31150. sh = mask.height;
  31151. alphaBuf = new Uint8Array(sw * sh);
  31152. mask.numComps = 1;
  31153. mask.fillGrayBuffer(alphaBuf);
  31154. // Need to invert values in rgbaBuf
  31155. for (i = 0, ii = sw * sh; i < ii; ++i) {
  31156. alphaBuf[i] = 255 - alphaBuf[i];
  31157. }
  31158. if (sw !== width || sh !== height) {
  31159. alphaBuf = PDFImage.resize(alphaBuf, mask.bpc, 1, sw, sh, width,
  31160. height);
  31161. }
  31162. } else if (isArray(mask)) {
  31163. // Color key mask: if any of the compontents are outside the range
  31164. // then they should be painted.
  31165. alphaBuf = new Uint8Array(width * height);
  31166. var numComps = this.numComps;
  31167. for (i = 0, ii = width * height; i < ii; ++i) {
  31168. var opacity = 0;
  31169. var imageOffset = i * numComps;
  31170. for (j = 0; j < numComps; ++j) {
  31171. var color = image[imageOffset + j];
  31172. var maskOffset = j * 2;
  31173. if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
  31174. opacity = 255;
  31175. break;
  31176. }
  31177. }
  31178. alphaBuf[i] = opacity;
  31179. }
  31180. } else {
  31181. error('Unknown mask format.');
  31182. }
  31183. }
  31184. if (alphaBuf) {
  31185. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  31186. rgbaBuf[j] = alphaBuf[i];
  31187. }
  31188. } else {
  31189. // No mask.
  31190. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  31191. rgbaBuf[j] = 255;
  31192. }
  31193. }
  31194. },
  31195. undoPreblend: function PDFImage_undoPreblend(buffer, width, height) {
  31196. var matte = this.smask && this.smask.matte;
  31197. if (!matte) {
  31198. return;
  31199. }
  31200. var matteRgb = this.colorSpace.getRgb(matte, 0);
  31201. var matteR = matteRgb[0];
  31202. var matteG = matteRgb[1];
  31203. var matteB = matteRgb[2];
  31204. var length = width * height * 4;
  31205. var r, g, b;
  31206. for (var i = 0; i < length; i += 4) {
  31207. var alpha = buffer[i + 3];
  31208. if (alpha === 0) {
  31209. // according formula we have to get Infinity in all components
  31210. // making it white (typical paper color) should be okay
  31211. buffer[i] = 255;
  31212. buffer[i + 1] = 255;
  31213. buffer[i + 2] = 255;
  31214. continue;
  31215. }
  31216. var k = 255 / alpha;
  31217. r = (buffer[i] - matteR) * k + matteR;
  31218. g = (buffer[i + 1] - matteG) * k + matteG;
  31219. b = (buffer[i + 2] - matteB) * k + matteB;
  31220. buffer[i] = r <= 0 ? 0 : r >= 255 ? 255 : r | 0;
  31221. buffer[i + 1] = g <= 0 ? 0 : g >= 255 ? 255 : g | 0;
  31222. buffer[i + 2] = b <= 0 ? 0 : b >= 255 ? 255 : b | 0;
  31223. }
  31224. },
  31225. createImageData: function PDFImage_createImageData(forceRGBA) {
  31226. var drawWidth = this.drawWidth;
  31227. var drawHeight = this.drawHeight;
  31228. var imgData = { // other fields are filled in below
  31229. width: drawWidth,
  31230. height: drawHeight
  31231. };
  31232. var numComps = this.numComps;
  31233. var originalWidth = this.width;
  31234. var originalHeight = this.height;
  31235. var bpc = this.bpc;
  31236. // Rows start at byte boundary.
  31237. var rowBytes = (originalWidth * numComps * bpc + 7) >> 3;
  31238. var imgArray;
  31239. if (!forceRGBA) {
  31240. // If it is a 1-bit-per-pixel grayscale (i.e. black-and-white) image
  31241. // without any complications, we pass a same-sized copy to the main
  31242. // thread rather than expanding by 32x to RGBA form. This saves *lots*
  31243. // of memory for many scanned documents. It's also much faster.
  31244. //
  31245. // Similarly, if it is a 24-bit-per pixel RGB image without any
  31246. // complications, we avoid expanding by 1.333x to RGBA form.
  31247. var kind;
  31248. if (this.colorSpace.name === 'DeviceGray' && bpc === 1) {
  31249. kind = ImageKind.GRAYSCALE_1BPP;
  31250. } else if (this.colorSpace.name === 'DeviceRGB' && bpc === 8 &&
  31251. !this.needsDecode) {
  31252. kind = ImageKind.RGB_24BPP;
  31253. }
  31254. if (kind && !this.smask && !this.mask &&
  31255. drawWidth === originalWidth && drawHeight === originalHeight) {
  31256. imgData.kind = kind;
  31257. imgArray = this.getImageBytes(originalHeight * rowBytes);
  31258. // If imgArray came from a DecodeStream, we're safe to transfer it
  31259. // (and thus neuter it) because it will constitute the entire
  31260. // DecodeStream's data. But if it came from a Stream, we need to
  31261. // copy it because it'll only be a portion of the Stream's data, and
  31262. // the rest will be read later on.
  31263. if (this.image instanceof DecodeStream) {
  31264. imgData.data = imgArray;
  31265. } else {
  31266. var newArray = new Uint8Array(imgArray.length);
  31267. newArray.set(imgArray);
  31268. imgData.data = newArray;
  31269. }
  31270. if (this.needsDecode) {
  31271. // Invert the buffer (which must be grayscale if we reached here).
  31272. assert(kind === ImageKind.GRAYSCALE_1BPP);
  31273. var buffer = imgData.data;
  31274. for (var i = 0, ii = buffer.length; i < ii; i++) {
  31275. buffer[i] ^= 0xff;
  31276. }
  31277. }
  31278. return imgData;
  31279. }
  31280. if (this.image instanceof JpegStream && !this.smask && !this.mask) {
  31281. imgData.kind = ImageKind.RGB_24BPP;
  31282. imgData.data = this.getImageBytes(originalHeight * rowBytes,
  31283. drawWidth, drawHeight, true);
  31284. return imgData;
  31285. }
  31286. }
  31287. imgArray = this.getImageBytes(originalHeight * rowBytes);
  31288. // imgArray can be incomplete (e.g. after CCITT fax encoding).
  31289. var actualHeight = 0 | (imgArray.length / rowBytes *
  31290. drawHeight / originalHeight);
  31291. var comps = this.getComponents(imgArray);
  31292. // If opacity data is present, use RGBA_32BPP form. Otherwise, use the
  31293. // more compact RGB_24BPP form if allowable.
  31294. var alpha01, maybeUndoPreblend;
  31295. if (!forceRGBA && !this.smask && !this.mask) {
  31296. imgData.kind = ImageKind.RGB_24BPP;
  31297. imgData.data = new Uint8Array(drawWidth * drawHeight * 3);
  31298. alpha01 = 0;
  31299. maybeUndoPreblend = false;
  31300. } else {
  31301. imgData.kind = ImageKind.RGBA_32BPP;
  31302. imgData.data = new Uint8Array(drawWidth * drawHeight * 4);
  31303. alpha01 = 1;
  31304. maybeUndoPreblend = true;
  31305. // Color key masking (opacity) must be performed before decoding.
  31306. this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight,
  31307. comps);
  31308. }
  31309. if (this.needsDecode) {
  31310. this.decodeBuffer(comps);
  31311. }
  31312. this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight,
  31313. drawWidth, drawHeight, actualHeight, bpc, comps,
  31314. alpha01);
  31315. if (maybeUndoPreblend) {
  31316. this.undoPreblend(imgData.data, drawWidth, actualHeight);
  31317. }
  31318. return imgData;
  31319. },
  31320. fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) {
  31321. var numComps = this.numComps;
  31322. if (numComps !== 1) {
  31323. error('Reading gray scale from a color image: ' + numComps);
  31324. }
  31325. var width = this.width;
  31326. var height = this.height;
  31327. var bpc = this.bpc;
  31328. // rows start at byte boundary
  31329. var rowBytes = (width * numComps * bpc + 7) >> 3;
  31330. var imgArray = this.getImageBytes(height * rowBytes);
  31331. var comps = this.getComponents(imgArray);
  31332. var i, length;
  31333. if (bpc === 1) {
  31334. // inline decoding (= inversion) for 1 bpc images
  31335. length = width * height;
  31336. if (this.needsDecode) {
  31337. // invert and scale to {0, 255}
  31338. for (i = 0; i < length; ++i) {
  31339. buffer[i] = (comps[i] - 1) & 255;
  31340. }
  31341. } else {
  31342. // scale to {0, 255}
  31343. for (i = 0; i < length; ++i) {
  31344. buffer[i] = (-comps[i]) & 255;
  31345. }
  31346. }
  31347. return;
  31348. }
  31349. if (this.needsDecode) {
  31350. this.decodeBuffer(comps);
  31351. }
  31352. length = width * height;
  31353. // we aren't using a colorspace so we need to scale the value
  31354. var scale = 255 / ((1 << bpc) - 1);
  31355. for (i = 0; i < length; ++i) {
  31356. buffer[i] = (scale * comps[i]) | 0;
  31357. }
  31358. },
  31359. getImageBytes: function PDFImage_getImageBytes(length,
  31360. drawWidth, drawHeight,
  31361. forceRGB) {
  31362. this.image.reset();
  31363. this.image.drawWidth = drawWidth || this.width;
  31364. this.image.drawHeight = drawHeight || this.height;
  31365. this.image.forceRGB = !!forceRGB;
  31366. return this.image.getBytes(length);
  31367. }
  31368. };
  31369. return PDFImage;
  31370. })();
  31371. // The Metrics object contains glyph widths (in glyph space units).
  31372. // As per PDF spec, for most fonts (Type 3 being an exception) a glyph
  31373. // space unit corresponds to 1/1000th of text space unit.
  31374. var Metrics = {
  31375. 'Courier': 600,
  31376. 'Courier-Bold': 600,
  31377. 'Courier-BoldOblique': 600,
  31378. 'Courier-Oblique': 600,
  31379. 'Helvetica' : {
  31380. 'space': 278,
  31381. 'exclam': 278,
  31382. 'quotedbl': 355,
  31383. 'numbersign': 556,
  31384. 'dollar': 556,
  31385. 'percent': 889,
  31386. 'ampersand': 667,
  31387. 'quoteright': 222,
  31388. 'parenleft': 333,
  31389. 'parenright': 333,
  31390. 'asterisk': 389,
  31391. 'plus': 584,
  31392. 'comma': 278,
  31393. 'hyphen': 333,
  31394. 'period': 278,
  31395. 'slash': 278,
  31396. 'zero': 556,
  31397. 'one': 556,
  31398. 'two': 556,
  31399. 'three': 556,
  31400. 'four': 556,
  31401. 'five': 556,
  31402. 'six': 556,
  31403. 'seven': 556,
  31404. 'eight': 556,
  31405. 'nine': 556,
  31406. 'colon': 278,
  31407. 'semicolon': 278,
  31408. 'less': 584,
  31409. 'equal': 584,
  31410. 'greater': 584,
  31411. 'question': 556,
  31412. 'at': 1015,
  31413. 'A': 667,
  31414. 'B': 667,
  31415. 'C': 722,
  31416. 'D': 722,
  31417. 'E': 667,
  31418. 'F': 611,
  31419. 'G': 778,
  31420. 'H': 722,
  31421. 'I': 278,
  31422. 'J': 500,
  31423. 'K': 667,
  31424. 'L': 556,
  31425. 'M': 833,
  31426. 'N': 722,
  31427. 'O': 778,
  31428. 'P': 667,
  31429. 'Q': 778,
  31430. 'R': 722,
  31431. 'S': 667,
  31432. 'T': 611,
  31433. 'U': 722,
  31434. 'V': 667,
  31435. 'W': 944,
  31436. 'X': 667,
  31437. 'Y': 667,
  31438. 'Z': 611,
  31439. 'bracketleft': 278,
  31440. 'backslash': 278,
  31441. 'bracketright': 278,
  31442. 'asciicircum': 469,
  31443. 'underscore': 556,
  31444. 'quoteleft': 222,
  31445. 'a': 556,
  31446. 'b': 556,
  31447. 'c': 500,
  31448. 'd': 556,
  31449. 'e': 556,
  31450. 'f': 278,
  31451. 'g': 556,
  31452. 'h': 556,
  31453. 'i': 222,
  31454. 'j': 222,
  31455. 'k': 500,
  31456. 'l': 222,
  31457. 'm': 833,
  31458. 'n': 556,
  31459. 'o': 556,
  31460. 'p': 556,
  31461. 'q': 556,
  31462. 'r': 333,
  31463. 's': 500,
  31464. 't': 278,
  31465. 'u': 556,
  31466. 'v': 500,
  31467. 'w': 722,
  31468. 'x': 500,
  31469. 'y': 500,
  31470. 'z': 500,
  31471. 'braceleft': 334,
  31472. 'bar': 260,
  31473. 'braceright': 334,
  31474. 'asciitilde': 584,
  31475. 'exclamdown': 333,
  31476. 'cent': 556,
  31477. 'sterling': 556,
  31478. 'fraction': 167,
  31479. 'yen': 556,
  31480. 'florin': 556,
  31481. 'section': 556,
  31482. 'currency': 556,
  31483. 'quotesingle': 191,
  31484. 'quotedblleft': 333,
  31485. 'guillemotleft': 556,
  31486. 'guilsinglleft': 333,
  31487. 'guilsinglright': 333,
  31488. 'fi': 500,
  31489. 'fl': 500,
  31490. 'endash': 556,
  31491. 'dagger': 556,
  31492. 'daggerdbl': 556,
  31493. 'periodcentered': 278,
  31494. 'paragraph': 537,
  31495. 'bullet': 350,
  31496. 'quotesinglbase': 222,
  31497. 'quotedblbase': 333,
  31498. 'quotedblright': 333,
  31499. 'guillemotright': 556,
  31500. 'ellipsis': 1000,
  31501. 'perthousand': 1000,
  31502. 'questiondown': 611,
  31503. 'grave': 333,
  31504. 'acute': 333,
  31505. 'circumflex': 333,
  31506. 'tilde': 333,
  31507. 'macron': 333,
  31508. 'breve': 333,
  31509. 'dotaccent': 333,
  31510. 'dieresis': 333,
  31511. 'ring': 333,
  31512. 'cedilla': 333,
  31513. 'hungarumlaut': 333,
  31514. 'ogonek': 333,
  31515. 'caron': 333,
  31516. 'emdash': 1000,
  31517. 'AE': 1000,
  31518. 'ordfeminine': 370,
  31519. 'Lslash': 556,
  31520. 'Oslash': 778,
  31521. 'OE': 1000,
  31522. 'ordmasculine': 365,
  31523. 'ae': 889,
  31524. 'dotlessi': 278,
  31525. 'lslash': 222,
  31526. 'oslash': 611,
  31527. 'oe': 944,
  31528. 'germandbls': 611,
  31529. 'Idieresis': 278,
  31530. 'eacute': 556,
  31531. 'abreve': 556,
  31532. 'uhungarumlaut': 556,
  31533. 'ecaron': 556,
  31534. 'Ydieresis': 667,
  31535. 'divide': 584,
  31536. 'Yacute': 667,
  31537. 'Acircumflex': 667,
  31538. 'aacute': 556,
  31539. 'Ucircumflex': 722,
  31540. 'yacute': 500,
  31541. 'scommaaccent': 500,
  31542. 'ecircumflex': 556,
  31543. 'Uring': 722,
  31544. 'Udieresis': 722,
  31545. 'aogonek': 556,
  31546. 'Uacute': 722,
  31547. 'uogonek': 556,
  31548. 'Edieresis': 667,
  31549. 'Dcroat': 722,
  31550. 'commaaccent': 250,
  31551. 'copyright': 737,
  31552. 'Emacron': 667,
  31553. 'ccaron': 500,
  31554. 'aring': 556,
  31555. 'Ncommaaccent': 722,
  31556. 'lacute': 222,
  31557. 'agrave': 556,
  31558. 'Tcommaaccent': 611,
  31559. 'Cacute': 722,
  31560. 'atilde': 556,
  31561. 'Edotaccent': 667,
  31562. 'scaron': 500,
  31563. 'scedilla': 500,
  31564. 'iacute': 278,
  31565. 'lozenge': 471,
  31566. 'Rcaron': 722,
  31567. 'Gcommaaccent': 778,
  31568. 'ucircumflex': 556,
  31569. 'acircumflex': 556,
  31570. 'Amacron': 667,
  31571. 'rcaron': 333,
  31572. 'ccedilla': 500,
  31573. 'Zdotaccent': 611,
  31574. 'Thorn': 667,
  31575. 'Omacron': 778,
  31576. 'Racute': 722,
  31577. 'Sacute': 667,
  31578. 'dcaron': 643,
  31579. 'Umacron': 722,
  31580. 'uring': 556,
  31581. 'threesuperior': 333,
  31582. 'Ograve': 778,
  31583. 'Agrave': 667,
  31584. 'Abreve': 667,
  31585. 'multiply': 584,
  31586. 'uacute': 556,
  31587. 'Tcaron': 611,
  31588. 'partialdiff': 476,
  31589. 'ydieresis': 500,
  31590. 'Nacute': 722,
  31591. 'icircumflex': 278,
  31592. 'Ecircumflex': 667,
  31593. 'adieresis': 556,
  31594. 'edieresis': 556,
  31595. 'cacute': 500,
  31596. 'nacute': 556,
  31597. 'umacron': 556,
  31598. 'Ncaron': 722,
  31599. 'Iacute': 278,
  31600. 'plusminus': 584,
  31601. 'brokenbar': 260,
  31602. 'registered': 737,
  31603. 'Gbreve': 778,
  31604. 'Idotaccent': 278,
  31605. 'summation': 600,
  31606. 'Egrave': 667,
  31607. 'racute': 333,
  31608. 'omacron': 556,
  31609. 'Zacute': 611,
  31610. 'Zcaron': 611,
  31611. 'greaterequal': 549,
  31612. 'Eth': 722,
  31613. 'Ccedilla': 722,
  31614. 'lcommaaccent': 222,
  31615. 'tcaron': 317,
  31616. 'eogonek': 556,
  31617. 'Uogonek': 722,
  31618. 'Aacute': 667,
  31619. 'Adieresis': 667,
  31620. 'egrave': 556,
  31621. 'zacute': 500,
  31622. 'iogonek': 222,
  31623. 'Oacute': 778,
  31624. 'oacute': 556,
  31625. 'amacron': 556,
  31626. 'sacute': 500,
  31627. 'idieresis': 278,
  31628. 'Ocircumflex': 778,
  31629. 'Ugrave': 722,
  31630. 'Delta': 612,
  31631. 'thorn': 556,
  31632. 'twosuperior': 333,
  31633. 'Odieresis': 778,
  31634. 'mu': 556,
  31635. 'igrave': 278,
  31636. 'ohungarumlaut': 556,
  31637. 'Eogonek': 667,
  31638. 'dcroat': 556,
  31639. 'threequarters': 834,
  31640. 'Scedilla': 667,
  31641. 'lcaron': 299,
  31642. 'Kcommaaccent': 667,
  31643. 'Lacute': 556,
  31644. 'trademark': 1000,
  31645. 'edotaccent': 556,
  31646. 'Igrave': 278,
  31647. 'Imacron': 278,
  31648. 'Lcaron': 556,
  31649. 'onehalf': 834,
  31650. 'lessequal': 549,
  31651. 'ocircumflex': 556,
  31652. 'ntilde': 556,
  31653. 'Uhungarumlaut': 722,
  31654. 'Eacute': 667,
  31655. 'emacron': 556,
  31656. 'gbreve': 556,
  31657. 'onequarter': 834,
  31658. 'Scaron': 667,
  31659. 'Scommaaccent': 667,
  31660. 'Ohungarumlaut': 778,
  31661. 'degree': 400,
  31662. 'ograve': 556,
  31663. 'Ccaron': 722,
  31664. 'ugrave': 556,
  31665. 'radical': 453,
  31666. 'Dcaron': 722,
  31667. 'rcommaaccent': 333,
  31668. 'Ntilde': 722,
  31669. 'otilde': 556,
  31670. 'Rcommaaccent': 722,
  31671. 'Lcommaaccent': 556,
  31672. 'Atilde': 667,
  31673. 'Aogonek': 667,
  31674. 'Aring': 667,
  31675. 'Otilde': 778,
  31676. 'zdotaccent': 500,
  31677. 'Ecaron': 667,
  31678. 'Iogonek': 278,
  31679. 'kcommaaccent': 500,
  31680. 'minus': 584,
  31681. 'Icircumflex': 278,
  31682. 'ncaron': 556,
  31683. 'tcommaaccent': 278,
  31684. 'logicalnot': 584,
  31685. 'odieresis': 556,
  31686. 'udieresis': 556,
  31687. 'notequal': 549,
  31688. 'gcommaaccent': 556,
  31689. 'eth': 556,
  31690. 'zcaron': 500,
  31691. 'ncommaaccent': 556,
  31692. 'onesuperior': 333,
  31693. 'imacron': 278,
  31694. 'Euro': 556
  31695. },
  31696. 'Helvetica-Bold': {
  31697. 'space': 278,
  31698. 'exclam': 333,
  31699. 'quotedbl': 474,
  31700. 'numbersign': 556,
  31701. 'dollar': 556,
  31702. 'percent': 889,
  31703. 'ampersand': 722,
  31704. 'quoteright': 278,
  31705. 'parenleft': 333,
  31706. 'parenright': 333,
  31707. 'asterisk': 389,
  31708. 'plus': 584,
  31709. 'comma': 278,
  31710. 'hyphen': 333,
  31711. 'period': 278,
  31712. 'slash': 278,
  31713. 'zero': 556,
  31714. 'one': 556,
  31715. 'two': 556,
  31716. 'three': 556,
  31717. 'four': 556,
  31718. 'five': 556,
  31719. 'six': 556,
  31720. 'seven': 556,
  31721. 'eight': 556,
  31722. 'nine': 556,
  31723. 'colon': 333,
  31724. 'semicolon': 333,
  31725. 'less': 584,
  31726. 'equal': 584,
  31727. 'greater': 584,
  31728. 'question': 611,
  31729. 'at': 975,
  31730. 'A': 722,
  31731. 'B': 722,
  31732. 'C': 722,
  31733. 'D': 722,
  31734. 'E': 667,
  31735. 'F': 611,
  31736. 'G': 778,
  31737. 'H': 722,
  31738. 'I': 278,
  31739. 'J': 556,
  31740. 'K': 722,
  31741. 'L': 611,
  31742. 'M': 833,
  31743. 'N': 722,
  31744. 'O': 778,
  31745. 'P': 667,
  31746. 'Q': 778,
  31747. 'R': 722,
  31748. 'S': 667,
  31749. 'T': 611,
  31750. 'U': 722,
  31751. 'V': 667,
  31752. 'W': 944,
  31753. 'X': 667,
  31754. 'Y': 667,
  31755. 'Z': 611,
  31756. 'bracketleft': 333,
  31757. 'backslash': 278,
  31758. 'bracketright': 333,
  31759. 'asciicircum': 584,
  31760. 'underscore': 556,
  31761. 'quoteleft': 278,
  31762. 'a': 556,
  31763. 'b': 611,
  31764. 'c': 556,
  31765. 'd': 611,
  31766. 'e': 556,
  31767. 'f': 333,
  31768. 'g': 611,
  31769. 'h': 611,
  31770. 'i': 278,
  31771. 'j': 278,
  31772. 'k': 556,
  31773. 'l': 278,
  31774. 'm': 889,
  31775. 'n': 611,
  31776. 'o': 611,
  31777. 'p': 611,
  31778. 'q': 611,
  31779. 'r': 389,
  31780. 's': 556,
  31781. 't': 333,
  31782. 'u': 611,
  31783. 'v': 556,
  31784. 'w': 778,
  31785. 'x': 556,
  31786. 'y': 556,
  31787. 'z': 500,
  31788. 'braceleft': 389,
  31789. 'bar': 280,
  31790. 'braceright': 389,
  31791. 'asciitilde': 584,
  31792. 'exclamdown': 333,
  31793. 'cent': 556,
  31794. 'sterling': 556,
  31795. 'fraction': 167,
  31796. 'yen': 556,
  31797. 'florin': 556,
  31798. 'section': 556,
  31799. 'currency': 556,
  31800. 'quotesingle': 238,
  31801. 'quotedblleft': 500,
  31802. 'guillemotleft': 556,
  31803. 'guilsinglleft': 333,
  31804. 'guilsinglright': 333,
  31805. 'fi': 611,
  31806. 'fl': 611,
  31807. 'endash': 556,
  31808. 'dagger': 556,
  31809. 'daggerdbl': 556,
  31810. 'periodcentered': 278,
  31811. 'paragraph': 556,
  31812. 'bullet': 350,
  31813. 'quotesinglbase': 278,
  31814. 'quotedblbase': 500,
  31815. 'quotedblright': 500,
  31816. 'guillemotright': 556,
  31817. 'ellipsis': 1000,
  31818. 'perthousand': 1000,
  31819. 'questiondown': 611,
  31820. 'grave': 333,
  31821. 'acute': 333,
  31822. 'circumflex': 333,
  31823. 'tilde': 333,
  31824. 'macron': 333,
  31825. 'breve': 333,
  31826. 'dotaccent': 333,
  31827. 'dieresis': 333,
  31828. 'ring': 333,
  31829. 'cedilla': 333,
  31830. 'hungarumlaut': 333,
  31831. 'ogonek': 333,
  31832. 'caron': 333,
  31833. 'emdash': 1000,
  31834. 'AE': 1000,
  31835. 'ordfeminine': 370,
  31836. 'Lslash': 611,
  31837. 'Oslash': 778,
  31838. 'OE': 1000,
  31839. 'ordmasculine': 365,
  31840. 'ae': 889,
  31841. 'dotlessi': 278,
  31842. 'lslash': 278,
  31843. 'oslash': 611,
  31844. 'oe': 944,
  31845. 'germandbls': 611,
  31846. 'Idieresis': 278,
  31847. 'eacute': 556,
  31848. 'abreve': 556,
  31849. 'uhungarumlaut': 611,
  31850. 'ecaron': 556,
  31851. 'Ydieresis': 667,
  31852. 'divide': 584,
  31853. 'Yacute': 667,
  31854. 'Acircumflex': 722,
  31855. 'aacute': 556,
  31856. 'Ucircumflex': 722,
  31857. 'yacute': 556,
  31858. 'scommaaccent': 556,
  31859. 'ecircumflex': 556,
  31860. 'Uring': 722,
  31861. 'Udieresis': 722,
  31862. 'aogonek': 556,
  31863. 'Uacute': 722,
  31864. 'uogonek': 611,
  31865. 'Edieresis': 667,
  31866. 'Dcroat': 722,
  31867. 'commaaccent': 250,
  31868. 'copyright': 737,
  31869. 'Emacron': 667,
  31870. 'ccaron': 556,
  31871. 'aring': 556,
  31872. 'Ncommaaccent': 722,
  31873. 'lacute': 278,
  31874. 'agrave': 556,
  31875. 'Tcommaaccent': 611,
  31876. 'Cacute': 722,
  31877. 'atilde': 556,
  31878. 'Edotaccent': 667,
  31879. 'scaron': 556,
  31880. 'scedilla': 556,
  31881. 'iacute': 278,
  31882. 'lozenge': 494,
  31883. 'Rcaron': 722,
  31884. 'Gcommaaccent': 778,
  31885. 'ucircumflex': 611,
  31886. 'acircumflex': 556,
  31887. 'Amacron': 722,
  31888. 'rcaron': 389,
  31889. 'ccedilla': 556,
  31890. 'Zdotaccent': 611,
  31891. 'Thorn': 667,
  31892. 'Omacron': 778,
  31893. 'Racute': 722,
  31894. 'Sacute': 667,
  31895. 'dcaron': 743,
  31896. 'Umacron': 722,
  31897. 'uring': 611,
  31898. 'threesuperior': 333,
  31899. 'Ograve': 778,
  31900. 'Agrave': 722,
  31901. 'Abreve': 722,
  31902. 'multiply': 584,
  31903. 'uacute': 611,
  31904. 'Tcaron': 611,
  31905. 'partialdiff': 494,
  31906. 'ydieresis': 556,
  31907. 'Nacute': 722,
  31908. 'icircumflex': 278,
  31909. 'Ecircumflex': 667,
  31910. 'adieresis': 556,
  31911. 'edieresis': 556,
  31912. 'cacute': 556,
  31913. 'nacute': 611,
  31914. 'umacron': 611,
  31915. 'Ncaron': 722,
  31916. 'Iacute': 278,
  31917. 'plusminus': 584,
  31918. 'brokenbar': 280,
  31919. 'registered': 737,
  31920. 'Gbreve': 778,
  31921. 'Idotaccent': 278,
  31922. 'summation': 600,
  31923. 'Egrave': 667,
  31924. 'racute': 389,
  31925. 'omacron': 611,
  31926. 'Zacute': 611,
  31927. 'Zcaron': 611,
  31928. 'greaterequal': 549,
  31929. 'Eth': 722,
  31930. 'Ccedilla': 722,
  31931. 'lcommaaccent': 278,
  31932. 'tcaron': 389,
  31933. 'eogonek': 556,
  31934. 'Uogonek': 722,
  31935. 'Aacute': 722,
  31936. 'Adieresis': 722,
  31937. 'egrave': 556,
  31938. 'zacute': 500,
  31939. 'iogonek': 278,
  31940. 'Oacute': 778,
  31941. 'oacute': 611,
  31942. 'amacron': 556,
  31943. 'sacute': 556,
  31944. 'idieresis': 278,
  31945. 'Ocircumflex': 778,
  31946. 'Ugrave': 722,
  31947. 'Delta': 612,
  31948. 'thorn': 611,
  31949. 'twosuperior': 333,
  31950. 'Odieresis': 778,
  31951. 'mu': 611,
  31952. 'igrave': 278,
  31953. 'ohungarumlaut': 611,
  31954. 'Eogonek': 667,
  31955. 'dcroat': 611,
  31956. 'threequarters': 834,
  31957. 'Scedilla': 667,
  31958. 'lcaron': 400,
  31959. 'Kcommaaccent': 722,
  31960. 'Lacute': 611,
  31961. 'trademark': 1000,
  31962. 'edotaccent': 556,
  31963. 'Igrave': 278,
  31964. 'Imacron': 278,
  31965. 'Lcaron': 611,
  31966. 'onehalf': 834,
  31967. 'lessequal': 549,
  31968. 'ocircumflex': 611,
  31969. 'ntilde': 611,
  31970. 'Uhungarumlaut': 722,
  31971. 'Eacute': 667,
  31972. 'emacron': 556,
  31973. 'gbreve': 611,
  31974. 'onequarter': 834,
  31975. 'Scaron': 667,
  31976. 'Scommaaccent': 667,
  31977. 'Ohungarumlaut': 778,
  31978. 'degree': 400,
  31979. 'ograve': 611,
  31980. 'Ccaron': 722,
  31981. 'ugrave': 611,
  31982. 'radical': 549,
  31983. 'Dcaron': 722,
  31984. 'rcommaaccent': 389,
  31985. 'Ntilde': 722,
  31986. 'otilde': 611,
  31987. 'Rcommaaccent': 722,
  31988. 'Lcommaaccent': 611,
  31989. 'Atilde': 722,
  31990. 'Aogonek': 722,
  31991. 'Aring': 722,
  31992. 'Otilde': 778,
  31993. 'zdotaccent': 500,
  31994. 'Ecaron': 667,
  31995. 'Iogonek': 278,
  31996. 'kcommaaccent': 556,
  31997. 'minus': 584,
  31998. 'Icircumflex': 278,
  31999. 'ncaron': 611,
  32000. 'tcommaaccent': 333,
  32001. 'logicalnot': 584,
  32002. 'odieresis': 611,
  32003. 'udieresis': 611,
  32004. 'notequal': 549,
  32005. 'gcommaaccent': 611,
  32006. 'eth': 611,
  32007. 'zcaron': 500,
  32008. 'ncommaaccent': 611,
  32009. 'onesuperior': 333,
  32010. 'imacron': 278,
  32011. 'Euro': 556
  32012. },
  32013. 'Helvetica-BoldOblique': {
  32014. 'space': 278,
  32015. 'exclam': 333,
  32016. 'quotedbl': 474,
  32017. 'numbersign': 556,
  32018. 'dollar': 556,
  32019. 'percent': 889,
  32020. 'ampersand': 722,
  32021. 'quoteright': 278,
  32022. 'parenleft': 333,
  32023. 'parenright': 333,
  32024. 'asterisk': 389,
  32025. 'plus': 584,
  32026. 'comma': 278,
  32027. 'hyphen': 333,
  32028. 'period': 278,
  32029. 'slash': 278,
  32030. 'zero': 556,
  32031. 'one': 556,
  32032. 'two': 556,
  32033. 'three': 556,
  32034. 'four': 556,
  32035. 'five': 556,
  32036. 'six': 556,
  32037. 'seven': 556,
  32038. 'eight': 556,
  32039. 'nine': 556,
  32040. 'colon': 333,
  32041. 'semicolon': 333,
  32042. 'less': 584,
  32043. 'equal': 584,
  32044. 'greater': 584,
  32045. 'question': 611,
  32046. 'at': 975,
  32047. 'A': 722,
  32048. 'B': 722,
  32049. 'C': 722,
  32050. 'D': 722,
  32051. 'E': 667,
  32052. 'F': 611,
  32053. 'G': 778,
  32054. 'H': 722,
  32055. 'I': 278,
  32056. 'J': 556,
  32057. 'K': 722,
  32058. 'L': 611,
  32059. 'M': 833,
  32060. 'N': 722,
  32061. 'O': 778,
  32062. 'P': 667,
  32063. 'Q': 778,
  32064. 'R': 722,
  32065. 'S': 667,
  32066. 'T': 611,
  32067. 'U': 722,
  32068. 'V': 667,
  32069. 'W': 944,
  32070. 'X': 667,
  32071. 'Y': 667,
  32072. 'Z': 611,
  32073. 'bracketleft': 333,
  32074. 'backslash': 278,
  32075. 'bracketright': 333,
  32076. 'asciicircum': 584,
  32077. 'underscore': 556,
  32078. 'quoteleft': 278,
  32079. 'a': 556,
  32080. 'b': 611,
  32081. 'c': 556,
  32082. 'd': 611,
  32083. 'e': 556,
  32084. 'f': 333,
  32085. 'g': 611,
  32086. 'h': 611,
  32087. 'i': 278,
  32088. 'j': 278,
  32089. 'k': 556,
  32090. 'l': 278,
  32091. 'm': 889,
  32092. 'n': 611,
  32093. 'o': 611,
  32094. 'p': 611,
  32095. 'q': 611,
  32096. 'r': 389,
  32097. 's': 556,
  32098. 't': 333,
  32099. 'u': 611,
  32100. 'v': 556,
  32101. 'w': 778,
  32102. 'x': 556,
  32103. 'y': 556,
  32104. 'z': 500,
  32105. 'braceleft': 389,
  32106. 'bar': 280,
  32107. 'braceright': 389,
  32108. 'asciitilde': 584,
  32109. 'exclamdown': 333,
  32110. 'cent': 556,
  32111. 'sterling': 556,
  32112. 'fraction': 167,
  32113. 'yen': 556,
  32114. 'florin': 556,
  32115. 'section': 556,
  32116. 'currency': 556,
  32117. 'quotesingle': 238,
  32118. 'quotedblleft': 500,
  32119. 'guillemotleft': 556,
  32120. 'guilsinglleft': 333,
  32121. 'guilsinglright': 333,
  32122. 'fi': 611,
  32123. 'fl': 611,
  32124. 'endash': 556,
  32125. 'dagger': 556,
  32126. 'daggerdbl': 556,
  32127. 'periodcentered': 278,
  32128. 'paragraph': 556,
  32129. 'bullet': 350,
  32130. 'quotesinglbase': 278,
  32131. 'quotedblbase': 500,
  32132. 'quotedblright': 500,
  32133. 'guillemotright': 556,
  32134. 'ellipsis': 1000,
  32135. 'perthousand': 1000,
  32136. 'questiondown': 611,
  32137. 'grave': 333,
  32138. 'acute': 333,
  32139. 'circumflex': 333,
  32140. 'tilde': 333,
  32141. 'macron': 333,
  32142. 'breve': 333,
  32143. 'dotaccent': 333,
  32144. 'dieresis': 333,
  32145. 'ring': 333,
  32146. 'cedilla': 333,
  32147. 'hungarumlaut': 333,
  32148. 'ogonek': 333,
  32149. 'caron': 333,
  32150. 'emdash': 1000,
  32151. 'AE': 1000,
  32152. 'ordfeminine': 370,
  32153. 'Lslash': 611,
  32154. 'Oslash': 778,
  32155. 'OE': 1000,
  32156. 'ordmasculine': 365,
  32157. 'ae': 889,
  32158. 'dotlessi': 278,
  32159. 'lslash': 278,
  32160. 'oslash': 611,
  32161. 'oe': 944,
  32162. 'germandbls': 611,
  32163. 'Idieresis': 278,
  32164. 'eacute': 556,
  32165. 'abreve': 556,
  32166. 'uhungarumlaut': 611,
  32167. 'ecaron': 556,
  32168. 'Ydieresis': 667,
  32169. 'divide': 584,
  32170. 'Yacute': 667,
  32171. 'Acircumflex': 722,
  32172. 'aacute': 556,
  32173. 'Ucircumflex': 722,
  32174. 'yacute': 556,
  32175. 'scommaaccent': 556,
  32176. 'ecircumflex': 556,
  32177. 'Uring': 722,
  32178. 'Udieresis': 722,
  32179. 'aogonek': 556,
  32180. 'Uacute': 722,
  32181. 'uogonek': 611,
  32182. 'Edieresis': 667,
  32183. 'Dcroat': 722,
  32184. 'commaaccent': 250,
  32185. 'copyright': 737,
  32186. 'Emacron': 667,
  32187. 'ccaron': 556,
  32188. 'aring': 556,
  32189. 'Ncommaaccent': 722,
  32190. 'lacute': 278,
  32191. 'agrave': 556,
  32192. 'Tcommaaccent': 611,
  32193. 'Cacute': 722,
  32194. 'atilde': 556,
  32195. 'Edotaccent': 667,
  32196. 'scaron': 556,
  32197. 'scedilla': 556,
  32198. 'iacute': 278,
  32199. 'lozenge': 494,
  32200. 'Rcaron': 722,
  32201. 'Gcommaaccent': 778,
  32202. 'ucircumflex': 611,
  32203. 'acircumflex': 556,
  32204. 'Amacron': 722,
  32205. 'rcaron': 389,
  32206. 'ccedilla': 556,
  32207. 'Zdotaccent': 611,
  32208. 'Thorn': 667,
  32209. 'Omacron': 778,
  32210. 'Racute': 722,
  32211. 'Sacute': 667,
  32212. 'dcaron': 743,
  32213. 'Umacron': 722,
  32214. 'uring': 611,
  32215. 'threesuperior': 333,
  32216. 'Ograve': 778,
  32217. 'Agrave': 722,
  32218. 'Abreve': 722,
  32219. 'multiply': 584,
  32220. 'uacute': 611,
  32221. 'Tcaron': 611,
  32222. 'partialdiff': 494,
  32223. 'ydieresis': 556,
  32224. 'Nacute': 722,
  32225. 'icircumflex': 278,
  32226. 'Ecircumflex': 667,
  32227. 'adieresis': 556,
  32228. 'edieresis': 556,
  32229. 'cacute': 556,
  32230. 'nacute': 611,
  32231. 'umacron': 611,
  32232. 'Ncaron': 722,
  32233. 'Iacute': 278,
  32234. 'plusminus': 584,
  32235. 'brokenbar': 280,
  32236. 'registered': 737,
  32237. 'Gbreve': 778,
  32238. 'Idotaccent': 278,
  32239. 'summation': 600,
  32240. 'Egrave': 667,
  32241. 'racute': 389,
  32242. 'omacron': 611,
  32243. 'Zacute': 611,
  32244. 'Zcaron': 611,
  32245. 'greaterequal': 549,
  32246. 'Eth': 722,
  32247. 'Ccedilla': 722,
  32248. 'lcommaaccent': 278,
  32249. 'tcaron': 389,
  32250. 'eogonek': 556,
  32251. 'Uogonek': 722,
  32252. 'Aacute': 722,
  32253. 'Adieresis': 722,
  32254. 'egrave': 556,
  32255. 'zacute': 500,
  32256. 'iogonek': 278,
  32257. 'Oacute': 778,
  32258. 'oacute': 611,
  32259. 'amacron': 556,
  32260. 'sacute': 556,
  32261. 'idieresis': 278,
  32262. 'Ocircumflex': 778,
  32263. 'Ugrave': 722,
  32264. 'Delta': 612,
  32265. 'thorn': 611,
  32266. 'twosuperior': 333,
  32267. 'Odieresis': 778,
  32268. 'mu': 611,
  32269. 'igrave': 278,
  32270. 'ohungarumlaut': 611,
  32271. 'Eogonek': 667,
  32272. 'dcroat': 611,
  32273. 'threequarters': 834,
  32274. 'Scedilla': 667,
  32275. 'lcaron': 400,
  32276. 'Kcommaaccent': 722,
  32277. 'Lacute': 611,
  32278. 'trademark': 1000,
  32279. 'edotaccent': 556,
  32280. 'Igrave': 278,
  32281. 'Imacron': 278,
  32282. 'Lcaron': 611,
  32283. 'onehalf': 834,
  32284. 'lessequal': 549,
  32285. 'ocircumflex': 611,
  32286. 'ntilde': 611,
  32287. 'Uhungarumlaut': 722,
  32288. 'Eacute': 667,
  32289. 'emacron': 556,
  32290. 'gbreve': 611,
  32291. 'onequarter': 834,
  32292. 'Scaron': 667,
  32293. 'Scommaaccent': 667,
  32294. 'Ohungarumlaut': 778,
  32295. 'degree': 400,
  32296. 'ograve': 611,
  32297. 'Ccaron': 722,
  32298. 'ugrave': 611,
  32299. 'radical': 549,
  32300. 'Dcaron': 722,
  32301. 'rcommaaccent': 389,
  32302. 'Ntilde': 722,
  32303. 'otilde': 611,
  32304. 'Rcommaaccent': 722,
  32305. 'Lcommaaccent': 611,
  32306. 'Atilde': 722,
  32307. 'Aogonek': 722,
  32308. 'Aring': 722,
  32309. 'Otilde': 778,
  32310. 'zdotaccent': 500,
  32311. 'Ecaron': 667,
  32312. 'Iogonek': 278,
  32313. 'kcommaaccent': 556,
  32314. 'minus': 584,
  32315. 'Icircumflex': 278,
  32316. 'ncaron': 611,
  32317. 'tcommaaccent': 333,
  32318. 'logicalnot': 584,
  32319. 'odieresis': 611,
  32320. 'udieresis': 611,
  32321. 'notequal': 549,
  32322. 'gcommaaccent': 611,
  32323. 'eth': 611,
  32324. 'zcaron': 500,
  32325. 'ncommaaccent': 611,
  32326. 'onesuperior': 333,
  32327. 'imacron': 278,
  32328. 'Euro': 556
  32329. },
  32330. 'Helvetica-Oblique' : {
  32331. 'space': 278,
  32332. 'exclam': 278,
  32333. 'quotedbl': 355,
  32334. 'numbersign': 556,
  32335. 'dollar': 556,
  32336. 'percent': 889,
  32337. 'ampersand': 667,
  32338. 'quoteright': 222,
  32339. 'parenleft': 333,
  32340. 'parenright': 333,
  32341. 'asterisk': 389,
  32342. 'plus': 584,
  32343. 'comma': 278,
  32344. 'hyphen': 333,
  32345. 'period': 278,
  32346. 'slash': 278,
  32347. 'zero': 556,
  32348. 'one': 556,
  32349. 'two': 556,
  32350. 'three': 556,
  32351. 'four': 556,
  32352. 'five': 556,
  32353. 'six': 556,
  32354. 'seven': 556,
  32355. 'eight': 556,
  32356. 'nine': 556,
  32357. 'colon': 278,
  32358. 'semicolon': 278,
  32359. 'less': 584,
  32360. 'equal': 584,
  32361. 'greater': 584,
  32362. 'question': 556,
  32363. 'at': 1015,
  32364. 'A': 667,
  32365. 'B': 667,
  32366. 'C': 722,
  32367. 'D': 722,
  32368. 'E': 667,
  32369. 'F': 611,
  32370. 'G': 778,
  32371. 'H': 722,
  32372. 'I': 278,
  32373. 'J': 500,
  32374. 'K': 667,
  32375. 'L': 556,
  32376. 'M': 833,
  32377. 'N': 722,
  32378. 'O': 778,
  32379. 'P': 667,
  32380. 'Q': 778,
  32381. 'R': 722,
  32382. 'S': 667,
  32383. 'T': 611,
  32384. 'U': 722,
  32385. 'V': 667,
  32386. 'W': 944,
  32387. 'X': 667,
  32388. 'Y': 667,
  32389. 'Z': 611,
  32390. 'bracketleft': 278,
  32391. 'backslash': 278,
  32392. 'bracketright': 278,
  32393. 'asciicircum': 469,
  32394. 'underscore': 556,
  32395. 'quoteleft': 222,
  32396. 'a': 556,
  32397. 'b': 556,
  32398. 'c': 500,
  32399. 'd': 556,
  32400. 'e': 556,
  32401. 'f': 278,
  32402. 'g': 556,
  32403. 'h': 556,
  32404. 'i': 222,
  32405. 'j': 222,
  32406. 'k': 500,
  32407. 'l': 222,
  32408. 'm': 833,
  32409. 'n': 556,
  32410. 'o': 556,
  32411. 'p': 556,
  32412. 'q': 556,
  32413. 'r': 333,
  32414. 's': 500,
  32415. 't': 278,
  32416. 'u': 556,
  32417. 'v': 500,
  32418. 'w': 722,
  32419. 'x': 500,
  32420. 'y': 500,
  32421. 'z': 500,
  32422. 'braceleft': 334,
  32423. 'bar': 260,
  32424. 'braceright': 334,
  32425. 'asciitilde': 584,
  32426. 'exclamdown': 333,
  32427. 'cent': 556,
  32428. 'sterling': 556,
  32429. 'fraction': 167,
  32430. 'yen': 556,
  32431. 'florin': 556,
  32432. 'section': 556,
  32433. 'currency': 556,
  32434. 'quotesingle': 191,
  32435. 'quotedblleft': 333,
  32436. 'guillemotleft': 556,
  32437. 'guilsinglleft': 333,
  32438. 'guilsinglright': 333,
  32439. 'fi': 500,
  32440. 'fl': 500,
  32441. 'endash': 556,
  32442. 'dagger': 556,
  32443. 'daggerdbl': 556,
  32444. 'periodcentered': 278,
  32445. 'paragraph': 537,
  32446. 'bullet': 350,
  32447. 'quotesinglbase': 222,
  32448. 'quotedblbase': 333,
  32449. 'quotedblright': 333,
  32450. 'guillemotright': 556,
  32451. 'ellipsis': 1000,
  32452. 'perthousand': 1000,
  32453. 'questiondown': 611,
  32454. 'grave': 333,
  32455. 'acute': 333,
  32456. 'circumflex': 333,
  32457. 'tilde': 333,
  32458. 'macron': 333,
  32459. 'breve': 333,
  32460. 'dotaccent': 333,
  32461. 'dieresis': 333,
  32462. 'ring': 333,
  32463. 'cedilla': 333,
  32464. 'hungarumlaut': 333,
  32465. 'ogonek': 333,
  32466. 'caron': 333,
  32467. 'emdash': 1000,
  32468. 'AE': 1000,
  32469. 'ordfeminine': 370,
  32470. 'Lslash': 556,
  32471. 'Oslash': 778,
  32472. 'OE': 1000,
  32473. 'ordmasculine': 365,
  32474. 'ae': 889,
  32475. 'dotlessi': 278,
  32476. 'lslash': 222,
  32477. 'oslash': 611,
  32478. 'oe': 944,
  32479. 'germandbls': 611,
  32480. 'Idieresis': 278,
  32481. 'eacute': 556,
  32482. 'abreve': 556,
  32483. 'uhungarumlaut': 556,
  32484. 'ecaron': 556,
  32485. 'Ydieresis': 667,
  32486. 'divide': 584,
  32487. 'Yacute': 667,
  32488. 'Acircumflex': 667,
  32489. 'aacute': 556,
  32490. 'Ucircumflex': 722,
  32491. 'yacute': 500,
  32492. 'scommaaccent': 500,
  32493. 'ecircumflex': 556,
  32494. 'Uring': 722,
  32495. 'Udieresis': 722,
  32496. 'aogonek': 556,
  32497. 'Uacute': 722,
  32498. 'uogonek': 556,
  32499. 'Edieresis': 667,
  32500. 'Dcroat': 722,
  32501. 'commaaccent': 250,
  32502. 'copyright': 737,
  32503. 'Emacron': 667,
  32504. 'ccaron': 500,
  32505. 'aring': 556,
  32506. 'Ncommaaccent': 722,
  32507. 'lacute': 222,
  32508. 'agrave': 556,
  32509. 'Tcommaaccent': 611,
  32510. 'Cacute': 722,
  32511. 'atilde': 556,
  32512. 'Edotaccent': 667,
  32513. 'scaron': 500,
  32514. 'scedilla': 500,
  32515. 'iacute': 278,
  32516. 'lozenge': 471,
  32517. 'Rcaron': 722,
  32518. 'Gcommaaccent': 778,
  32519. 'ucircumflex': 556,
  32520. 'acircumflex': 556,
  32521. 'Amacron': 667,
  32522. 'rcaron': 333,
  32523. 'ccedilla': 500,
  32524. 'Zdotaccent': 611,
  32525. 'Thorn': 667,
  32526. 'Omacron': 778,
  32527. 'Racute': 722,
  32528. 'Sacute': 667,
  32529. 'dcaron': 643,
  32530. 'Umacron': 722,
  32531. 'uring': 556,
  32532. 'threesuperior': 333,
  32533. 'Ograve': 778,
  32534. 'Agrave': 667,
  32535. 'Abreve': 667,
  32536. 'multiply': 584,
  32537. 'uacute': 556,
  32538. 'Tcaron': 611,
  32539. 'partialdiff': 476,
  32540. 'ydieresis': 500,
  32541. 'Nacute': 722,
  32542. 'icircumflex': 278,
  32543. 'Ecircumflex': 667,
  32544. 'adieresis': 556,
  32545. 'edieresis': 556,
  32546. 'cacute': 500,
  32547. 'nacute': 556,
  32548. 'umacron': 556,
  32549. 'Ncaron': 722,
  32550. 'Iacute': 278,
  32551. 'plusminus': 584,
  32552. 'brokenbar': 260,
  32553. 'registered': 737,
  32554. 'Gbreve': 778,
  32555. 'Idotaccent': 278,
  32556. 'summation': 600,
  32557. 'Egrave': 667,
  32558. 'racute': 333,
  32559. 'omacron': 556,
  32560. 'Zacute': 611,
  32561. 'Zcaron': 611,
  32562. 'greaterequal': 549,
  32563. 'Eth': 722,
  32564. 'Ccedilla': 722,
  32565. 'lcommaaccent': 222,
  32566. 'tcaron': 317,
  32567. 'eogonek': 556,
  32568. 'Uogonek': 722,
  32569. 'Aacute': 667,
  32570. 'Adieresis': 667,
  32571. 'egrave': 556,
  32572. 'zacute': 500,
  32573. 'iogonek': 222,
  32574. 'Oacute': 778,
  32575. 'oacute': 556,
  32576. 'amacron': 556,
  32577. 'sacute': 500,
  32578. 'idieresis': 278,
  32579. 'Ocircumflex': 778,
  32580. 'Ugrave': 722,
  32581. 'Delta': 612,
  32582. 'thorn': 556,
  32583. 'twosuperior': 333,
  32584. 'Odieresis': 778,
  32585. 'mu': 556,
  32586. 'igrave': 278,
  32587. 'ohungarumlaut': 556,
  32588. 'Eogonek': 667,
  32589. 'dcroat': 556,
  32590. 'threequarters': 834,
  32591. 'Scedilla': 667,
  32592. 'lcaron': 299,
  32593. 'Kcommaaccent': 667,
  32594. 'Lacute': 556,
  32595. 'trademark': 1000,
  32596. 'edotaccent': 556,
  32597. 'Igrave': 278,
  32598. 'Imacron': 278,
  32599. 'Lcaron': 556,
  32600. 'onehalf': 834,
  32601. 'lessequal': 549,
  32602. 'ocircumflex': 556,
  32603. 'ntilde': 556,
  32604. 'Uhungarumlaut': 722,
  32605. 'Eacute': 667,
  32606. 'emacron': 556,
  32607. 'gbreve': 556,
  32608. 'onequarter': 834,
  32609. 'Scaron': 667,
  32610. 'Scommaaccent': 667,
  32611. 'Ohungarumlaut': 778,
  32612. 'degree': 400,
  32613. 'ograve': 556,
  32614. 'Ccaron': 722,
  32615. 'ugrave': 556,
  32616. 'radical': 453,
  32617. 'Dcaron': 722,
  32618. 'rcommaaccent': 333,
  32619. 'Ntilde': 722,
  32620. 'otilde': 556,
  32621. 'Rcommaaccent': 722,
  32622. 'Lcommaaccent': 556,
  32623. 'Atilde': 667,
  32624. 'Aogonek': 667,
  32625. 'Aring': 667,
  32626. 'Otilde': 778,
  32627. 'zdotaccent': 500,
  32628. 'Ecaron': 667,
  32629. 'Iogonek': 278,
  32630. 'kcommaaccent': 500,
  32631. 'minus': 584,
  32632. 'Icircumflex': 278,
  32633. 'ncaron': 556,
  32634. 'tcommaaccent': 278,
  32635. 'logicalnot': 584,
  32636. 'odieresis': 556,
  32637. 'udieresis': 556,
  32638. 'notequal': 549,
  32639. 'gcommaaccent': 556,
  32640. 'eth': 556,
  32641. 'zcaron': 500,
  32642. 'ncommaaccent': 556,
  32643. 'onesuperior': 333,
  32644. 'imacron': 278,
  32645. 'Euro': 556
  32646. },
  32647. 'Symbol': {
  32648. 'space': 250,
  32649. 'exclam': 333,
  32650. 'universal': 713,
  32651. 'numbersign': 500,
  32652. 'existential': 549,
  32653. 'percent': 833,
  32654. 'ampersand': 778,
  32655. 'suchthat': 439,
  32656. 'parenleft': 333,
  32657. 'parenright': 333,
  32658. 'asteriskmath': 500,
  32659. 'plus': 549,
  32660. 'comma': 250,
  32661. 'minus': 549,
  32662. 'period': 250,
  32663. 'slash': 278,
  32664. 'zero': 500,
  32665. 'one': 500,
  32666. 'two': 500,
  32667. 'three': 500,
  32668. 'four': 500,
  32669. 'five': 500,
  32670. 'six': 500,
  32671. 'seven': 500,
  32672. 'eight': 500,
  32673. 'nine': 500,
  32674. 'colon': 278,
  32675. 'semicolon': 278,
  32676. 'less': 549,
  32677. 'equal': 549,
  32678. 'greater': 549,
  32679. 'question': 444,
  32680. 'congruent': 549,
  32681. 'Alpha': 722,
  32682. 'Beta': 667,
  32683. 'Chi': 722,
  32684. 'Delta': 612,
  32685. 'Epsilon': 611,
  32686. 'Phi': 763,
  32687. 'Gamma': 603,
  32688. 'Eta': 722,
  32689. 'Iota': 333,
  32690. 'theta1': 631,
  32691. 'Kappa': 722,
  32692. 'Lambda': 686,
  32693. 'Mu': 889,
  32694. 'Nu': 722,
  32695. 'Omicron': 722,
  32696. 'Pi': 768,
  32697. 'Theta': 741,
  32698. 'Rho': 556,
  32699. 'Sigma': 592,
  32700. 'Tau': 611,
  32701. 'Upsilon': 690,
  32702. 'sigma1': 439,
  32703. 'Omega': 768,
  32704. 'Xi': 645,
  32705. 'Psi': 795,
  32706. 'Zeta': 611,
  32707. 'bracketleft': 333,
  32708. 'therefore': 863,
  32709. 'bracketright': 333,
  32710. 'perpendicular': 658,
  32711. 'underscore': 500,
  32712. 'radicalex': 500,
  32713. 'alpha': 631,
  32714. 'beta': 549,
  32715. 'chi': 549,
  32716. 'delta': 494,
  32717. 'epsilon': 439,
  32718. 'phi': 521,
  32719. 'gamma': 411,
  32720. 'eta': 603,
  32721. 'iota': 329,
  32722. 'phi1': 603,
  32723. 'kappa': 549,
  32724. 'lambda': 549,
  32725. 'mu': 576,
  32726. 'nu': 521,
  32727. 'omicron': 549,
  32728. 'pi': 549,
  32729. 'theta': 521,
  32730. 'rho': 549,
  32731. 'sigma': 603,
  32732. 'tau': 439,
  32733. 'upsilon': 576,
  32734. 'omega1': 713,
  32735. 'omega': 686,
  32736. 'xi': 493,
  32737. 'psi': 686,
  32738. 'zeta': 494,
  32739. 'braceleft': 480,
  32740. 'bar': 200,
  32741. 'braceright': 480,
  32742. 'similar': 549,
  32743. 'Euro': 750,
  32744. 'Upsilon1': 620,
  32745. 'minute': 247,
  32746. 'lessequal': 549,
  32747. 'fraction': 167,
  32748. 'infinity': 713,
  32749. 'florin': 500,
  32750. 'club': 753,
  32751. 'diamond': 753,
  32752. 'heart': 753,
  32753. 'spade': 753,
  32754. 'arrowboth': 1042,
  32755. 'arrowleft': 987,
  32756. 'arrowup': 603,
  32757. 'arrowright': 987,
  32758. 'arrowdown': 603,
  32759. 'degree': 400,
  32760. 'plusminus': 549,
  32761. 'second': 411,
  32762. 'greaterequal': 549,
  32763. 'multiply': 549,
  32764. 'proportional': 713,
  32765. 'partialdiff': 494,
  32766. 'bullet': 460,
  32767. 'divide': 549,
  32768. 'notequal': 549,
  32769. 'equivalence': 549,
  32770. 'approxequal': 549,
  32771. 'ellipsis': 1000,
  32772. 'arrowvertex': 603,
  32773. 'arrowhorizex': 1000,
  32774. 'carriagereturn': 658,
  32775. 'aleph': 823,
  32776. 'Ifraktur': 686,
  32777. 'Rfraktur': 795,
  32778. 'weierstrass': 987,
  32779. 'circlemultiply': 768,
  32780. 'circleplus': 768,
  32781. 'emptyset': 823,
  32782. 'intersection': 768,
  32783. 'union': 768,
  32784. 'propersuperset': 713,
  32785. 'reflexsuperset': 713,
  32786. 'notsubset': 713,
  32787. 'propersubset': 713,
  32788. 'reflexsubset': 713,
  32789. 'element': 713,
  32790. 'notelement': 713,
  32791. 'angle': 768,
  32792. 'gradient': 713,
  32793. 'registerserif': 790,
  32794. 'copyrightserif': 790,
  32795. 'trademarkserif': 890,
  32796. 'product': 823,
  32797. 'radical': 549,
  32798. 'dotmath': 250,
  32799. 'logicalnot': 713,
  32800. 'logicaland': 603,
  32801. 'logicalor': 603,
  32802. 'arrowdblboth': 1042,
  32803. 'arrowdblleft': 987,
  32804. 'arrowdblup': 603,
  32805. 'arrowdblright': 987,
  32806. 'arrowdbldown': 603,
  32807. 'lozenge': 494,
  32808. 'angleleft': 329,
  32809. 'registersans': 790,
  32810. 'copyrightsans': 790,
  32811. 'trademarksans': 786,
  32812. 'summation': 713,
  32813. 'parenlefttp': 384,
  32814. 'parenleftex': 384,
  32815. 'parenleftbt': 384,
  32816. 'bracketlefttp': 384,
  32817. 'bracketleftex': 384,
  32818. 'bracketleftbt': 384,
  32819. 'bracelefttp': 494,
  32820. 'braceleftmid': 494,
  32821. 'braceleftbt': 494,
  32822. 'braceex': 494,
  32823. 'angleright': 329,
  32824. 'integral': 274,
  32825. 'integraltp': 686,
  32826. 'integralex': 686,
  32827. 'integralbt': 686,
  32828. 'parenrighttp': 384,
  32829. 'parenrightex': 384,
  32830. 'parenrightbt': 384,
  32831. 'bracketrighttp': 384,
  32832. 'bracketrightex': 384,
  32833. 'bracketrightbt': 384,
  32834. 'bracerighttp': 494,
  32835. 'bracerightmid': 494,
  32836. 'bracerightbt': 494,
  32837. 'apple': 790
  32838. },
  32839. 'Times-Roman': {
  32840. 'space': 250,
  32841. 'exclam': 333,
  32842. 'quotedbl': 408,
  32843. 'numbersign': 500,
  32844. 'dollar': 500,
  32845. 'percent': 833,
  32846. 'ampersand': 778,
  32847. 'quoteright': 333,
  32848. 'parenleft': 333,
  32849. 'parenright': 333,
  32850. 'asterisk': 500,
  32851. 'plus': 564,
  32852. 'comma': 250,
  32853. 'hyphen': 333,
  32854. 'period': 250,
  32855. 'slash': 278,
  32856. 'zero': 500,
  32857. 'one': 500,
  32858. 'two': 500,
  32859. 'three': 500,
  32860. 'four': 500,
  32861. 'five': 500,
  32862. 'six': 500,
  32863. 'seven': 500,
  32864. 'eight': 500,
  32865. 'nine': 500,
  32866. 'colon': 278,
  32867. 'semicolon': 278,
  32868. 'less': 564,
  32869. 'equal': 564,
  32870. 'greater': 564,
  32871. 'question': 444,
  32872. 'at': 921,
  32873. 'A': 722,
  32874. 'B': 667,
  32875. 'C': 667,
  32876. 'D': 722,
  32877. 'E': 611,
  32878. 'F': 556,
  32879. 'G': 722,
  32880. 'H': 722,
  32881. 'I': 333,
  32882. 'J': 389,
  32883. 'K': 722,
  32884. 'L': 611,
  32885. 'M': 889,
  32886. 'N': 722,
  32887. 'O': 722,
  32888. 'P': 556,
  32889. 'Q': 722,
  32890. 'R': 667,
  32891. 'S': 556,
  32892. 'T': 611,
  32893. 'U': 722,
  32894. 'V': 722,
  32895. 'W': 944,
  32896. 'X': 722,
  32897. 'Y': 722,
  32898. 'Z': 611,
  32899. 'bracketleft': 333,
  32900. 'backslash': 278,
  32901. 'bracketright': 333,
  32902. 'asciicircum': 469,
  32903. 'underscore': 500,
  32904. 'quoteleft': 333,
  32905. 'a': 444,
  32906. 'b': 500,
  32907. 'c': 444,
  32908. 'd': 500,
  32909. 'e': 444,
  32910. 'f': 333,
  32911. 'g': 500,
  32912. 'h': 500,
  32913. 'i': 278,
  32914. 'j': 278,
  32915. 'k': 500,
  32916. 'l': 278,
  32917. 'm': 778,
  32918. 'n': 500,
  32919. 'o': 500,
  32920. 'p': 500,
  32921. 'q': 500,
  32922. 'r': 333,
  32923. 's': 389,
  32924. 't': 278,
  32925. 'u': 500,
  32926. 'v': 500,
  32927. 'w': 722,
  32928. 'x': 500,
  32929. 'y': 500,
  32930. 'z': 444,
  32931. 'braceleft': 480,
  32932. 'bar': 200,
  32933. 'braceright': 480,
  32934. 'asciitilde': 541,
  32935. 'exclamdown': 333,
  32936. 'cent': 500,
  32937. 'sterling': 500,
  32938. 'fraction': 167,
  32939. 'yen': 500,
  32940. 'florin': 500,
  32941. 'section': 500,
  32942. 'currency': 500,
  32943. 'quotesingle': 180,
  32944. 'quotedblleft': 444,
  32945. 'guillemotleft': 500,
  32946. 'guilsinglleft': 333,
  32947. 'guilsinglright': 333,
  32948. 'fi': 556,
  32949. 'fl': 556,
  32950. 'endash': 500,
  32951. 'dagger': 500,
  32952. 'daggerdbl': 500,
  32953. 'periodcentered': 250,
  32954. 'paragraph': 453,
  32955. 'bullet': 350,
  32956. 'quotesinglbase': 333,
  32957. 'quotedblbase': 444,
  32958. 'quotedblright': 444,
  32959. 'guillemotright': 500,
  32960. 'ellipsis': 1000,
  32961. 'perthousand': 1000,
  32962. 'questiondown': 444,
  32963. 'grave': 333,
  32964. 'acute': 333,
  32965. 'circumflex': 333,
  32966. 'tilde': 333,
  32967. 'macron': 333,
  32968. 'breve': 333,
  32969. 'dotaccent': 333,
  32970. 'dieresis': 333,
  32971. 'ring': 333,
  32972. 'cedilla': 333,
  32973. 'hungarumlaut': 333,
  32974. 'ogonek': 333,
  32975. 'caron': 333,
  32976. 'emdash': 1000,
  32977. 'AE': 889,
  32978. 'ordfeminine': 276,
  32979. 'Lslash': 611,
  32980. 'Oslash': 722,
  32981. 'OE': 889,
  32982. 'ordmasculine': 310,
  32983. 'ae': 667,
  32984. 'dotlessi': 278,
  32985. 'lslash': 278,
  32986. 'oslash': 500,
  32987. 'oe': 722,
  32988. 'germandbls': 500,
  32989. 'Idieresis': 333,
  32990. 'eacute': 444,
  32991. 'abreve': 444,
  32992. 'uhungarumlaut': 500,
  32993. 'ecaron': 444,
  32994. 'Ydieresis': 722,
  32995. 'divide': 564,
  32996. 'Yacute': 722,
  32997. 'Acircumflex': 722,
  32998. 'aacute': 444,
  32999. 'Ucircumflex': 722,
  33000. 'yacute': 500,
  33001. 'scommaaccent': 389,
  33002. 'ecircumflex': 444,
  33003. 'Uring': 722,
  33004. 'Udieresis': 722,
  33005. 'aogonek': 444,
  33006. 'Uacute': 722,
  33007. 'uogonek': 500,
  33008. 'Edieresis': 611,
  33009. 'Dcroat': 722,
  33010. 'commaaccent': 250,
  33011. 'copyright': 760,
  33012. 'Emacron': 611,
  33013. 'ccaron': 444,
  33014. 'aring': 444,
  33015. 'Ncommaaccent': 722,
  33016. 'lacute': 278,
  33017. 'agrave': 444,
  33018. 'Tcommaaccent': 611,
  33019. 'Cacute': 667,
  33020. 'atilde': 444,
  33021. 'Edotaccent': 611,
  33022. 'scaron': 389,
  33023. 'scedilla': 389,
  33024. 'iacute': 278,
  33025. 'lozenge': 471,
  33026. 'Rcaron': 667,
  33027. 'Gcommaaccent': 722,
  33028. 'ucircumflex': 500,
  33029. 'acircumflex': 444,
  33030. 'Amacron': 722,
  33031. 'rcaron': 333,
  33032. 'ccedilla': 444,
  33033. 'Zdotaccent': 611,
  33034. 'Thorn': 556,
  33035. 'Omacron': 722,
  33036. 'Racute': 667,
  33037. 'Sacute': 556,
  33038. 'dcaron': 588,
  33039. 'Umacron': 722,
  33040. 'uring': 500,
  33041. 'threesuperior': 300,
  33042. 'Ograve': 722,
  33043. 'Agrave': 722,
  33044. 'Abreve': 722,
  33045. 'multiply': 564,
  33046. 'uacute': 500,
  33047. 'Tcaron': 611,
  33048. 'partialdiff': 476,
  33049. 'ydieresis': 500,
  33050. 'Nacute': 722,
  33051. 'icircumflex': 278,
  33052. 'Ecircumflex': 611,
  33053. 'adieresis': 444,
  33054. 'edieresis': 444,
  33055. 'cacute': 444,
  33056. 'nacute': 500,
  33057. 'umacron': 500,
  33058. 'Ncaron': 722,
  33059. 'Iacute': 333,
  33060. 'plusminus': 564,
  33061. 'brokenbar': 200,
  33062. 'registered': 760,
  33063. 'Gbreve': 722,
  33064. 'Idotaccent': 333,
  33065. 'summation': 600,
  33066. 'Egrave': 611,
  33067. 'racute': 333,
  33068. 'omacron': 500,
  33069. 'Zacute': 611,
  33070. 'Zcaron': 611,
  33071. 'greaterequal': 549,
  33072. 'Eth': 722,
  33073. 'Ccedilla': 667,
  33074. 'lcommaaccent': 278,
  33075. 'tcaron': 326,
  33076. 'eogonek': 444,
  33077. 'Uogonek': 722,
  33078. 'Aacute': 722,
  33079. 'Adieresis': 722,
  33080. 'egrave': 444,
  33081. 'zacute': 444,
  33082. 'iogonek': 278,
  33083. 'Oacute': 722,
  33084. 'oacute': 500,
  33085. 'amacron': 444,
  33086. 'sacute': 389,
  33087. 'idieresis': 278,
  33088. 'Ocircumflex': 722,
  33089. 'Ugrave': 722,
  33090. 'Delta': 612,
  33091. 'thorn': 500,
  33092. 'twosuperior': 300,
  33093. 'Odieresis': 722,
  33094. 'mu': 500,
  33095. 'igrave': 278,
  33096. 'ohungarumlaut': 500,
  33097. 'Eogonek': 611,
  33098. 'dcroat': 500,
  33099. 'threequarters': 750,
  33100. 'Scedilla': 556,
  33101. 'lcaron': 344,
  33102. 'Kcommaaccent': 722,
  33103. 'Lacute': 611,
  33104. 'trademark': 980,
  33105. 'edotaccent': 444,
  33106. 'Igrave': 333,
  33107. 'Imacron': 333,
  33108. 'Lcaron': 611,
  33109. 'onehalf': 750,
  33110. 'lessequal': 549,
  33111. 'ocircumflex': 500,
  33112. 'ntilde': 500,
  33113. 'Uhungarumlaut': 722,
  33114. 'Eacute': 611,
  33115. 'emacron': 444,
  33116. 'gbreve': 500,
  33117. 'onequarter': 750,
  33118. 'Scaron': 556,
  33119. 'Scommaaccent': 556,
  33120. 'Ohungarumlaut': 722,
  33121. 'degree': 400,
  33122. 'ograve': 500,
  33123. 'Ccaron': 667,
  33124. 'ugrave': 500,
  33125. 'radical': 453,
  33126. 'Dcaron': 722,
  33127. 'rcommaaccent': 333,
  33128. 'Ntilde': 722,
  33129. 'otilde': 500,
  33130. 'Rcommaaccent': 667,
  33131. 'Lcommaaccent': 611,
  33132. 'Atilde': 722,
  33133. 'Aogonek': 722,
  33134. 'Aring': 722,
  33135. 'Otilde': 722,
  33136. 'zdotaccent': 444,
  33137. 'Ecaron': 611,
  33138. 'Iogonek': 333,
  33139. 'kcommaaccent': 500,
  33140. 'minus': 564,
  33141. 'Icircumflex': 333,
  33142. 'ncaron': 500,
  33143. 'tcommaaccent': 278,
  33144. 'logicalnot': 564,
  33145. 'odieresis': 500,
  33146. 'udieresis': 500,
  33147. 'notequal': 549,
  33148. 'gcommaaccent': 500,
  33149. 'eth': 500,
  33150. 'zcaron': 444,
  33151. 'ncommaaccent': 500,
  33152. 'onesuperior': 300,
  33153. 'imacron': 278,
  33154. 'Euro': 500
  33155. },
  33156. 'Times-Bold': {
  33157. 'space': 250,
  33158. 'exclam': 333,
  33159. 'quotedbl': 555,
  33160. 'numbersign': 500,
  33161. 'dollar': 500,
  33162. 'percent': 1000,
  33163. 'ampersand': 833,
  33164. 'quoteright': 333,
  33165. 'parenleft': 333,
  33166. 'parenright': 333,
  33167. 'asterisk': 500,
  33168. 'plus': 570,
  33169. 'comma': 250,
  33170. 'hyphen': 333,
  33171. 'period': 250,
  33172. 'slash': 278,
  33173. 'zero': 500,
  33174. 'one': 500,
  33175. 'two': 500,
  33176. 'three': 500,
  33177. 'four': 500,
  33178. 'five': 500,
  33179. 'six': 500,
  33180. 'seven': 500,
  33181. 'eight': 500,
  33182. 'nine': 500,
  33183. 'colon': 333,
  33184. 'semicolon': 333,
  33185. 'less': 570,
  33186. 'equal': 570,
  33187. 'greater': 570,
  33188. 'question': 500,
  33189. 'at': 930,
  33190. 'A': 722,
  33191. 'B': 667,
  33192. 'C': 722,
  33193. 'D': 722,
  33194. 'E': 667,
  33195. 'F': 611,
  33196. 'G': 778,
  33197. 'H': 778,
  33198. 'I': 389,
  33199. 'J': 500,
  33200. 'K': 778,
  33201. 'L': 667,
  33202. 'M': 944,
  33203. 'N': 722,
  33204. 'O': 778,
  33205. 'P': 611,
  33206. 'Q': 778,
  33207. 'R': 722,
  33208. 'S': 556,
  33209. 'T': 667,
  33210. 'U': 722,
  33211. 'V': 722,
  33212. 'W': 1000,
  33213. 'X': 722,
  33214. 'Y': 722,
  33215. 'Z': 667,
  33216. 'bracketleft': 333,
  33217. 'backslash': 278,
  33218. 'bracketright': 333,
  33219. 'asciicircum': 581,
  33220. 'underscore': 500,
  33221. 'quoteleft': 333,
  33222. 'a': 500,
  33223. 'b': 556,
  33224. 'c': 444,
  33225. 'd': 556,
  33226. 'e': 444,
  33227. 'f': 333,
  33228. 'g': 500,
  33229. 'h': 556,
  33230. 'i': 278,
  33231. 'j': 333,
  33232. 'k': 556,
  33233. 'l': 278,
  33234. 'm': 833,
  33235. 'n': 556,
  33236. 'o': 500,
  33237. 'p': 556,
  33238. 'q': 556,
  33239. 'r': 444,
  33240. 's': 389,
  33241. 't': 333,
  33242. 'u': 556,
  33243. 'v': 500,
  33244. 'w': 722,
  33245. 'x': 500,
  33246. 'y': 500,
  33247. 'z': 444,
  33248. 'braceleft': 394,
  33249. 'bar': 220,
  33250. 'braceright': 394,
  33251. 'asciitilde': 520,
  33252. 'exclamdown': 333,
  33253. 'cent': 500,
  33254. 'sterling': 500,
  33255. 'fraction': 167,
  33256. 'yen': 500,
  33257. 'florin': 500,
  33258. 'section': 500,
  33259. 'currency': 500,
  33260. 'quotesingle': 278,
  33261. 'quotedblleft': 500,
  33262. 'guillemotleft': 500,
  33263. 'guilsinglleft': 333,
  33264. 'guilsinglright': 333,
  33265. 'fi': 556,
  33266. 'fl': 556,
  33267. 'endash': 500,
  33268. 'dagger': 500,
  33269. 'daggerdbl': 500,
  33270. 'periodcentered': 250,
  33271. 'paragraph': 540,
  33272. 'bullet': 350,
  33273. 'quotesinglbase': 333,
  33274. 'quotedblbase': 500,
  33275. 'quotedblright': 500,
  33276. 'guillemotright': 500,
  33277. 'ellipsis': 1000,
  33278. 'perthousand': 1000,
  33279. 'questiondown': 500,
  33280. 'grave': 333,
  33281. 'acute': 333,
  33282. 'circumflex': 333,
  33283. 'tilde': 333,
  33284. 'macron': 333,
  33285. 'breve': 333,
  33286. 'dotaccent': 333,
  33287. 'dieresis': 333,
  33288. 'ring': 333,
  33289. 'cedilla': 333,
  33290. 'hungarumlaut': 333,
  33291. 'ogonek': 333,
  33292. 'caron': 333,
  33293. 'emdash': 1000,
  33294. 'AE': 1000,
  33295. 'ordfeminine': 300,
  33296. 'Lslash': 667,
  33297. 'Oslash': 778,
  33298. 'OE': 1000,
  33299. 'ordmasculine': 330,
  33300. 'ae': 722,
  33301. 'dotlessi': 278,
  33302. 'lslash': 278,
  33303. 'oslash': 500,
  33304. 'oe': 722,
  33305. 'germandbls': 556,
  33306. 'Idieresis': 389,
  33307. 'eacute': 444,
  33308. 'abreve': 500,
  33309. 'uhungarumlaut': 556,
  33310. 'ecaron': 444,
  33311. 'Ydieresis': 722,
  33312. 'divide': 570,
  33313. 'Yacute': 722,
  33314. 'Acircumflex': 722,
  33315. 'aacute': 500,
  33316. 'Ucircumflex': 722,
  33317. 'yacute': 500,
  33318. 'scommaaccent': 389,
  33319. 'ecircumflex': 444,
  33320. 'Uring': 722,
  33321. 'Udieresis': 722,
  33322. 'aogonek': 500,
  33323. 'Uacute': 722,
  33324. 'uogonek': 556,
  33325. 'Edieresis': 667,
  33326. 'Dcroat': 722,
  33327. 'commaaccent': 250,
  33328. 'copyright': 747,
  33329. 'Emacron': 667,
  33330. 'ccaron': 444,
  33331. 'aring': 500,
  33332. 'Ncommaaccent': 722,
  33333. 'lacute': 278,
  33334. 'agrave': 500,
  33335. 'Tcommaaccent': 667,
  33336. 'Cacute': 722,
  33337. 'atilde': 500,
  33338. 'Edotaccent': 667,
  33339. 'scaron': 389,
  33340. 'scedilla': 389,
  33341. 'iacute': 278,
  33342. 'lozenge': 494,
  33343. 'Rcaron': 722,
  33344. 'Gcommaaccent': 778,
  33345. 'ucircumflex': 556,
  33346. 'acircumflex': 500,
  33347. 'Amacron': 722,
  33348. 'rcaron': 444,
  33349. 'ccedilla': 444,
  33350. 'Zdotaccent': 667,
  33351. 'Thorn': 611,
  33352. 'Omacron': 778,
  33353. 'Racute': 722,
  33354. 'Sacute': 556,
  33355. 'dcaron': 672,
  33356. 'Umacron': 722,
  33357. 'uring': 556,
  33358. 'threesuperior': 300,
  33359. 'Ograve': 778,
  33360. 'Agrave': 722,
  33361. 'Abreve': 722,
  33362. 'multiply': 570,
  33363. 'uacute': 556,
  33364. 'Tcaron': 667,
  33365. 'partialdiff': 494,
  33366. 'ydieresis': 500,
  33367. 'Nacute': 722,
  33368. 'icircumflex': 278,
  33369. 'Ecircumflex': 667,
  33370. 'adieresis': 500,
  33371. 'edieresis': 444,
  33372. 'cacute': 444,
  33373. 'nacute': 556,
  33374. 'umacron': 556,
  33375. 'Ncaron': 722,
  33376. 'Iacute': 389,
  33377. 'plusminus': 570,
  33378. 'brokenbar': 220,
  33379. 'registered': 747,
  33380. 'Gbreve': 778,
  33381. 'Idotaccent': 389,
  33382. 'summation': 600,
  33383. 'Egrave': 667,
  33384. 'racute': 444,
  33385. 'omacron': 500,
  33386. 'Zacute': 667,
  33387. 'Zcaron': 667,
  33388. 'greaterequal': 549,
  33389. 'Eth': 722,
  33390. 'Ccedilla': 722,
  33391. 'lcommaaccent': 278,
  33392. 'tcaron': 416,
  33393. 'eogonek': 444,
  33394. 'Uogonek': 722,
  33395. 'Aacute': 722,
  33396. 'Adieresis': 722,
  33397. 'egrave': 444,
  33398. 'zacute': 444,
  33399. 'iogonek': 278,
  33400. 'Oacute': 778,
  33401. 'oacute': 500,
  33402. 'amacron': 500,
  33403. 'sacute': 389,
  33404. 'idieresis': 278,
  33405. 'Ocircumflex': 778,
  33406. 'Ugrave': 722,
  33407. 'Delta': 612,
  33408. 'thorn': 556,
  33409. 'twosuperior': 300,
  33410. 'Odieresis': 778,
  33411. 'mu': 556,
  33412. 'igrave': 278,
  33413. 'ohungarumlaut': 500,
  33414. 'Eogonek': 667,
  33415. 'dcroat': 556,
  33416. 'threequarters': 750,
  33417. 'Scedilla': 556,
  33418. 'lcaron': 394,
  33419. 'Kcommaaccent': 778,
  33420. 'Lacute': 667,
  33421. 'trademark': 1000,
  33422. 'edotaccent': 444,
  33423. 'Igrave': 389,
  33424. 'Imacron': 389,
  33425. 'Lcaron': 667,
  33426. 'onehalf': 750,
  33427. 'lessequal': 549,
  33428. 'ocircumflex': 500,
  33429. 'ntilde': 556,
  33430. 'Uhungarumlaut': 722,
  33431. 'Eacute': 667,
  33432. 'emacron': 444,
  33433. 'gbreve': 500,
  33434. 'onequarter': 750,
  33435. 'Scaron': 556,
  33436. 'Scommaaccent': 556,
  33437. 'Ohungarumlaut': 778,
  33438. 'degree': 400,
  33439. 'ograve': 500,
  33440. 'Ccaron': 722,
  33441. 'ugrave': 556,
  33442. 'radical': 549,
  33443. 'Dcaron': 722,
  33444. 'rcommaaccent': 444,
  33445. 'Ntilde': 722,
  33446. 'otilde': 500,
  33447. 'Rcommaaccent': 722,
  33448. 'Lcommaaccent': 667,
  33449. 'Atilde': 722,
  33450. 'Aogonek': 722,
  33451. 'Aring': 722,
  33452. 'Otilde': 778,
  33453. 'zdotaccent': 444,
  33454. 'Ecaron': 667,
  33455. 'Iogonek': 389,
  33456. 'kcommaaccent': 556,
  33457. 'minus': 570,
  33458. 'Icircumflex': 389,
  33459. 'ncaron': 556,
  33460. 'tcommaaccent': 333,
  33461. 'logicalnot': 570,
  33462. 'odieresis': 500,
  33463. 'udieresis': 556,
  33464. 'notequal': 549,
  33465. 'gcommaaccent': 500,
  33466. 'eth': 500,
  33467. 'zcaron': 444,
  33468. 'ncommaaccent': 556,
  33469. 'onesuperior': 300,
  33470. 'imacron': 278,
  33471. 'Euro': 500
  33472. },
  33473. 'Times-BoldItalic': {
  33474. 'space': 250,
  33475. 'exclam': 389,
  33476. 'quotedbl': 555,
  33477. 'numbersign': 500,
  33478. 'dollar': 500,
  33479. 'percent': 833,
  33480. 'ampersand': 778,
  33481. 'quoteright': 333,
  33482. 'parenleft': 333,
  33483. 'parenright': 333,
  33484. 'asterisk': 500,
  33485. 'plus': 570,
  33486. 'comma': 250,
  33487. 'hyphen': 333,
  33488. 'period': 250,
  33489. 'slash': 278,
  33490. 'zero': 500,
  33491. 'one': 500,
  33492. 'two': 500,
  33493. 'three': 500,
  33494. 'four': 500,
  33495. 'five': 500,
  33496. 'six': 500,
  33497. 'seven': 500,
  33498. 'eight': 500,
  33499. 'nine': 500,
  33500. 'colon': 333,
  33501. 'semicolon': 333,
  33502. 'less': 570,
  33503. 'equal': 570,
  33504. 'greater': 570,
  33505. 'question': 500,
  33506. 'at': 832,
  33507. 'A': 667,
  33508. 'B': 667,
  33509. 'C': 667,
  33510. 'D': 722,
  33511. 'E': 667,
  33512. 'F': 667,
  33513. 'G': 722,
  33514. 'H': 778,
  33515. 'I': 389,
  33516. 'J': 500,
  33517. 'K': 667,
  33518. 'L': 611,
  33519. 'M': 889,
  33520. 'N': 722,
  33521. 'O': 722,
  33522. 'P': 611,
  33523. 'Q': 722,
  33524. 'R': 667,
  33525. 'S': 556,
  33526. 'T': 611,
  33527. 'U': 722,
  33528. 'V': 667,
  33529. 'W': 889,
  33530. 'X': 667,
  33531. 'Y': 611,
  33532. 'Z': 611,
  33533. 'bracketleft': 333,
  33534. 'backslash': 278,
  33535. 'bracketright': 333,
  33536. 'asciicircum': 570,
  33537. 'underscore': 500,
  33538. 'quoteleft': 333,
  33539. 'a': 500,
  33540. 'b': 500,
  33541. 'c': 444,
  33542. 'd': 500,
  33543. 'e': 444,
  33544. 'f': 333,
  33545. 'g': 500,
  33546. 'h': 556,
  33547. 'i': 278,
  33548. 'j': 278,
  33549. 'k': 500,
  33550. 'l': 278,
  33551. 'm': 778,
  33552. 'n': 556,
  33553. 'o': 500,
  33554. 'p': 500,
  33555. 'q': 500,
  33556. 'r': 389,
  33557. 's': 389,
  33558. 't': 278,
  33559. 'u': 556,
  33560. 'v': 444,
  33561. 'w': 667,
  33562. 'x': 500,
  33563. 'y': 444,
  33564. 'z': 389,
  33565. 'braceleft': 348,
  33566. 'bar': 220,
  33567. 'braceright': 348,
  33568. 'asciitilde': 570,
  33569. 'exclamdown': 389,
  33570. 'cent': 500,
  33571. 'sterling': 500,
  33572. 'fraction': 167,
  33573. 'yen': 500,
  33574. 'florin': 500,
  33575. 'section': 500,
  33576. 'currency': 500,
  33577. 'quotesingle': 278,
  33578. 'quotedblleft': 500,
  33579. 'guillemotleft': 500,
  33580. 'guilsinglleft': 333,
  33581. 'guilsinglright': 333,
  33582. 'fi': 556,
  33583. 'fl': 556,
  33584. 'endash': 500,
  33585. 'dagger': 500,
  33586. 'daggerdbl': 500,
  33587. 'periodcentered': 250,
  33588. 'paragraph': 500,
  33589. 'bullet': 350,
  33590. 'quotesinglbase': 333,
  33591. 'quotedblbase': 500,
  33592. 'quotedblright': 500,
  33593. 'guillemotright': 500,
  33594. 'ellipsis': 1000,
  33595. 'perthousand': 1000,
  33596. 'questiondown': 500,
  33597. 'grave': 333,
  33598. 'acute': 333,
  33599. 'circumflex': 333,
  33600. 'tilde': 333,
  33601. 'macron': 333,
  33602. 'breve': 333,
  33603. 'dotaccent': 333,
  33604. 'dieresis': 333,
  33605. 'ring': 333,
  33606. 'cedilla': 333,
  33607. 'hungarumlaut': 333,
  33608. 'ogonek': 333,
  33609. 'caron': 333,
  33610. 'emdash': 1000,
  33611. 'AE': 944,
  33612. 'ordfeminine': 266,
  33613. 'Lslash': 611,
  33614. 'Oslash': 722,
  33615. 'OE': 944,
  33616. 'ordmasculine': 300,
  33617. 'ae': 722,
  33618. 'dotlessi': 278,
  33619. 'lslash': 278,
  33620. 'oslash': 500,
  33621. 'oe': 722,
  33622. 'germandbls': 500,
  33623. 'Idieresis': 389,
  33624. 'eacute': 444,
  33625. 'abreve': 500,
  33626. 'uhungarumlaut': 556,
  33627. 'ecaron': 444,
  33628. 'Ydieresis': 611,
  33629. 'divide': 570,
  33630. 'Yacute': 611,
  33631. 'Acircumflex': 667,
  33632. 'aacute': 500,
  33633. 'Ucircumflex': 722,
  33634. 'yacute': 444,
  33635. 'scommaaccent': 389,
  33636. 'ecircumflex': 444,
  33637. 'Uring': 722,
  33638. 'Udieresis': 722,
  33639. 'aogonek': 500,
  33640. 'Uacute': 722,
  33641. 'uogonek': 556,
  33642. 'Edieresis': 667,
  33643. 'Dcroat': 722,
  33644. 'commaaccent': 250,
  33645. 'copyright': 747,
  33646. 'Emacron': 667,
  33647. 'ccaron': 444,
  33648. 'aring': 500,
  33649. 'Ncommaaccent': 722,
  33650. 'lacute': 278,
  33651. 'agrave': 500,
  33652. 'Tcommaaccent': 611,
  33653. 'Cacute': 667,
  33654. 'atilde': 500,
  33655. 'Edotaccent': 667,
  33656. 'scaron': 389,
  33657. 'scedilla': 389,
  33658. 'iacute': 278,
  33659. 'lozenge': 494,
  33660. 'Rcaron': 667,
  33661. 'Gcommaaccent': 722,
  33662. 'ucircumflex': 556,
  33663. 'acircumflex': 500,
  33664. 'Amacron': 667,
  33665. 'rcaron': 389,
  33666. 'ccedilla': 444,
  33667. 'Zdotaccent': 611,
  33668. 'Thorn': 611,
  33669. 'Omacron': 722,
  33670. 'Racute': 667,
  33671. 'Sacute': 556,
  33672. 'dcaron': 608,
  33673. 'Umacron': 722,
  33674. 'uring': 556,
  33675. 'threesuperior': 300,
  33676. 'Ograve': 722,
  33677. 'Agrave': 667,
  33678. 'Abreve': 667,
  33679. 'multiply': 570,
  33680. 'uacute': 556,
  33681. 'Tcaron': 611,
  33682. 'partialdiff': 494,
  33683. 'ydieresis': 444,
  33684. 'Nacute': 722,
  33685. 'icircumflex': 278,
  33686. 'Ecircumflex': 667,
  33687. 'adieresis': 500,
  33688. 'edieresis': 444,
  33689. 'cacute': 444,
  33690. 'nacute': 556,
  33691. 'umacron': 556,
  33692. 'Ncaron': 722,
  33693. 'Iacute': 389,
  33694. 'plusminus': 570,
  33695. 'brokenbar': 220,
  33696. 'registered': 747,
  33697. 'Gbreve': 722,
  33698. 'Idotaccent': 389,
  33699. 'summation': 600,
  33700. 'Egrave': 667,
  33701. 'racute': 389,
  33702. 'omacron': 500,
  33703. 'Zacute': 611,
  33704. 'Zcaron': 611,
  33705. 'greaterequal': 549,
  33706. 'Eth': 722,
  33707. 'Ccedilla': 667,
  33708. 'lcommaaccent': 278,
  33709. 'tcaron': 366,
  33710. 'eogonek': 444,
  33711. 'Uogonek': 722,
  33712. 'Aacute': 667,
  33713. 'Adieresis': 667,
  33714. 'egrave': 444,
  33715. 'zacute': 389,
  33716. 'iogonek': 278,
  33717. 'Oacute': 722,
  33718. 'oacute': 500,
  33719. 'amacron': 500,
  33720. 'sacute': 389,
  33721. 'idieresis': 278,
  33722. 'Ocircumflex': 722,
  33723. 'Ugrave': 722,
  33724. 'Delta': 612,
  33725. 'thorn': 500,
  33726. 'twosuperior': 300,
  33727. 'Odieresis': 722,
  33728. 'mu': 576,
  33729. 'igrave': 278,
  33730. 'ohungarumlaut': 500,
  33731. 'Eogonek': 667,
  33732. 'dcroat': 500,
  33733. 'threequarters': 750,
  33734. 'Scedilla': 556,
  33735. 'lcaron': 382,
  33736. 'Kcommaaccent': 667,
  33737. 'Lacute': 611,
  33738. 'trademark': 1000,
  33739. 'edotaccent': 444,
  33740. 'Igrave': 389,
  33741. 'Imacron': 389,
  33742. 'Lcaron': 611,
  33743. 'onehalf': 750,
  33744. 'lessequal': 549,
  33745. 'ocircumflex': 500,
  33746. 'ntilde': 556,
  33747. 'Uhungarumlaut': 722,
  33748. 'Eacute': 667,
  33749. 'emacron': 444,
  33750. 'gbreve': 500,
  33751. 'onequarter': 750,
  33752. 'Scaron': 556,
  33753. 'Scommaaccent': 556,
  33754. 'Ohungarumlaut': 722,
  33755. 'degree': 400,
  33756. 'ograve': 500,
  33757. 'Ccaron': 667,
  33758. 'ugrave': 556,
  33759. 'radical': 549,
  33760. 'Dcaron': 722,
  33761. 'rcommaaccent': 389,
  33762. 'Ntilde': 722,
  33763. 'otilde': 500,
  33764. 'Rcommaaccent': 667,
  33765. 'Lcommaaccent': 611,
  33766. 'Atilde': 667,
  33767. 'Aogonek': 667,
  33768. 'Aring': 667,
  33769. 'Otilde': 722,
  33770. 'zdotaccent': 389,
  33771. 'Ecaron': 667,
  33772. 'Iogonek': 389,
  33773. 'kcommaaccent': 500,
  33774. 'minus': 606,
  33775. 'Icircumflex': 389,
  33776. 'ncaron': 556,
  33777. 'tcommaaccent': 278,
  33778. 'logicalnot': 606,
  33779. 'odieresis': 500,
  33780. 'udieresis': 556,
  33781. 'notequal': 549,
  33782. 'gcommaaccent': 500,
  33783. 'eth': 500,
  33784. 'zcaron': 389,
  33785. 'ncommaaccent': 556,
  33786. 'onesuperior': 300,
  33787. 'imacron': 278,
  33788. 'Euro': 500
  33789. },
  33790. 'Times-Italic': {
  33791. 'space': 250,
  33792. 'exclam': 333,
  33793. 'quotedbl': 420,
  33794. 'numbersign': 500,
  33795. 'dollar': 500,
  33796. 'percent': 833,
  33797. 'ampersand': 778,
  33798. 'quoteright': 333,
  33799. 'parenleft': 333,
  33800. 'parenright': 333,
  33801. 'asterisk': 500,
  33802. 'plus': 675,
  33803. 'comma': 250,
  33804. 'hyphen': 333,
  33805. 'period': 250,
  33806. 'slash': 278,
  33807. 'zero': 500,
  33808. 'one': 500,
  33809. 'two': 500,
  33810. 'three': 500,
  33811. 'four': 500,
  33812. 'five': 500,
  33813. 'six': 500,
  33814. 'seven': 500,
  33815. 'eight': 500,
  33816. 'nine': 500,
  33817. 'colon': 333,
  33818. 'semicolon': 333,
  33819. 'less': 675,
  33820. 'equal': 675,
  33821. 'greater': 675,
  33822. 'question': 500,
  33823. 'at': 920,
  33824. 'A': 611,
  33825. 'B': 611,
  33826. 'C': 667,
  33827. 'D': 722,
  33828. 'E': 611,
  33829. 'F': 611,
  33830. 'G': 722,
  33831. 'H': 722,
  33832. 'I': 333,
  33833. 'J': 444,
  33834. 'K': 667,
  33835. 'L': 556,
  33836. 'M': 833,
  33837. 'N': 667,
  33838. 'O': 722,
  33839. 'P': 611,
  33840. 'Q': 722,
  33841. 'R': 611,
  33842. 'S': 500,
  33843. 'T': 556,
  33844. 'U': 722,
  33845. 'V': 611,
  33846. 'W': 833,
  33847. 'X': 611,
  33848. 'Y': 556,
  33849. 'Z': 556,
  33850. 'bracketleft': 389,
  33851. 'backslash': 278,
  33852. 'bracketright': 389,
  33853. 'asciicircum': 422,
  33854. 'underscore': 500,
  33855. 'quoteleft': 333,
  33856. 'a': 500,
  33857. 'b': 500,
  33858. 'c': 444,
  33859. 'd': 500,
  33860. 'e': 444,
  33861. 'f': 278,
  33862. 'g': 500,
  33863. 'h': 500,
  33864. 'i': 278,
  33865. 'j': 278,
  33866. 'k': 444,
  33867. 'l': 278,
  33868. 'm': 722,
  33869. 'n': 500,
  33870. 'o': 500,
  33871. 'p': 500,
  33872. 'q': 500,
  33873. 'r': 389,
  33874. 's': 389,
  33875. 't': 278,
  33876. 'u': 500,
  33877. 'v': 444,
  33878. 'w': 667,
  33879. 'x': 444,
  33880. 'y': 444,
  33881. 'z': 389,
  33882. 'braceleft': 400,
  33883. 'bar': 275,
  33884. 'braceright': 400,
  33885. 'asciitilde': 541,
  33886. 'exclamdown': 389,
  33887. 'cent': 500,
  33888. 'sterling': 500,
  33889. 'fraction': 167,
  33890. 'yen': 500,
  33891. 'florin': 500,
  33892. 'section': 500,
  33893. 'currency': 500,
  33894. 'quotesingle': 214,
  33895. 'quotedblleft': 556,
  33896. 'guillemotleft': 500,
  33897. 'guilsinglleft': 333,
  33898. 'guilsinglright': 333,
  33899. 'fi': 500,
  33900. 'fl': 500,
  33901. 'endash': 500,
  33902. 'dagger': 500,
  33903. 'daggerdbl': 500,
  33904. 'periodcentered': 250,
  33905. 'paragraph': 523,
  33906. 'bullet': 350,
  33907. 'quotesinglbase': 333,
  33908. 'quotedblbase': 556,
  33909. 'quotedblright': 556,
  33910. 'guillemotright': 500,
  33911. 'ellipsis': 889,
  33912. 'perthousand': 1000,
  33913. 'questiondown': 500,
  33914. 'grave': 333,
  33915. 'acute': 333,
  33916. 'circumflex': 333,
  33917. 'tilde': 333,
  33918. 'macron': 333,
  33919. 'breve': 333,
  33920. 'dotaccent': 333,
  33921. 'dieresis': 333,
  33922. 'ring': 333,
  33923. 'cedilla': 333,
  33924. 'hungarumlaut': 333,
  33925. 'ogonek': 333,
  33926. 'caron': 333,
  33927. 'emdash': 889,
  33928. 'AE': 889,
  33929. 'ordfeminine': 276,
  33930. 'Lslash': 556,
  33931. 'Oslash': 722,
  33932. 'OE': 944,
  33933. 'ordmasculine': 310,
  33934. 'ae': 667,
  33935. 'dotlessi': 278,
  33936. 'lslash': 278,
  33937. 'oslash': 500,
  33938. 'oe': 667,
  33939. 'germandbls': 500,
  33940. 'Idieresis': 333,
  33941. 'eacute': 444,
  33942. 'abreve': 500,
  33943. 'uhungarumlaut': 500,
  33944. 'ecaron': 444,
  33945. 'Ydieresis': 556,
  33946. 'divide': 675,
  33947. 'Yacute': 556,
  33948. 'Acircumflex': 611,
  33949. 'aacute': 500,
  33950. 'Ucircumflex': 722,
  33951. 'yacute': 444,
  33952. 'scommaaccent': 389,
  33953. 'ecircumflex': 444,
  33954. 'Uring': 722,
  33955. 'Udieresis': 722,
  33956. 'aogonek': 500,
  33957. 'Uacute': 722,
  33958. 'uogonek': 500,
  33959. 'Edieresis': 611,
  33960. 'Dcroat': 722,
  33961. 'commaaccent': 250,
  33962. 'copyright': 760,
  33963. 'Emacron': 611,
  33964. 'ccaron': 444,
  33965. 'aring': 500,
  33966. 'Ncommaaccent': 667,
  33967. 'lacute': 278,
  33968. 'agrave': 500,
  33969. 'Tcommaaccent': 556,
  33970. 'Cacute': 667,
  33971. 'atilde': 500,
  33972. 'Edotaccent': 611,
  33973. 'scaron': 389,
  33974. 'scedilla': 389,
  33975. 'iacute': 278,
  33976. 'lozenge': 471,
  33977. 'Rcaron': 611,
  33978. 'Gcommaaccent': 722,
  33979. 'ucircumflex': 500,
  33980. 'acircumflex': 500,
  33981. 'Amacron': 611,
  33982. 'rcaron': 389,
  33983. 'ccedilla': 444,
  33984. 'Zdotaccent': 556,
  33985. 'Thorn': 611,
  33986. 'Omacron': 722,
  33987. 'Racute': 611,
  33988. 'Sacute': 500,
  33989. 'dcaron': 544,
  33990. 'Umacron': 722,
  33991. 'uring': 500,
  33992. 'threesuperior': 300,
  33993. 'Ograve': 722,
  33994. 'Agrave': 611,
  33995. 'Abreve': 611,
  33996. 'multiply': 675,
  33997. 'uacute': 500,
  33998. 'Tcaron': 556,
  33999. 'partialdiff': 476,
  34000. 'ydieresis': 444,
  34001. 'Nacute': 667,
  34002. 'icircumflex': 278,
  34003. 'Ecircumflex': 611,
  34004. 'adieresis': 500,
  34005. 'edieresis': 444,
  34006. 'cacute': 444,
  34007. 'nacute': 500,
  34008. 'umacron': 500,
  34009. 'Ncaron': 667,
  34010. 'Iacute': 333,
  34011. 'plusminus': 675,
  34012. 'brokenbar': 275,
  34013. 'registered': 760,
  34014. 'Gbreve': 722,
  34015. 'Idotaccent': 333,
  34016. 'summation': 600,
  34017. 'Egrave': 611,
  34018. 'racute': 389,
  34019. 'omacron': 500,
  34020. 'Zacute': 556,
  34021. 'Zcaron': 556,
  34022. 'greaterequal': 549,
  34023. 'Eth': 722,
  34024. 'Ccedilla': 667,
  34025. 'lcommaaccent': 278,
  34026. 'tcaron': 300,
  34027. 'eogonek': 444,
  34028. 'Uogonek': 722,
  34029. 'Aacute': 611,
  34030. 'Adieresis': 611,
  34031. 'egrave': 444,
  34032. 'zacute': 389,
  34033. 'iogonek': 278,
  34034. 'Oacute': 722,
  34035. 'oacute': 500,
  34036. 'amacron': 500,
  34037. 'sacute': 389,
  34038. 'idieresis': 278,
  34039. 'Ocircumflex': 722,
  34040. 'Ugrave': 722,
  34041. 'Delta': 612,
  34042. 'thorn': 500,
  34043. 'twosuperior': 300,
  34044. 'Odieresis': 722,
  34045. 'mu': 500,
  34046. 'igrave': 278,
  34047. 'ohungarumlaut': 500,
  34048. 'Eogonek': 611,
  34049. 'dcroat': 500,
  34050. 'threequarters': 750,
  34051. 'Scedilla': 500,
  34052. 'lcaron': 300,
  34053. 'Kcommaaccent': 667,
  34054. 'Lacute': 556,
  34055. 'trademark': 980,
  34056. 'edotaccent': 444,
  34057. 'Igrave': 333,
  34058. 'Imacron': 333,
  34059. 'Lcaron': 611,
  34060. 'onehalf': 750,
  34061. 'lessequal': 549,
  34062. 'ocircumflex': 500,
  34063. 'ntilde': 500,
  34064. 'Uhungarumlaut': 722,
  34065. 'Eacute': 611,
  34066. 'emacron': 444,
  34067. 'gbreve': 500,
  34068. 'onequarter': 750,
  34069. 'Scaron': 500,
  34070. 'Scommaaccent': 500,
  34071. 'Ohungarumlaut': 722,
  34072. 'degree': 400,
  34073. 'ograve': 500,
  34074. 'Ccaron': 667,
  34075. 'ugrave': 500,
  34076. 'radical': 453,
  34077. 'Dcaron': 722,
  34078. 'rcommaaccent': 389,
  34079. 'Ntilde': 667,
  34080. 'otilde': 500,
  34081. 'Rcommaaccent': 611,
  34082. 'Lcommaaccent': 556,
  34083. 'Atilde': 611,
  34084. 'Aogonek': 611,
  34085. 'Aring': 611,
  34086. 'Otilde': 722,
  34087. 'zdotaccent': 389,
  34088. 'Ecaron': 611,
  34089. 'Iogonek': 333,
  34090. 'kcommaaccent': 444,
  34091. 'minus': 675,
  34092. 'Icircumflex': 333,
  34093. 'ncaron': 500,
  34094. 'tcommaaccent': 278,
  34095. 'logicalnot': 675,
  34096. 'odieresis': 500,
  34097. 'udieresis': 500,
  34098. 'notequal': 549,
  34099. 'gcommaaccent': 500,
  34100. 'eth': 500,
  34101. 'zcaron': 389,
  34102. 'ncommaaccent': 500,
  34103. 'onesuperior': 300,
  34104. 'imacron': 278,
  34105. 'Euro': 500
  34106. },
  34107. 'ZapfDingbats': {
  34108. 'space': 278,
  34109. 'a1': 974,
  34110. 'a2': 961,
  34111. 'a202': 974,
  34112. 'a3': 980,
  34113. 'a4': 719,
  34114. 'a5': 789,
  34115. 'a119': 790,
  34116. 'a118': 791,
  34117. 'a117': 690,
  34118. 'a11': 960,
  34119. 'a12': 939,
  34120. 'a13': 549,
  34121. 'a14': 855,
  34122. 'a15': 911,
  34123. 'a16': 933,
  34124. 'a105': 911,
  34125. 'a17': 945,
  34126. 'a18': 974,
  34127. 'a19': 755,
  34128. 'a20': 846,
  34129. 'a21': 762,
  34130. 'a22': 761,
  34131. 'a23': 571,
  34132. 'a24': 677,
  34133. 'a25': 763,
  34134. 'a26': 760,
  34135. 'a27': 759,
  34136. 'a28': 754,
  34137. 'a6': 494,
  34138. 'a7': 552,
  34139. 'a8': 537,
  34140. 'a9': 577,
  34141. 'a10': 692,
  34142. 'a29': 786,
  34143. 'a30': 788,
  34144. 'a31': 788,
  34145. 'a32': 790,
  34146. 'a33': 793,
  34147. 'a34': 794,
  34148. 'a35': 816,
  34149. 'a36': 823,
  34150. 'a37': 789,
  34151. 'a38': 841,
  34152. 'a39': 823,
  34153. 'a40': 833,
  34154. 'a41': 816,
  34155. 'a42': 831,
  34156. 'a43': 923,
  34157. 'a44': 744,
  34158. 'a45': 723,
  34159. 'a46': 749,
  34160. 'a47': 790,
  34161. 'a48': 792,
  34162. 'a49': 695,
  34163. 'a50': 776,
  34164. 'a51': 768,
  34165. 'a52': 792,
  34166. 'a53': 759,
  34167. 'a54': 707,
  34168. 'a55': 708,
  34169. 'a56': 682,
  34170. 'a57': 701,
  34171. 'a58': 826,
  34172. 'a59': 815,
  34173. 'a60': 789,
  34174. 'a61': 789,
  34175. 'a62': 707,
  34176. 'a63': 687,
  34177. 'a64': 696,
  34178. 'a65': 689,
  34179. 'a66': 786,
  34180. 'a67': 787,
  34181. 'a68': 713,
  34182. 'a69': 791,
  34183. 'a70': 785,
  34184. 'a71': 791,
  34185. 'a72': 873,
  34186. 'a73': 761,
  34187. 'a74': 762,
  34188. 'a203': 762,
  34189. 'a75': 759,
  34190. 'a204': 759,
  34191. 'a76': 892,
  34192. 'a77': 892,
  34193. 'a78': 788,
  34194. 'a79': 784,
  34195. 'a81': 438,
  34196. 'a82': 138,
  34197. 'a83': 277,
  34198. 'a84': 415,
  34199. 'a97': 392,
  34200. 'a98': 392,
  34201. 'a99': 668,
  34202. 'a100': 668,
  34203. 'a89': 390,
  34204. 'a90': 390,
  34205. 'a93': 317,
  34206. 'a94': 317,
  34207. 'a91': 276,
  34208. 'a92': 276,
  34209. 'a205': 509,
  34210. 'a85': 509,
  34211. 'a206': 410,
  34212. 'a86': 410,
  34213. 'a87': 234,
  34214. 'a88': 234,
  34215. 'a95': 334,
  34216. 'a96': 334,
  34217. 'a101': 732,
  34218. 'a102': 544,
  34219. 'a103': 544,
  34220. 'a104': 910,
  34221. 'a106': 667,
  34222. 'a107': 760,
  34223. 'a108': 760,
  34224. 'a112': 776,
  34225. 'a111': 595,
  34226. 'a110': 694,
  34227. 'a109': 626,
  34228. 'a120': 788,
  34229. 'a121': 788,
  34230. 'a122': 788,
  34231. 'a123': 788,
  34232. 'a124': 788,
  34233. 'a125': 788,
  34234. 'a126': 788,
  34235. 'a127': 788,
  34236. 'a128': 788,
  34237. 'a129': 788,
  34238. 'a130': 788,
  34239. 'a131': 788,
  34240. 'a132': 788,
  34241. 'a133': 788,
  34242. 'a134': 788,
  34243. 'a135': 788,
  34244. 'a136': 788,
  34245. 'a137': 788,
  34246. 'a138': 788,
  34247. 'a139': 788,
  34248. 'a140': 788,
  34249. 'a141': 788,
  34250. 'a142': 788,
  34251. 'a143': 788,
  34252. 'a144': 788,
  34253. 'a145': 788,
  34254. 'a146': 788,
  34255. 'a147': 788,
  34256. 'a148': 788,
  34257. 'a149': 788,
  34258. 'a150': 788,
  34259. 'a151': 788,
  34260. 'a152': 788,
  34261. 'a153': 788,
  34262. 'a154': 788,
  34263. 'a155': 788,
  34264. 'a156': 788,
  34265. 'a157': 788,
  34266. 'a158': 788,
  34267. 'a159': 788,
  34268. 'a160': 894,
  34269. 'a161': 838,
  34270. 'a163': 1016,
  34271. 'a164': 458,
  34272. 'a196': 748,
  34273. 'a165': 924,
  34274. 'a192': 748,
  34275. 'a166': 918,
  34276. 'a167': 927,
  34277. 'a168': 928,
  34278. 'a169': 928,
  34279. 'a170': 834,
  34280. 'a171': 873,
  34281. 'a172': 828,
  34282. 'a173': 924,
  34283. 'a162': 924,
  34284. 'a174': 917,
  34285. 'a175': 930,
  34286. 'a176': 931,
  34287. 'a177': 463,
  34288. 'a178': 883,
  34289. 'a179': 836,
  34290. 'a193': 836,
  34291. 'a180': 867,
  34292. 'a199': 867,
  34293. 'a181': 696,
  34294. 'a200': 696,
  34295. 'a182': 874,
  34296. 'a201': 874,
  34297. 'a183': 760,
  34298. 'a184': 946,
  34299. 'a197': 771,
  34300. 'a185': 865,
  34301. 'a194': 771,
  34302. 'a198': 888,
  34303. 'a186': 967,
  34304. 'a195': 888,
  34305. 'a187': 831,
  34306. 'a188': 873,
  34307. 'a189': 927,
  34308. 'a190': 970,
  34309. 'a191': 918
  34310. }
  34311. };
  34312. var EOF = {};
  34313. function isEOF(v) {
  34314. return (v === EOF);
  34315. }
  34316. var MAX_LENGTH_TO_CACHE = 1000;
  34317. var Parser = (function ParserClosure() {
  34318. function Parser(lexer, allowStreams, xref) {
  34319. this.lexer = lexer;
  34320. this.allowStreams = allowStreams;
  34321. this.xref = xref;
  34322. this.imageCache = {};
  34323. this.refill();
  34324. }
  34325. Parser.prototype = {
  34326. refill: function Parser_refill() {
  34327. this.buf1 = this.lexer.getObj();
  34328. this.buf2 = this.lexer.getObj();
  34329. },
  34330. shift: function Parser_shift() {
  34331. if (isCmd(this.buf2, 'ID')) {
  34332. this.buf1 = this.buf2;
  34333. this.buf2 = null;
  34334. } else {
  34335. this.buf1 = this.buf2;
  34336. this.buf2 = this.lexer.getObj();
  34337. }
  34338. },
  34339. getObj: function Parser_getObj(cipherTransform) {
  34340. var buf1 = this.buf1;
  34341. this.shift();
  34342. if (buf1 instanceof Cmd) {
  34343. switch (buf1.cmd) {
  34344. case 'BI': // inline image
  34345. return this.makeInlineImage(cipherTransform);
  34346. case '[': // array
  34347. var array = [];
  34348. while (!isCmd(this.buf1, ']') && !isEOF(this.buf1)) {
  34349. array.push(this.getObj(cipherTransform));
  34350. }
  34351. if (isEOF(this.buf1)) {
  34352. error('End of file inside array');
  34353. }
  34354. this.shift();
  34355. return array;
  34356. case '<<': // dictionary or stream
  34357. var dict = new Dict(this.xref);
  34358. while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) {
  34359. if (!isName(this.buf1)) {
  34360. info('Malformed dictionary: key must be a name object');
  34361. this.shift();
  34362. continue;
  34363. }
  34364. var key = this.buf1.name;
  34365. this.shift();
  34366. if (isEOF(this.buf1)) {
  34367. break;
  34368. }
  34369. dict.set(key, this.getObj(cipherTransform));
  34370. }
  34371. if (isEOF(this.buf1)) {
  34372. error('End of file inside dictionary');
  34373. }
  34374. // Stream objects are not allowed inside content streams or
  34375. // object streams.
  34376. if (isCmd(this.buf2, 'stream')) {
  34377. return (this.allowStreams ?
  34378. this.makeStream(dict, cipherTransform) : dict);
  34379. }
  34380. this.shift();
  34381. return dict;
  34382. default: // simple object
  34383. return buf1;
  34384. }
  34385. }
  34386. if (isInt(buf1)) { // indirect reference or integer
  34387. var num = buf1;
  34388. if (isInt(this.buf1) && isCmd(this.buf2, 'R')) {
  34389. var ref = new Ref(num, this.buf1);
  34390. this.shift();
  34391. this.shift();
  34392. return ref;
  34393. }
  34394. return num;
  34395. }
  34396. if (isString(buf1)) { // string
  34397. var str = buf1;
  34398. if (cipherTransform) {
  34399. str = cipherTransform.decryptString(str);
  34400. }
  34401. return str;
  34402. }
  34403. // simple object
  34404. return buf1;
  34405. },
  34406. /**
  34407. * Find the end of the stream by searching for the /EI\s/.
  34408. * @returns {number} The inline stream length.
  34409. */
  34410. findDefaultInlineStreamEnd:
  34411. function Parser_findDefaultInlineStreamEnd(stream) {
  34412. var E = 0x45, I = 0x49, SPACE = 0x20, LF = 0xA, CR = 0xD;
  34413. var startPos = stream.pos, state = 0, ch, i, n, followingBytes;
  34414. while ((ch = stream.getByte()) !== -1) {
  34415. if (state === 0) {
  34416. state = (ch === E) ? 1 : 0;
  34417. } else if (state === 1) {
  34418. state = (ch === I) ? 2 : 0;
  34419. } else {
  34420. assert(state === 2);
  34421. if (ch === SPACE || ch === LF || ch === CR) {
  34422. // Let's check the next five bytes are ASCII... just be sure.
  34423. n = 5;
  34424. followingBytes = stream.peekBytes(n);
  34425. for (i = 0; i < n; i++) {
  34426. ch = followingBytes[i];
  34427. if (ch !== LF && ch !== CR && (ch < SPACE || ch > 0x7F)) {
  34428. // Not a LF, CR, SPACE or any visible ASCII character, i.e.
  34429. // it's binary stuff. Resetting the state.
  34430. state = 0;
  34431. break;
  34432. }
  34433. }
  34434. if (state === 2) {
  34435. break; // Finished!
  34436. }
  34437. } else {
  34438. state = 0;
  34439. }
  34440. }
  34441. }
  34442. return ((stream.pos - 4) - startPos);
  34443. },
  34444. /**
  34445. * Find the EOI (end-of-image) marker 0xFFD9 of the stream.
  34446. * @returns {number} The inline stream length.
  34447. */
  34448. findDCTDecodeInlineStreamEnd:
  34449. function Parser_findDCTDecodeInlineStreamEnd(stream) {
  34450. var startPos = stream.pos, foundEOI = false, b, markerLength, length;
  34451. while ((b = stream.getByte()) !== -1) {
  34452. if (b !== 0xFF) { // Not a valid marker.
  34453. continue;
  34454. }
  34455. switch (stream.getByte()) {
  34456. case 0x00: // Byte stuffing.
  34457. // 0xFF00 appears to be a very common byte sequence in JPEG images.
  34458. break;
  34459. case 0xFF: // Fill byte.
  34460. // Avoid skipping a valid marker, resetting the stream position.
  34461. stream.skip(-1);
  34462. break;
  34463. case 0xD9: // EOI
  34464. foundEOI = true;
  34465. break;
  34466. case 0xC0: // SOF0
  34467. case 0xC1: // SOF1
  34468. case 0xC2: // SOF2
  34469. case 0xC3: // SOF3
  34470. case 0xC5: // SOF5
  34471. case 0xC6: // SOF6
  34472. case 0xC7: // SOF7
  34473. case 0xC9: // SOF9
  34474. case 0xCA: // SOF10
  34475. case 0xCB: // SOF11
  34476. case 0xCD: // SOF13
  34477. case 0xCE: // SOF14
  34478. case 0xCF: // SOF15
  34479. case 0xC4: // DHT
  34480. case 0xCC: // DAC
  34481. case 0xDA: // SOS
  34482. case 0xDB: // DQT
  34483. case 0xDC: // DNL
  34484. case 0xDD: // DRI
  34485. case 0xDE: // DHP
  34486. case 0xDF: // EXP
  34487. case 0xE0: // APP0
  34488. case 0xE1: // APP1
  34489. case 0xE2: // APP2
  34490. case 0xE3: // APP3
  34491. case 0xE4: // APP4
  34492. case 0xE5: // APP5
  34493. case 0xE6: // APP6
  34494. case 0xE7: // APP7
  34495. case 0xE8: // APP8
  34496. case 0xE9: // APP9
  34497. case 0xEA: // APP10
  34498. case 0xEB: // APP11
  34499. case 0xEC: // APP12
  34500. case 0xED: // APP13
  34501. case 0xEE: // APP14
  34502. case 0xEF: // APP15
  34503. case 0xFE: // COM
  34504. // The marker should be followed by the length of the segment.
  34505. markerLength = stream.getUint16();
  34506. if (markerLength > 2) {
  34507. // |markerLength| contains the byte length of the marker segment,
  34508. // including its own length (2 bytes) and excluding the marker.
  34509. stream.skip(markerLength - 2); // Jump to the next marker.
  34510. } else {
  34511. // The marker length is invalid, resetting the stream position.
  34512. stream.skip(-2);
  34513. }
  34514. break;
  34515. }
  34516. if (foundEOI) {
  34517. break;
  34518. }
  34519. }
  34520. length = stream.pos - startPos;
  34521. if (b === -1) {
  34522. warn('Inline DCTDecode image stream: ' +
  34523. 'EOI marker not found, searching for /EI/ instead.');
  34524. stream.skip(-length); // Reset the stream position.
  34525. return this.findDefaultInlineStreamEnd(stream);
  34526. }
  34527. this.inlineStreamSkipEI(stream);
  34528. return length;
  34529. },
  34530. /**
  34531. * Find the EOD (end-of-data) marker '~>' (i.e. TILDE + GT) of the stream.
  34532. * @returns {number} The inline stream length.
  34533. */
  34534. findASCII85DecodeInlineStreamEnd:
  34535. function Parser_findASCII85DecodeInlineStreamEnd(stream) {
  34536. var TILDE = 0x7E, GT = 0x3E;
  34537. var startPos = stream.pos, ch, length;
  34538. while ((ch = stream.getByte()) !== -1) {
  34539. if (ch === TILDE && stream.peekByte() === GT) {
  34540. stream.skip();
  34541. break;
  34542. }
  34543. }
  34544. length = stream.pos - startPos;
  34545. if (ch === -1) {
  34546. warn('Inline ASCII85Decode image stream: ' +
  34547. 'EOD marker not found, searching for /EI/ instead.');
  34548. stream.skip(-length); // Reset the stream position.
  34549. return this.findDefaultInlineStreamEnd(stream);
  34550. }
  34551. this.inlineStreamSkipEI(stream);
  34552. return length;
  34553. },
  34554. /**
  34555. * Find the EOD (end-of-data) marker '>' (i.e. GT) of the stream.
  34556. * @returns {number} The inline stream length.
  34557. */
  34558. findASCIIHexDecodeInlineStreamEnd:
  34559. function Parser_findASCIIHexDecodeInlineStreamEnd(stream) {
  34560. var GT = 0x3E;
  34561. var startPos = stream.pos, ch, length;
  34562. while ((ch = stream.getByte()) !== -1) {
  34563. if (ch === GT) {
  34564. break;
  34565. }
  34566. }
  34567. length = stream.pos - startPos;
  34568. if (ch === -1) {
  34569. warn('Inline ASCIIHexDecode image stream: ' +
  34570. 'EOD marker not found, searching for /EI/ instead.');
  34571. stream.skip(-length); // Reset the stream position.
  34572. return this.findDefaultInlineStreamEnd(stream);
  34573. }
  34574. this.inlineStreamSkipEI(stream);
  34575. return length;
  34576. },
  34577. /**
  34578. * Skip over the /EI/ for streams where we search for an EOD marker.
  34579. */
  34580. inlineStreamSkipEI: function Parser_inlineStreamSkipEI(stream) {
  34581. var E = 0x45, I = 0x49;
  34582. var state = 0, ch;
  34583. while ((ch = stream.getByte()) !== -1) {
  34584. if (state === 0) {
  34585. state = (ch === E) ? 1 : 0;
  34586. } else if (state === 1) {
  34587. state = (ch === I) ? 2 : 0;
  34588. } else if (state === 2) {
  34589. break;
  34590. }
  34591. }
  34592. },
  34593. makeInlineImage: function Parser_makeInlineImage(cipherTransform) {
  34594. var lexer = this.lexer;
  34595. var stream = lexer.stream;
  34596. // Parse dictionary.
  34597. var dict = new Dict(null);
  34598. while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) {
  34599. if (!isName(this.buf1)) {
  34600. error('Dictionary key must be a name object');
  34601. }
  34602. var key = this.buf1.name;
  34603. this.shift();
  34604. if (isEOF(this.buf1)) {
  34605. break;
  34606. }
  34607. dict.set(key, this.getObj(cipherTransform));
  34608. }
  34609. // Extract the name of the first (i.e. the current) image filter.
  34610. var filter = this.fetchIfRef(dict.get('Filter', 'F')), filterName;
  34611. if (isName(filter)) {
  34612. filterName = filter.name;
  34613. } else if (isArray(filter) && isName(filter[0])) {
  34614. filterName = filter[0].name;
  34615. }
  34616. // Parse image stream.
  34617. var startPos = stream.pos, length, i, ii;
  34618. if (filterName === 'DCTDecode' || filterName === 'DCT') {
  34619. length = this.findDCTDecodeInlineStreamEnd(stream);
  34620. } else if (filterName === 'ASCII85Decide' || filterName === 'A85') {
  34621. length = this.findASCII85DecodeInlineStreamEnd(stream);
  34622. } else if (filterName === 'ASCIIHexDecode' || filterName === 'AHx') {
  34623. length = this.findASCIIHexDecodeInlineStreamEnd(stream);
  34624. } else {
  34625. length = this.findDefaultInlineStreamEnd(stream);
  34626. }
  34627. var imageStream = stream.makeSubStream(startPos, length, dict);
  34628. // Cache all images below the MAX_LENGTH_TO_CACHE threshold by their
  34629. // adler32 checksum.
  34630. var adler32;
  34631. if (length < MAX_LENGTH_TO_CACHE) {
  34632. var imageBytes = imageStream.getBytes();
  34633. imageStream.reset();
  34634. var a = 1;
  34635. var b = 0;
  34636. for (i = 0, ii = imageBytes.length; i < ii; ++i) {
  34637. // No modulo required in the loop if imageBytes.length < 5552.
  34638. a += imageBytes[i] & 0xff;
  34639. b += a;
  34640. }
  34641. adler32 = ((b % 65521) << 16) | (a % 65521);
  34642. if (this.imageCache.adler32 === adler32) {
  34643. this.buf2 = Cmd.get('EI');
  34644. this.shift();
  34645. this.imageCache[adler32].reset();
  34646. return this.imageCache[adler32];
  34647. }
  34648. }
  34649. if (cipherTransform) {
  34650. imageStream = cipherTransform.createStream(imageStream, length);
  34651. }
  34652. imageStream = this.filter(imageStream, dict, length);
  34653. imageStream.dict = dict;
  34654. if (adler32 !== undefined) {
  34655. imageStream.cacheKey = 'inline_' + length + '_' + adler32;
  34656. this.imageCache[adler32] = imageStream;
  34657. }
  34658. this.buf2 = Cmd.get('EI');
  34659. this.shift();
  34660. return imageStream;
  34661. },
  34662. fetchIfRef: function Parser_fetchIfRef(obj) {
  34663. // not relying on the xref.fetchIfRef -- xref might not be set
  34664. return (isRef(obj) ? this.xref.fetch(obj) : obj);
  34665. },
  34666. makeStream: function Parser_makeStream(dict, cipherTransform) {
  34667. var lexer = this.lexer;
  34668. var stream = lexer.stream;
  34669. // get stream start position
  34670. lexer.skipToNextLine();
  34671. var pos = stream.pos - 1;
  34672. // get length
  34673. var length = this.fetchIfRef(dict.get('Length'));
  34674. if (!isInt(length)) {
  34675. info('Bad ' + length + ' attribute in stream');
  34676. length = 0;
  34677. }
  34678. // skip over the stream data
  34679. stream.pos = pos + length;
  34680. lexer.nextChar();
  34681. this.shift(); // '>>'
  34682. this.shift(); // 'stream'
  34683. if (!isCmd(this.buf1, 'endstream')) {
  34684. // bad stream length, scanning for endstream
  34685. stream.pos = pos;
  34686. var SCAN_BLOCK_SIZE = 2048;
  34687. var ENDSTREAM_SIGNATURE_LENGTH = 9;
  34688. var ENDSTREAM_SIGNATURE = [0x65, 0x6E, 0x64, 0x73, 0x74, 0x72, 0x65,
  34689. 0x61, 0x6D];
  34690. var skipped = 0, found = false, i, j;
  34691. while (stream.pos < stream.end) {
  34692. var scanBytes = stream.peekBytes(SCAN_BLOCK_SIZE);
  34693. var scanLength = scanBytes.length - ENDSTREAM_SIGNATURE_LENGTH;
  34694. if (scanLength <= 0) {
  34695. break;
  34696. }
  34697. found = false;
  34698. for (i = 0, j = 0; i < scanLength; i++) {
  34699. var b = scanBytes[i];
  34700. if (b !== ENDSTREAM_SIGNATURE[j]) {
  34701. i -= j;
  34702. j = 0;
  34703. } else {
  34704. j++;
  34705. if (j >= ENDSTREAM_SIGNATURE_LENGTH) {
  34706. i++;
  34707. found = true;
  34708. break;
  34709. }
  34710. }
  34711. }
  34712. if (found) {
  34713. skipped += i - ENDSTREAM_SIGNATURE_LENGTH;
  34714. stream.pos += i - ENDSTREAM_SIGNATURE_LENGTH;
  34715. break;
  34716. }
  34717. skipped += scanLength;
  34718. stream.pos += scanLength;
  34719. }
  34720. if (!found) {
  34721. error('Missing endstream');
  34722. }
  34723. length = skipped;
  34724. lexer.nextChar();
  34725. this.shift();
  34726. this.shift();
  34727. }
  34728. this.shift(); // 'endstream'
  34729. stream = stream.makeSubStream(pos, length, dict);
  34730. if (cipherTransform) {
  34731. stream = cipherTransform.createStream(stream, length);
  34732. }
  34733. stream = this.filter(stream, dict, length);
  34734. stream.dict = dict;
  34735. return stream;
  34736. },
  34737. filter: function Parser_filter(stream, dict, length) {
  34738. var filter = this.fetchIfRef(dict.get('Filter', 'F'));
  34739. var params = this.fetchIfRef(dict.get('DecodeParms', 'DP'));
  34740. if (isName(filter)) {
  34741. return this.makeFilter(stream, filter.name, length, params);
  34742. }
  34743. var maybeLength = length;
  34744. if (isArray(filter)) {
  34745. var filterArray = filter;
  34746. var paramsArray = params;
  34747. for (var i = 0, ii = filterArray.length; i < ii; ++i) {
  34748. filter = filterArray[i];
  34749. if (!isName(filter)) {
  34750. error('Bad filter name: ' + filter);
  34751. }
  34752. params = null;
  34753. if (isArray(paramsArray) && (i in paramsArray)) {
  34754. params = paramsArray[i];
  34755. }
  34756. stream = this.makeFilter(stream, filter.name, maybeLength, params);
  34757. // after the first stream the length variable is invalid
  34758. maybeLength = null;
  34759. }
  34760. }
  34761. return stream;
  34762. },
  34763. makeFilter: function Parser_makeFilter(stream, name, maybeLength, params) {
  34764. if (stream.dict.get('Length') === 0) {
  34765. return new NullStream(stream);
  34766. }
  34767. try {
  34768. if (params) {
  34769. params = this.fetchIfRef(params);
  34770. }
  34771. var xrefStreamStats = this.xref.stats.streamTypes;
  34772. if (name === 'FlateDecode' || name === 'Fl') {
  34773. xrefStreamStats[StreamType.FLATE] = true;
  34774. if (params) {
  34775. return new PredictorStream(new FlateStream(stream, maybeLength),
  34776. maybeLength, params);
  34777. }
  34778. return new FlateStream(stream, maybeLength);
  34779. }
  34780. if (name === 'LZWDecode' || name === 'LZW') {
  34781. xrefStreamStats[StreamType.LZW] = true;
  34782. var earlyChange = 1;
  34783. if (params) {
  34784. if (params.has('EarlyChange')) {
  34785. earlyChange = params.get('EarlyChange');
  34786. }
  34787. return new PredictorStream(
  34788. new LZWStream(stream, maybeLength, earlyChange),
  34789. maybeLength, params);
  34790. }
  34791. return new LZWStream(stream, maybeLength, earlyChange);
  34792. }
  34793. if (name === 'DCTDecode' || name === 'DCT') {
  34794. xrefStreamStats[StreamType.DCT] = true;
  34795. return new JpegStream(stream, maybeLength, stream.dict, this.xref);
  34796. }
  34797. if (name === 'JPXDecode' || name === 'JPX') {
  34798. xrefStreamStats[StreamType.JPX] = true;
  34799. return new JpxStream(stream, maybeLength, stream.dict);
  34800. }
  34801. if (name === 'ASCII85Decode' || name === 'A85') {
  34802. xrefStreamStats[StreamType.A85] = true;
  34803. return new Ascii85Stream(stream, maybeLength);
  34804. }
  34805. if (name === 'ASCIIHexDecode' || name === 'AHx') {
  34806. xrefStreamStats[StreamType.AHX] = true;
  34807. return new AsciiHexStream(stream, maybeLength);
  34808. }
  34809. if (name === 'CCITTFaxDecode' || name === 'CCF') {
  34810. xrefStreamStats[StreamType.CCF] = true;
  34811. return new CCITTFaxStream(stream, maybeLength, params);
  34812. }
  34813. if (name === 'RunLengthDecode' || name === 'RL') {
  34814. xrefStreamStats[StreamType.RL] = true;
  34815. return new RunLengthStream(stream, maybeLength);
  34816. }
  34817. if (name === 'JBIG2Decode') {
  34818. xrefStreamStats[StreamType.JBIG] = true;
  34819. return new Jbig2Stream(stream, maybeLength, stream.dict);
  34820. }
  34821. warn('filter "' + name + '" not supported yet');
  34822. return stream;
  34823. } catch (ex) {
  34824. if (ex instanceof MissingDataException) {
  34825. throw ex;
  34826. }
  34827. warn('Invalid stream: \"' + ex + '\"');
  34828. return new NullStream(stream);
  34829. }
  34830. }
  34831. };
  34832. return Parser;
  34833. })();
  34834. var Lexer = (function LexerClosure() {
  34835. function Lexer(stream, knownCommands) {
  34836. this.stream = stream;
  34837. this.nextChar();
  34838. // While lexing, we build up many strings one char at a time. Using += for
  34839. // this can result in lots of garbage strings. It's better to build an
  34840. // array of single-char strings and then join() them together at the end.
  34841. // And reusing a single array (i.e. |this.strBuf|) over and over for this
  34842. // purpose uses less memory than using a new array for each string.
  34843. this.strBuf = [];
  34844. // The PDFs might have "glued" commands with other commands, operands or
  34845. // literals, e.g. "q1". The knownCommands is a dictionary of the valid
  34846. // commands and their prefixes. The prefixes are built the following way:
  34847. // if there a command that is a prefix of the other valid command or
  34848. // literal (e.g. 'f' and 'false') the following prefixes must be included,
  34849. // 'fa', 'fal', 'fals'. The prefixes are not needed, if the command has no
  34850. // other commands or literals as a prefix. The knowCommands is optional.
  34851. this.knownCommands = knownCommands;
  34852. }
  34853. Lexer.isSpace = function Lexer_isSpace(ch) {
  34854. // Space is one of the following characters: SPACE, TAB, CR or LF.
  34855. return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
  34856. };
  34857. // A '1' in this array means the character is white space. A '1' or
  34858. // '2' means the character ends a name or command.
  34859. var specialChars = [
  34860. 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x
  34861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
  34862. 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x
  34863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x
  34864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x
  34865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x
  34866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x
  34867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x
  34868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x
  34869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x
  34870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax
  34871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx
  34872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx
  34873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx
  34874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex
  34875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx
  34876. ];
  34877. function toHexDigit(ch) {
  34878. if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
  34879. return ch & 0x0F;
  34880. }
  34881. if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
  34882. // 'A'-'F', 'a'-'f'
  34883. return (ch & 0x0F) + 9;
  34884. }
  34885. return -1;
  34886. }
  34887. Lexer.prototype = {
  34888. nextChar: function Lexer_nextChar() {
  34889. return (this.currentChar = this.stream.getByte());
  34890. },
  34891. peekChar: function Lexer_peekChar() {
  34892. return this.stream.peekByte();
  34893. },
  34894. getNumber: function Lexer_getNumber() {
  34895. var ch = this.currentChar;
  34896. var eNotation = false;
  34897. var divideBy = 0; // different from 0 if it's a floating point value
  34898. var sign = 1;
  34899. if (ch === 0x2D) { // '-'
  34900. sign = -1;
  34901. ch = this.nextChar();
  34902. } else if (ch === 0x2B) { // '+'
  34903. ch = this.nextChar();
  34904. }
  34905. if (ch === 0x2E) { // '.'
  34906. divideBy = 10;
  34907. ch = this.nextChar();
  34908. }
  34909. if (ch < 0x30 || ch > 0x39) { // '0' - '9'
  34910. error('Invalid number: ' + String.fromCharCode(ch));
  34911. return 0;
  34912. }
  34913. var baseValue = ch - 0x30; // '0'
  34914. var powerValue = 0;
  34915. var powerValueSign = 1;
  34916. while ((ch = this.nextChar()) >= 0) {
  34917. if (0x30 <= ch && ch <= 0x39) { // '0' - '9'
  34918. var currentDigit = ch - 0x30; // '0'
  34919. if (eNotation) { // We are after an 'e' or 'E'
  34920. powerValue = powerValue * 10 + currentDigit;
  34921. } else {
  34922. if (divideBy !== 0) { // We are after a point
  34923. divideBy *= 10;
  34924. }
  34925. baseValue = baseValue * 10 + currentDigit;
  34926. }
  34927. } else if (ch === 0x2E) { // '.'
  34928. if (divideBy === 0) {
  34929. divideBy = 1;
  34930. } else {
  34931. // A number can have only one '.'
  34932. break;
  34933. }
  34934. } else if (ch === 0x2D) { // '-'
  34935. // ignore minus signs in the middle of numbers to match
  34936. // Adobe's behavior
  34937. warn('Badly formated number');
  34938. } else if (ch === 0x45 || ch === 0x65) { // 'E', 'e'
  34939. // 'E' can be either a scientific notation or the beginning of a new
  34940. // operator
  34941. ch = this.peekChar();
  34942. if (ch === 0x2B || ch === 0x2D) { // '+', '-'
  34943. powerValueSign = (ch === 0x2D) ? -1 : 1;
  34944. this.nextChar(); // Consume the sign character
  34945. } else if (ch < 0x30 || ch > 0x39) { // '0' - '9'
  34946. // The 'E' must be the beginning of a new operator
  34947. break;
  34948. }
  34949. eNotation = true;
  34950. } else {
  34951. // the last character doesn't belong to us
  34952. break;
  34953. }
  34954. }
  34955. if (divideBy !== 0) {
  34956. baseValue /= divideBy;
  34957. }
  34958. if (eNotation) {
  34959. baseValue *= Math.pow(10, powerValueSign * powerValue);
  34960. }
  34961. return sign * baseValue;
  34962. },
  34963. getString: function Lexer_getString() {
  34964. var numParen = 1;
  34965. var done = false;
  34966. var strBuf = this.strBuf;
  34967. strBuf.length = 0;
  34968. var ch = this.nextChar();
  34969. while (true) {
  34970. var charBuffered = false;
  34971. switch (ch | 0) {
  34972. case -1:
  34973. warn('Unterminated string');
  34974. done = true;
  34975. break;
  34976. case 0x28: // '('
  34977. ++numParen;
  34978. strBuf.push('(');
  34979. break;
  34980. case 0x29: // ')'
  34981. if (--numParen === 0) {
  34982. this.nextChar(); // consume strings ')'
  34983. done = true;
  34984. } else {
  34985. strBuf.push(')');
  34986. }
  34987. break;
  34988. case 0x5C: // '\\'
  34989. ch = this.nextChar();
  34990. switch (ch) {
  34991. case -1:
  34992. warn('Unterminated string');
  34993. done = true;
  34994. break;
  34995. case 0x6E: // 'n'
  34996. strBuf.push('\n');
  34997. break;
  34998. case 0x72: // 'r'
  34999. strBuf.push('\r');
  35000. break;
  35001. case 0x74: // 't'
  35002. strBuf.push('\t');
  35003. break;
  35004. case 0x62: // 'b'
  35005. strBuf.push('\b');
  35006. break;
  35007. case 0x66: // 'f'
  35008. strBuf.push('\f');
  35009. break;
  35010. case 0x5C: // '\'
  35011. case 0x28: // '('
  35012. case 0x29: // ')'
  35013. strBuf.push(String.fromCharCode(ch));
  35014. break;
  35015. case 0x30: case 0x31: case 0x32: case 0x33: // '0'-'3'
  35016. case 0x34: case 0x35: case 0x36: case 0x37: // '4'-'7'
  35017. var x = ch & 0x0F;
  35018. ch = this.nextChar();
  35019. charBuffered = true;
  35020. if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'
  35021. x = (x << 3) + (ch & 0x0F);
  35022. ch = this.nextChar();
  35023. if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'
  35024. charBuffered = false;
  35025. x = (x << 3) + (ch & 0x0F);
  35026. }
  35027. }
  35028. strBuf.push(String.fromCharCode(x));
  35029. break;
  35030. case 0x0D: // CR
  35031. if (this.peekChar() === 0x0A) { // LF
  35032. this.nextChar();
  35033. }
  35034. break;
  35035. case 0x0A: // LF
  35036. break;
  35037. default:
  35038. strBuf.push(String.fromCharCode(ch));
  35039. break;
  35040. }
  35041. break;
  35042. default:
  35043. strBuf.push(String.fromCharCode(ch));
  35044. break;
  35045. }
  35046. if (done) {
  35047. break;
  35048. }
  35049. if (!charBuffered) {
  35050. ch = this.nextChar();
  35051. }
  35052. }
  35053. return strBuf.join('');
  35054. },
  35055. getName: function Lexer_getName() {
  35056. var ch;
  35057. var strBuf = this.strBuf;
  35058. strBuf.length = 0;
  35059. while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
  35060. if (ch === 0x23) { // '#'
  35061. ch = this.nextChar();
  35062. var x = toHexDigit(ch);
  35063. if (x !== -1) {
  35064. var x2 = toHexDigit(this.nextChar());
  35065. if (x2 === -1) {
  35066. error('Illegal digit in hex char in name: ' + x2);
  35067. }
  35068. strBuf.push(String.fromCharCode((x << 4) | x2));
  35069. } else {
  35070. strBuf.push('#', String.fromCharCode(ch));
  35071. }
  35072. } else {
  35073. strBuf.push(String.fromCharCode(ch));
  35074. }
  35075. }
  35076. if (strBuf.length > 127) {
  35077. warn('name token is longer than allowed by the spec: ' + strBuf.length);
  35078. }
  35079. return Name.get(strBuf.join(''));
  35080. },
  35081. getHexString: function Lexer_getHexString() {
  35082. var strBuf = this.strBuf;
  35083. strBuf.length = 0;
  35084. var ch = this.currentChar;
  35085. var isFirstHex = true;
  35086. var firstDigit;
  35087. var secondDigit;
  35088. while (true) {
  35089. if (ch < 0) {
  35090. warn('Unterminated hex string');
  35091. break;
  35092. } else if (ch === 0x3E) { // '>'
  35093. this.nextChar();
  35094. break;
  35095. } else if (specialChars[ch] === 1) {
  35096. ch = this.nextChar();
  35097. continue;
  35098. } else {
  35099. if (isFirstHex) {
  35100. firstDigit = toHexDigit(ch);
  35101. if (firstDigit === -1) {
  35102. warn('Ignoring invalid character "' + ch + '" in hex string');
  35103. ch = this.nextChar();
  35104. continue;
  35105. }
  35106. } else {
  35107. secondDigit = toHexDigit(ch);
  35108. if (secondDigit === -1) {
  35109. warn('Ignoring invalid character "' + ch + '" in hex string');
  35110. ch = this.nextChar();
  35111. continue;
  35112. }
  35113. strBuf.push(String.fromCharCode((firstDigit << 4) | secondDigit));
  35114. }
  35115. isFirstHex = !isFirstHex;
  35116. ch = this.nextChar();
  35117. }
  35118. }
  35119. return strBuf.join('');
  35120. },
  35121. getObj: function Lexer_getObj() {
  35122. // skip whitespace and comments
  35123. var comment = false;
  35124. var ch = this.currentChar;
  35125. while (true) {
  35126. if (ch < 0) {
  35127. return EOF;
  35128. }
  35129. if (comment) {
  35130. if (ch === 0x0A || ch === 0x0D) { // LF, CR
  35131. comment = false;
  35132. }
  35133. } else if (ch === 0x25) { // '%'
  35134. comment = true;
  35135. } else if (specialChars[ch] !== 1) {
  35136. break;
  35137. }
  35138. ch = this.nextChar();
  35139. }
  35140. // start reading token
  35141. switch (ch | 0) {
  35142. case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'
  35143. case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'
  35144. case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'
  35145. return this.getNumber();
  35146. case 0x28: // '('
  35147. return this.getString();
  35148. case 0x2F: // '/'
  35149. return this.getName();
  35150. // array punctuation
  35151. case 0x5B: // '['
  35152. this.nextChar();
  35153. return Cmd.get('[');
  35154. case 0x5D: // ']'
  35155. this.nextChar();
  35156. return Cmd.get(']');
  35157. // hex string or dict punctuation
  35158. case 0x3C: // '<'
  35159. ch = this.nextChar();
  35160. if (ch === 0x3C) {
  35161. // dict punctuation
  35162. this.nextChar();
  35163. return Cmd.get('<<');
  35164. }
  35165. return this.getHexString();
  35166. // dict punctuation
  35167. case 0x3E: // '>'
  35168. ch = this.nextChar();
  35169. if (ch === 0x3E) {
  35170. this.nextChar();
  35171. return Cmd.get('>>');
  35172. }
  35173. return Cmd.get('>');
  35174. case 0x7B: // '{'
  35175. this.nextChar();
  35176. return Cmd.get('{');
  35177. case 0x7D: // '}'
  35178. this.nextChar();
  35179. return Cmd.get('}');
  35180. case 0x29: // ')'
  35181. error('Illegal character: ' + ch);
  35182. break;
  35183. }
  35184. // command
  35185. var str = String.fromCharCode(ch);
  35186. var knownCommands = this.knownCommands;
  35187. var knownCommandFound = knownCommands && knownCommands[str] !== undefined;
  35188. while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
  35189. // stop if known command is found and next character does not make
  35190. // the str a command
  35191. var possibleCommand = str + String.fromCharCode(ch);
  35192. if (knownCommandFound && knownCommands[possibleCommand] === undefined) {
  35193. break;
  35194. }
  35195. if (str.length === 128) {
  35196. error('Command token too long: ' + str.length);
  35197. }
  35198. str = possibleCommand;
  35199. knownCommandFound = knownCommands && knownCommands[str] !== undefined;
  35200. }
  35201. if (str === 'true') {
  35202. return true;
  35203. }
  35204. if (str === 'false') {
  35205. return false;
  35206. }
  35207. if (str === 'null') {
  35208. return null;
  35209. }
  35210. return Cmd.get(str);
  35211. },
  35212. skipToNextLine: function Lexer_skipToNextLine() {
  35213. var ch = this.currentChar;
  35214. while (ch >= 0) {
  35215. if (ch === 0x0D) { // CR
  35216. ch = this.nextChar();
  35217. if (ch === 0x0A) { // LF
  35218. this.nextChar();
  35219. }
  35220. break;
  35221. } else if (ch === 0x0A) { // LF
  35222. this.nextChar();
  35223. break;
  35224. }
  35225. ch = this.nextChar();
  35226. }
  35227. }
  35228. };
  35229. return Lexer;
  35230. })();
  35231. var Linearization = {
  35232. create: function LinearizationCreate(stream) {
  35233. function getInt(name, allowZeroValue) {
  35234. var obj = linDict.get(name);
  35235. if (isInt(obj) && (allowZeroValue ? obj >= 0 : obj > 0)) {
  35236. return obj;
  35237. }
  35238. throw new Error('The "' + name + '" parameter in the linearization ' +
  35239. 'dictionary is invalid.');
  35240. }
  35241. function getHints() {
  35242. var hints = linDict.get('H'), hintsLength, item;
  35243. if (isArray(hints) &&
  35244. ((hintsLength = hints.length) === 2 || hintsLength === 4)) {
  35245. for (var index = 0; index < hintsLength; index++) {
  35246. if (!(isInt(item = hints[index]) && item > 0)) {
  35247. throw new Error('Hint (' + index +
  35248. ') in the linearization dictionary is invalid.');
  35249. }
  35250. }
  35251. return hints;
  35252. }
  35253. throw new Error('Hint array in the linearization dictionary is invalid.');
  35254. }
  35255. var parser = new Parser(new Lexer(stream), false, null);
  35256. var obj1 = parser.getObj();
  35257. var obj2 = parser.getObj();
  35258. var obj3 = parser.getObj();
  35259. var linDict = parser.getObj();
  35260. var obj, length;
  35261. if (!(isInt(obj1) && isInt(obj2) && isCmd(obj3, 'obj') && isDict(linDict) &&
  35262. isNum(obj = linDict.get('Linearized')) && obj > 0)) {
  35263. return null; // No valid linearization dictionary found.
  35264. } else if ((length = getInt('L')) !== stream.length) {
  35265. throw new Error('The "L" parameter in the linearization dictionary ' +
  35266. 'does not equal the stream length.');
  35267. }
  35268. return {
  35269. length: length,
  35270. hints: getHints(),
  35271. objectNumberFirst: getInt('O'),
  35272. endFirst: getInt('E'),
  35273. numPages: getInt('N'),
  35274. mainXRefEntriesOffset: getInt('T'),
  35275. pageFirst: (linDict.has('P') ? getInt('P', true) : 0)
  35276. };
  35277. }
  35278. };
  35279. var PostScriptParser = (function PostScriptParserClosure() {
  35280. function PostScriptParser(lexer) {
  35281. this.lexer = lexer;
  35282. this.operators = [];
  35283. this.token = null;
  35284. this.prev = null;
  35285. }
  35286. PostScriptParser.prototype = {
  35287. nextToken: function PostScriptParser_nextToken() {
  35288. this.prev = this.token;
  35289. this.token = this.lexer.getToken();
  35290. },
  35291. accept: function PostScriptParser_accept(type) {
  35292. if (this.token.type === type) {
  35293. this.nextToken();
  35294. return true;
  35295. }
  35296. return false;
  35297. },
  35298. expect: function PostScriptParser_expect(type) {
  35299. if (this.accept(type)) {
  35300. return true;
  35301. }
  35302. error('Unexpected symbol: found ' + this.token.type + ' expected ' +
  35303. type + '.');
  35304. },
  35305. parse: function PostScriptParser_parse() {
  35306. this.nextToken();
  35307. this.expect(PostScriptTokenTypes.LBRACE);
  35308. this.parseBlock();
  35309. this.expect(PostScriptTokenTypes.RBRACE);
  35310. return this.operators;
  35311. },
  35312. parseBlock: function PostScriptParser_parseBlock() {
  35313. while (true) {
  35314. if (this.accept(PostScriptTokenTypes.NUMBER)) {
  35315. this.operators.push(this.prev.value);
  35316. } else if (this.accept(PostScriptTokenTypes.OPERATOR)) {
  35317. this.operators.push(this.prev.value);
  35318. } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
  35319. this.parseCondition();
  35320. } else {
  35321. return;
  35322. }
  35323. }
  35324. },
  35325. parseCondition: function PostScriptParser_parseCondition() {
  35326. // Add two place holders that will be updated later
  35327. var conditionLocation = this.operators.length;
  35328. this.operators.push(null, null);
  35329. this.parseBlock();
  35330. this.expect(PostScriptTokenTypes.RBRACE);
  35331. if (this.accept(PostScriptTokenTypes.IF)) {
  35332. // The true block is right after the 'if' so it just falls through on
  35333. // true else it jumps and skips the true block.
  35334. this.operators[conditionLocation] = this.operators.length;
  35335. this.operators[conditionLocation + 1] = 'jz';
  35336. } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
  35337. var jumpLocation = this.operators.length;
  35338. this.operators.push(null, null);
  35339. var endOfTrue = this.operators.length;
  35340. this.parseBlock();
  35341. this.expect(PostScriptTokenTypes.RBRACE);
  35342. this.expect(PostScriptTokenTypes.IFELSE);
  35343. // The jump is added at the end of the true block to skip the false
  35344. // block.
  35345. this.operators[jumpLocation] = this.operators.length;
  35346. this.operators[jumpLocation + 1] = 'j';
  35347. this.operators[conditionLocation] = endOfTrue;
  35348. this.operators[conditionLocation + 1] = 'jz';
  35349. } else {
  35350. error('PS Function: error parsing conditional.');
  35351. }
  35352. }
  35353. };
  35354. return PostScriptParser;
  35355. })();
  35356. var PostScriptTokenTypes = {
  35357. LBRACE: 0,
  35358. RBRACE: 1,
  35359. NUMBER: 2,
  35360. OPERATOR: 3,
  35361. IF: 4,
  35362. IFELSE: 5
  35363. };
  35364. var PostScriptToken = (function PostScriptTokenClosure() {
  35365. function PostScriptToken(type, value) {
  35366. this.type = type;
  35367. this.value = value;
  35368. }
  35369. var opCache = {};
  35370. PostScriptToken.getOperator = function PostScriptToken_getOperator(op) {
  35371. var opValue = opCache[op];
  35372. if (opValue) {
  35373. return opValue;
  35374. }
  35375. return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);
  35376. };
  35377. PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE,
  35378. '{');
  35379. PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE,
  35380. '}');
  35381. PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF');
  35382. PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE,
  35383. 'IFELSE');
  35384. return PostScriptToken;
  35385. })();
  35386. var PostScriptLexer = (function PostScriptLexerClosure() {
  35387. function PostScriptLexer(stream) {
  35388. this.stream = stream;
  35389. this.nextChar();
  35390. this.strBuf = [];
  35391. }
  35392. PostScriptLexer.prototype = {
  35393. nextChar: function PostScriptLexer_nextChar() {
  35394. return (this.currentChar = this.stream.getByte());
  35395. },
  35396. getToken: function PostScriptLexer_getToken() {
  35397. var comment = false;
  35398. var ch = this.currentChar;
  35399. // skip comments
  35400. while (true) {
  35401. if (ch < 0) {
  35402. return EOF;
  35403. }
  35404. if (comment) {
  35405. if (ch === 0x0A || ch === 0x0D) {
  35406. comment = false;
  35407. }
  35408. } else if (ch === 0x25) { // '%'
  35409. comment = true;
  35410. } else if (!Lexer.isSpace(ch)) {
  35411. break;
  35412. }
  35413. ch = this.nextChar();
  35414. }
  35415. switch (ch | 0) {
  35416. case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'
  35417. case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'
  35418. case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'
  35419. return new PostScriptToken(PostScriptTokenTypes.NUMBER,
  35420. this.getNumber());
  35421. case 0x7B: // '{'
  35422. this.nextChar();
  35423. return PostScriptToken.LBRACE;
  35424. case 0x7D: // '}'
  35425. this.nextChar();
  35426. return PostScriptToken.RBRACE;
  35427. }
  35428. // operator
  35429. var strBuf = this.strBuf;
  35430. strBuf.length = 0;
  35431. strBuf[0] = String.fromCharCode(ch);
  35432. while ((ch = this.nextChar()) >= 0 && // and 'A'-'Z', 'a'-'z'
  35433. ((ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A))) {
  35434. strBuf.push(String.fromCharCode(ch));
  35435. }
  35436. var str = strBuf.join('');
  35437. switch (str.toLowerCase()) {
  35438. case 'if':
  35439. return PostScriptToken.IF;
  35440. case 'ifelse':
  35441. return PostScriptToken.IFELSE;
  35442. default:
  35443. return PostScriptToken.getOperator(str);
  35444. }
  35445. },
  35446. getNumber: function PostScriptLexer_getNumber() {
  35447. var ch = this.currentChar;
  35448. var strBuf = this.strBuf;
  35449. strBuf.length = 0;
  35450. strBuf[0] = String.fromCharCode(ch);
  35451. while ((ch = this.nextChar()) >= 0) {
  35452. if ((ch >= 0x30 && ch <= 0x39) || // '0'-'9'
  35453. ch === 0x2D || ch === 0x2E) { // '-', '.'
  35454. strBuf.push(String.fromCharCode(ch));
  35455. } else {
  35456. break;
  35457. }
  35458. }
  35459. var value = parseFloat(strBuf.join(''));
  35460. if (isNaN(value)) {
  35461. error('Invalid floating point number: ' + value);
  35462. }
  35463. return value;
  35464. }
  35465. };
  35466. return PostScriptLexer;
  35467. })();
  35468. var Stream = (function StreamClosure() {
  35469. function Stream(arrayBuffer, start, length, dict) {
  35470. this.bytes = (arrayBuffer instanceof Uint8Array ?
  35471. arrayBuffer : new Uint8Array(arrayBuffer));
  35472. this.start = start || 0;
  35473. this.pos = this.start;
  35474. this.end = (start + length) || this.bytes.length;
  35475. this.dict = dict;
  35476. }
  35477. // required methods for a stream. if a particular stream does not
  35478. // implement these, an error should be thrown
  35479. Stream.prototype = {
  35480. get length() {
  35481. return this.end - this.start;
  35482. },
  35483. get isEmpty() {
  35484. return this.length === 0;
  35485. },
  35486. getByte: function Stream_getByte() {
  35487. if (this.pos >= this.end) {
  35488. return -1;
  35489. }
  35490. return this.bytes[this.pos++];
  35491. },
  35492. getUint16: function Stream_getUint16() {
  35493. var b0 = this.getByte();
  35494. var b1 = this.getByte();
  35495. if (b0 === -1 || b1 === -1) {
  35496. return -1;
  35497. }
  35498. return (b0 << 8) + b1;
  35499. },
  35500. getInt32: function Stream_getInt32() {
  35501. var b0 = this.getByte();
  35502. var b1 = this.getByte();
  35503. var b2 = this.getByte();
  35504. var b3 = this.getByte();
  35505. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  35506. },
  35507. // returns subarray of original buffer
  35508. // should only be read
  35509. getBytes: function Stream_getBytes(length) {
  35510. var bytes = this.bytes;
  35511. var pos = this.pos;
  35512. var strEnd = this.end;
  35513. if (!length) {
  35514. return bytes.subarray(pos, strEnd);
  35515. }
  35516. var end = pos + length;
  35517. if (end > strEnd) {
  35518. end = strEnd;
  35519. }
  35520. this.pos = end;
  35521. return bytes.subarray(pos, end);
  35522. },
  35523. peekByte: function Stream_peekByte() {
  35524. var peekedByte = this.getByte();
  35525. this.pos--;
  35526. return peekedByte;
  35527. },
  35528. peekBytes: function Stream_peekBytes(length) {
  35529. var bytes = this.getBytes(length);
  35530. this.pos -= bytes.length;
  35531. return bytes;
  35532. },
  35533. skip: function Stream_skip(n) {
  35534. if (!n) {
  35535. n = 1;
  35536. }
  35537. this.pos += n;
  35538. },
  35539. reset: function Stream_reset() {
  35540. this.pos = this.start;
  35541. },
  35542. moveStart: function Stream_moveStart() {
  35543. this.start = this.pos;
  35544. },
  35545. makeSubStream: function Stream_makeSubStream(start, length, dict) {
  35546. return new Stream(this.bytes.buffer, start, length, dict);
  35547. },
  35548. isStream: true
  35549. };
  35550. return Stream;
  35551. })();
  35552. var StringStream = (function StringStreamClosure() {
  35553. function StringStream(str) {
  35554. var length = str.length;
  35555. var bytes = new Uint8Array(length);
  35556. for (var n = 0; n < length; ++n) {
  35557. bytes[n] = str.charCodeAt(n);
  35558. }
  35559. Stream.call(this, bytes);
  35560. }
  35561. StringStream.prototype = Stream.prototype;
  35562. return StringStream;
  35563. })();
  35564. // super class for the decoding streams
  35565. var DecodeStream = (function DecodeStreamClosure() {
  35566. // Lots of DecodeStreams are created whose buffers are never used. For these
  35567. // we share a single empty buffer. This is (a) space-efficient and (b) avoids
  35568. // having special cases that would be required if we used |null| for an empty
  35569. // buffer.
  35570. var emptyBuffer = new Uint8Array(0);
  35571. function DecodeStream(maybeMinBufferLength) {
  35572. this.pos = 0;
  35573. this.bufferLength = 0;
  35574. this.eof = false;
  35575. this.buffer = emptyBuffer;
  35576. this.minBufferLength = 512;
  35577. if (maybeMinBufferLength) {
  35578. // Compute the first power of two that is as big as maybeMinBufferLength.
  35579. while (this.minBufferLength < maybeMinBufferLength) {
  35580. this.minBufferLength *= 2;
  35581. }
  35582. }
  35583. }
  35584. DecodeStream.prototype = {
  35585. get isEmpty() {
  35586. while (!this.eof && this.bufferLength === 0) {
  35587. this.readBlock();
  35588. }
  35589. return this.bufferLength === 0;
  35590. },
  35591. ensureBuffer: function DecodeStream_ensureBuffer(requested) {
  35592. var buffer = this.buffer;
  35593. if (requested <= buffer.byteLength) {
  35594. return buffer;
  35595. }
  35596. var size = this.minBufferLength;
  35597. while (size < requested) {
  35598. size *= 2;
  35599. }
  35600. var buffer2 = new Uint8Array(size);
  35601. buffer2.set(buffer);
  35602. return (this.buffer = buffer2);
  35603. },
  35604. getByte: function DecodeStream_getByte() {
  35605. var pos = this.pos;
  35606. while (this.bufferLength <= pos) {
  35607. if (this.eof) {
  35608. return -1;
  35609. }
  35610. this.readBlock();
  35611. }
  35612. return this.buffer[this.pos++];
  35613. },
  35614. getUint16: function DecodeStream_getUint16() {
  35615. var b0 = this.getByte();
  35616. var b1 = this.getByte();
  35617. if (b0 === -1 || b1 === -1) {
  35618. return -1;
  35619. }
  35620. return (b0 << 8) + b1;
  35621. },
  35622. getInt32: function DecodeStream_getInt32() {
  35623. var b0 = this.getByte();
  35624. var b1 = this.getByte();
  35625. var b2 = this.getByte();
  35626. var b3 = this.getByte();
  35627. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  35628. },
  35629. getBytes: function DecodeStream_getBytes(length) {
  35630. var end, pos = this.pos;
  35631. if (length) {
  35632. this.ensureBuffer(pos + length);
  35633. end = pos + length;
  35634. while (!this.eof && this.bufferLength < end) {
  35635. this.readBlock();
  35636. }
  35637. var bufEnd = this.bufferLength;
  35638. if (end > bufEnd) {
  35639. end = bufEnd;
  35640. }
  35641. } else {
  35642. while (!this.eof) {
  35643. this.readBlock();
  35644. }
  35645. end = this.bufferLength;
  35646. }
  35647. this.pos = end;
  35648. return this.buffer.subarray(pos, end);
  35649. },
  35650. peekByte: function DecodeStream_peekByte() {
  35651. var peekedByte = this.getByte();
  35652. this.pos--;
  35653. return peekedByte;
  35654. },
  35655. peekBytes: function DecodeStream_peekBytes(length) {
  35656. var bytes = this.getBytes(length);
  35657. this.pos -= bytes.length;
  35658. return bytes;
  35659. },
  35660. makeSubStream: function DecodeStream_makeSubStream(start, length, dict) {
  35661. var end = start + length;
  35662. while (this.bufferLength <= end && !this.eof) {
  35663. this.readBlock();
  35664. }
  35665. return new Stream(this.buffer, start, length, dict);
  35666. },
  35667. skip: function DecodeStream_skip(n) {
  35668. if (!n) {
  35669. n = 1;
  35670. }
  35671. this.pos += n;
  35672. },
  35673. reset: function DecodeStream_reset() {
  35674. this.pos = 0;
  35675. },
  35676. getBaseStreams: function DecodeStream_getBaseStreams() {
  35677. if (this.str && this.str.getBaseStreams) {
  35678. return this.str.getBaseStreams();
  35679. }
  35680. return [];
  35681. }
  35682. };
  35683. return DecodeStream;
  35684. })();
  35685. var StreamsSequenceStream = (function StreamsSequenceStreamClosure() {
  35686. function StreamsSequenceStream(streams) {
  35687. this.streams = streams;
  35688. DecodeStream.call(this, /* maybeLength = */ null);
  35689. }
  35690. StreamsSequenceStream.prototype = Object.create(DecodeStream.prototype);
  35691. StreamsSequenceStream.prototype.readBlock =
  35692. function streamSequenceStreamReadBlock() {
  35693. var streams = this.streams;
  35694. if (streams.length === 0) {
  35695. this.eof = true;
  35696. return;
  35697. }
  35698. var stream = streams.shift();
  35699. var chunk = stream.getBytes();
  35700. var bufferLength = this.bufferLength;
  35701. var newLength = bufferLength + chunk.length;
  35702. var buffer = this.ensureBuffer(newLength);
  35703. buffer.set(chunk, bufferLength);
  35704. this.bufferLength = newLength;
  35705. };
  35706. StreamsSequenceStream.prototype.getBaseStreams =
  35707. function StreamsSequenceStream_getBaseStreams() {
  35708. var baseStreams = [];
  35709. for (var i = 0, ii = this.streams.length; i < ii; i++) {
  35710. var stream = this.streams[i];
  35711. if (stream.getBaseStreams) {
  35712. Util.appendToArray(baseStreams, stream.getBaseStreams());
  35713. }
  35714. }
  35715. return baseStreams;
  35716. };
  35717. return StreamsSequenceStream;
  35718. })();
  35719. var FlateStream = (function FlateStreamClosure() {
  35720. var codeLenCodeMap = new Int32Array([
  35721. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  35722. ]);
  35723. var lengthDecode = new Int32Array([
  35724. 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
  35725. 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
  35726. 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
  35727. 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
  35728. ]);
  35729. var distDecode = new Int32Array([
  35730. 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
  35731. 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
  35732. 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
  35733. 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
  35734. ]);
  35735. var fixedLitCodeTab = [new Int32Array([
  35736. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
  35737. 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
  35738. 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
  35739. 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
  35740. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
  35741. 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
  35742. 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
  35743. 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
  35744. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
  35745. 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
  35746. 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
  35747. 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
  35748. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
  35749. 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
  35750. 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
  35751. 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
  35752. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
  35753. 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
  35754. 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
  35755. 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
  35756. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
  35757. 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
  35758. 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
  35759. 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
  35760. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
  35761. 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
  35762. 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
  35763. 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
  35764. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
  35765. 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
  35766. 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
  35767. 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
  35768. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
  35769. 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
  35770. 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
  35771. 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
  35772. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
  35773. 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
  35774. 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
  35775. 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
  35776. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
  35777. 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
  35778. 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
  35779. 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
  35780. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
  35781. 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
  35782. 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
  35783. 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
  35784. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
  35785. 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
  35786. 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
  35787. 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
  35788. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
  35789. 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
  35790. 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
  35791. 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
  35792. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
  35793. 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
  35794. 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
  35795. 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
  35796. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
  35797. 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
  35798. 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
  35799. 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
  35800. ]), 9];
  35801. var fixedDistCodeTab = [new Int32Array([
  35802. 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
  35803. 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
  35804. 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
  35805. 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
  35806. ]), 5];
  35807. function FlateStream(str, maybeLength) {
  35808. this.str = str;
  35809. this.dict = str.dict;
  35810. var cmf = str.getByte();
  35811. var flg = str.getByte();
  35812. if (cmf === -1 || flg === -1) {
  35813. error('Invalid header in flate stream: ' + cmf + ', ' + flg);
  35814. }
  35815. if ((cmf & 0x0f) !== 0x08) {
  35816. error('Unknown compression method in flate stream: ' + cmf + ', ' + flg);
  35817. }
  35818. if ((((cmf << 8) + flg) % 31) !== 0) {
  35819. error('Bad FCHECK in flate stream: ' + cmf + ', ' + flg);
  35820. }
  35821. if (flg & 0x20) {
  35822. error('FDICT bit set in flate stream: ' + cmf + ', ' + flg);
  35823. }
  35824. this.codeSize = 0;
  35825. this.codeBuf = 0;
  35826. DecodeStream.call(this, maybeLength);
  35827. }
  35828. FlateStream.prototype = Object.create(DecodeStream.prototype);
  35829. FlateStream.prototype.getBits = function FlateStream_getBits(bits) {
  35830. var str = this.str;
  35831. var codeSize = this.codeSize;
  35832. var codeBuf = this.codeBuf;
  35833. var b;
  35834. while (codeSize < bits) {
  35835. if ((b = str.getByte()) === -1) {
  35836. error('Bad encoding in flate stream');
  35837. }
  35838. codeBuf |= b << codeSize;
  35839. codeSize += 8;
  35840. }
  35841. b = codeBuf & ((1 << bits) - 1);
  35842. this.codeBuf = codeBuf >> bits;
  35843. this.codeSize = codeSize -= bits;
  35844. return b;
  35845. };
  35846. FlateStream.prototype.getCode = function FlateStream_getCode(table) {
  35847. var str = this.str;
  35848. var codes = table[0];
  35849. var maxLen = table[1];
  35850. var codeSize = this.codeSize;
  35851. var codeBuf = this.codeBuf;
  35852. var b;
  35853. while (codeSize < maxLen) {
  35854. if ((b = str.getByte()) === -1) {
  35855. // premature end of stream. code might however still be valid.
  35856. // codeSize < codeLen check below guards against incomplete codeVal.
  35857. break;
  35858. }
  35859. codeBuf |= (b << codeSize);
  35860. codeSize += 8;
  35861. }
  35862. var code = codes[codeBuf & ((1 << maxLen) - 1)];
  35863. var codeLen = code >> 16;
  35864. var codeVal = code & 0xffff;
  35865. if (codeLen < 1 || codeSize < codeLen) {
  35866. error('Bad encoding in flate stream');
  35867. }
  35868. this.codeBuf = (codeBuf >> codeLen);
  35869. this.codeSize = (codeSize - codeLen);
  35870. return codeVal;
  35871. };
  35872. FlateStream.prototype.generateHuffmanTable =
  35873. function flateStreamGenerateHuffmanTable(lengths) {
  35874. var n = lengths.length;
  35875. // find max code length
  35876. var maxLen = 0;
  35877. var i;
  35878. for (i = 0; i < n; ++i) {
  35879. if (lengths[i] > maxLen) {
  35880. maxLen = lengths[i];
  35881. }
  35882. }
  35883. // build the table
  35884. var size = 1 << maxLen;
  35885. var codes = new Int32Array(size);
  35886. for (var len = 1, code = 0, skip = 2;
  35887. len <= maxLen;
  35888. ++len, code <<= 1, skip <<= 1) {
  35889. for (var val = 0; val < n; ++val) {
  35890. if (lengths[val] === len) {
  35891. // bit-reverse the code
  35892. var code2 = 0;
  35893. var t = code;
  35894. for (i = 0; i < len; ++i) {
  35895. code2 = (code2 << 1) | (t & 1);
  35896. t >>= 1;
  35897. }
  35898. // fill the table entries
  35899. for (i = code2; i < size; i += skip) {
  35900. codes[i] = (len << 16) | val;
  35901. }
  35902. ++code;
  35903. }
  35904. }
  35905. }
  35906. return [codes, maxLen];
  35907. };
  35908. FlateStream.prototype.readBlock = function FlateStream_readBlock() {
  35909. var buffer, len;
  35910. var str = this.str;
  35911. // read block header
  35912. var hdr = this.getBits(3);
  35913. if (hdr & 1) {
  35914. this.eof = true;
  35915. }
  35916. hdr >>= 1;
  35917. if (hdr === 0) { // uncompressed block
  35918. var b;
  35919. if ((b = str.getByte()) === -1) {
  35920. error('Bad block header in flate stream');
  35921. }
  35922. var blockLen = b;
  35923. if ((b = str.getByte()) === -1) {
  35924. error('Bad block header in flate stream');
  35925. }
  35926. blockLen |= (b << 8);
  35927. if ((b = str.getByte()) === -1) {
  35928. error('Bad block header in flate stream');
  35929. }
  35930. var check = b;
  35931. if ((b = str.getByte()) === -1) {
  35932. error('Bad block header in flate stream');
  35933. }
  35934. check |= (b << 8);
  35935. if (check !== (~blockLen & 0xffff) &&
  35936. (blockLen !== 0 || check !== 0)) {
  35937. // Ignoring error for bad "empty" block (see issue 1277)
  35938. error('Bad uncompressed block length in flate stream');
  35939. }
  35940. this.codeBuf = 0;
  35941. this.codeSize = 0;
  35942. var bufferLength = this.bufferLength;
  35943. buffer = this.ensureBuffer(bufferLength + blockLen);
  35944. var end = bufferLength + blockLen;
  35945. this.bufferLength = end;
  35946. if (blockLen === 0) {
  35947. if (str.peekByte() === -1) {
  35948. this.eof = true;
  35949. }
  35950. } else {
  35951. for (var n = bufferLength; n < end; ++n) {
  35952. if ((b = str.getByte()) === -1) {
  35953. this.eof = true;
  35954. break;
  35955. }
  35956. buffer[n] = b;
  35957. }
  35958. }
  35959. return;
  35960. }
  35961. var litCodeTable;
  35962. var distCodeTable;
  35963. if (hdr === 1) { // compressed block, fixed codes
  35964. litCodeTable = fixedLitCodeTab;
  35965. distCodeTable = fixedDistCodeTab;
  35966. } else if (hdr === 2) { // compressed block, dynamic codes
  35967. var numLitCodes = this.getBits(5) + 257;
  35968. var numDistCodes = this.getBits(5) + 1;
  35969. var numCodeLenCodes = this.getBits(4) + 4;
  35970. // build the code lengths code table
  35971. var codeLenCodeLengths = new Uint8Array(codeLenCodeMap.length);
  35972. var i;
  35973. for (i = 0; i < numCodeLenCodes; ++i) {
  35974. codeLenCodeLengths[codeLenCodeMap[i]] = this.getBits(3);
  35975. }
  35976. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
  35977. // build the literal and distance code tables
  35978. len = 0;
  35979. i = 0;
  35980. var codes = numLitCodes + numDistCodes;
  35981. var codeLengths = new Uint8Array(codes);
  35982. var bitsLength, bitsOffset, what;
  35983. while (i < codes) {
  35984. var code = this.getCode(codeLenCodeTab);
  35985. if (code === 16) {
  35986. bitsLength = 2; bitsOffset = 3; what = len;
  35987. } else if (code === 17) {
  35988. bitsLength = 3; bitsOffset = 3; what = (len = 0);
  35989. } else if (code === 18) {
  35990. bitsLength = 7; bitsOffset = 11; what = (len = 0);
  35991. } else {
  35992. codeLengths[i++] = len = code;
  35993. continue;
  35994. }
  35995. var repeatLength = this.getBits(bitsLength) + bitsOffset;
  35996. while (repeatLength-- > 0) {
  35997. codeLengths[i++] = what;
  35998. }
  35999. }
  36000. litCodeTable =
  36001. this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes));
  36002. distCodeTable =
  36003. this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes));
  36004. } else {
  36005. error('Unknown block type in flate stream');
  36006. }
  36007. buffer = this.buffer;
  36008. var limit = buffer ? buffer.length : 0;
  36009. var pos = this.bufferLength;
  36010. while (true) {
  36011. var code1 = this.getCode(litCodeTable);
  36012. if (code1 < 256) {
  36013. if (pos + 1 >= limit) {
  36014. buffer = this.ensureBuffer(pos + 1);
  36015. limit = buffer.length;
  36016. }
  36017. buffer[pos++] = code1;
  36018. continue;
  36019. }
  36020. if (code1 === 256) {
  36021. this.bufferLength = pos;
  36022. return;
  36023. }
  36024. code1 -= 257;
  36025. code1 = lengthDecode[code1];
  36026. var code2 = code1 >> 16;
  36027. if (code2 > 0) {
  36028. code2 = this.getBits(code2);
  36029. }
  36030. len = (code1 & 0xffff) + code2;
  36031. code1 = this.getCode(distCodeTable);
  36032. code1 = distDecode[code1];
  36033. code2 = code1 >> 16;
  36034. if (code2 > 0) {
  36035. code2 = this.getBits(code2);
  36036. }
  36037. var dist = (code1 & 0xffff) + code2;
  36038. if (pos + len >= limit) {
  36039. buffer = this.ensureBuffer(pos + len);
  36040. limit = buffer.length;
  36041. }
  36042. for (var k = 0; k < len; ++k, ++pos) {
  36043. buffer[pos] = buffer[pos - dist];
  36044. }
  36045. }
  36046. };
  36047. return FlateStream;
  36048. })();
  36049. var PredictorStream = (function PredictorStreamClosure() {
  36050. function PredictorStream(str, maybeLength, params) {
  36051. var predictor = this.predictor = params.get('Predictor') || 1;
  36052. if (predictor <= 1) {
  36053. return str; // no prediction
  36054. }
  36055. if (predictor !== 2 && (predictor < 10 || predictor > 15)) {
  36056. error('Unsupported predictor: ' + predictor);
  36057. }
  36058. if (predictor === 2) {
  36059. this.readBlock = this.readBlockTiff;
  36060. } else {
  36061. this.readBlock = this.readBlockPng;
  36062. }
  36063. this.str = str;
  36064. this.dict = str.dict;
  36065. var colors = this.colors = params.get('Colors') || 1;
  36066. var bits = this.bits = params.get('BitsPerComponent') || 8;
  36067. var columns = this.columns = params.get('Columns') || 1;
  36068. this.pixBytes = (colors * bits + 7) >> 3;
  36069. this.rowBytes = (columns * colors * bits + 7) >> 3;
  36070. DecodeStream.call(this, maybeLength);
  36071. return this;
  36072. }
  36073. PredictorStream.prototype = Object.create(DecodeStream.prototype);
  36074. PredictorStream.prototype.readBlockTiff =
  36075. function predictorStreamReadBlockTiff() {
  36076. var rowBytes = this.rowBytes;
  36077. var bufferLength = this.bufferLength;
  36078. var buffer = this.ensureBuffer(bufferLength + rowBytes);
  36079. var bits = this.bits;
  36080. var colors = this.colors;
  36081. var rawBytes = this.str.getBytes(rowBytes);
  36082. this.eof = !rawBytes.length;
  36083. if (this.eof) {
  36084. return;
  36085. }
  36086. var inbuf = 0, outbuf = 0;
  36087. var inbits = 0, outbits = 0;
  36088. var pos = bufferLength;
  36089. var i;
  36090. if (bits === 1) {
  36091. for (i = 0; i < rowBytes; ++i) {
  36092. var c = rawBytes[i];
  36093. inbuf = (inbuf << 8) | c;
  36094. // bitwise addition is exclusive or
  36095. // first shift inbuf and then add
  36096. buffer[pos++] = (c ^ (inbuf >> colors)) & 0xFF;
  36097. // truncate inbuf (assumes colors < 16)
  36098. inbuf &= 0xFFFF;
  36099. }
  36100. } else if (bits === 8) {
  36101. for (i = 0; i < colors; ++i) {
  36102. buffer[pos++] = rawBytes[i];
  36103. }
  36104. for (; i < rowBytes; ++i) {
  36105. buffer[pos] = buffer[pos - colors] + rawBytes[i];
  36106. pos++;
  36107. }
  36108. } else {
  36109. var compArray = new Uint8Array(colors + 1);
  36110. var bitMask = (1 << bits) - 1;
  36111. var j = 0, k = bufferLength;
  36112. var columns = this.columns;
  36113. for (i = 0; i < columns; ++i) {
  36114. for (var kk = 0; kk < colors; ++kk) {
  36115. if (inbits < bits) {
  36116. inbuf = (inbuf << 8) | (rawBytes[j++] & 0xFF);
  36117. inbits += 8;
  36118. }
  36119. compArray[kk] = (compArray[kk] +
  36120. (inbuf >> (inbits - bits))) & bitMask;
  36121. inbits -= bits;
  36122. outbuf = (outbuf << bits) | compArray[kk];
  36123. outbits += bits;
  36124. if (outbits >= 8) {
  36125. buffer[k++] = (outbuf >> (outbits - 8)) & 0xFF;
  36126. outbits -= 8;
  36127. }
  36128. }
  36129. }
  36130. if (outbits > 0) {
  36131. buffer[k++] = (outbuf << (8 - outbits)) +
  36132. (inbuf & ((1 << (8 - outbits)) - 1));
  36133. }
  36134. }
  36135. this.bufferLength += rowBytes;
  36136. };
  36137. PredictorStream.prototype.readBlockPng =
  36138. function predictorStreamReadBlockPng() {
  36139. var rowBytes = this.rowBytes;
  36140. var pixBytes = this.pixBytes;
  36141. var predictor = this.str.getByte();
  36142. var rawBytes = this.str.getBytes(rowBytes);
  36143. this.eof = !rawBytes.length;
  36144. if (this.eof) {
  36145. return;
  36146. }
  36147. var bufferLength = this.bufferLength;
  36148. var buffer = this.ensureBuffer(bufferLength + rowBytes);
  36149. var prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength);
  36150. if (prevRow.length === 0) {
  36151. prevRow = new Uint8Array(rowBytes);
  36152. }
  36153. var i, j = bufferLength, up, c;
  36154. switch (predictor) {
  36155. case 0:
  36156. for (i = 0; i < rowBytes; ++i) {
  36157. buffer[j++] = rawBytes[i];
  36158. }
  36159. break;
  36160. case 1:
  36161. for (i = 0; i < pixBytes; ++i) {
  36162. buffer[j++] = rawBytes[i];
  36163. }
  36164. for (; i < rowBytes; ++i) {
  36165. buffer[j] = (buffer[j - pixBytes] + rawBytes[i]) & 0xFF;
  36166. j++;
  36167. }
  36168. break;
  36169. case 2:
  36170. for (i = 0; i < rowBytes; ++i) {
  36171. buffer[j++] = (prevRow[i] + rawBytes[i]) & 0xFF;
  36172. }
  36173. break;
  36174. case 3:
  36175. for (i = 0; i < pixBytes; ++i) {
  36176. buffer[j++] = (prevRow[i] >> 1) + rawBytes[i];
  36177. }
  36178. for (; i < rowBytes; ++i) {
  36179. buffer[j] = (((prevRow[i] + buffer[j - pixBytes]) >> 1) +
  36180. rawBytes[i]) & 0xFF;
  36181. j++;
  36182. }
  36183. break;
  36184. case 4:
  36185. // we need to save the up left pixels values. the simplest way
  36186. // is to create a new buffer
  36187. for (i = 0; i < pixBytes; ++i) {
  36188. up = prevRow[i];
  36189. c = rawBytes[i];
  36190. buffer[j++] = up + c;
  36191. }
  36192. for (; i < rowBytes; ++i) {
  36193. up = prevRow[i];
  36194. var upLeft = prevRow[i - pixBytes];
  36195. var left = buffer[j - pixBytes];
  36196. var p = left + up - upLeft;
  36197. var pa = p - left;
  36198. if (pa < 0) {
  36199. pa = -pa;
  36200. }
  36201. var pb = p - up;
  36202. if (pb < 0) {
  36203. pb = -pb;
  36204. }
  36205. var pc = p - upLeft;
  36206. if (pc < 0) {
  36207. pc = -pc;
  36208. }
  36209. c = rawBytes[i];
  36210. if (pa <= pb && pa <= pc) {
  36211. buffer[j++] = left + c;
  36212. } else if (pb <= pc) {
  36213. buffer[j++] = up + c;
  36214. } else {
  36215. buffer[j++] = upLeft + c;
  36216. }
  36217. }
  36218. break;
  36219. default:
  36220. error('Unsupported predictor: ' + predictor);
  36221. }
  36222. this.bufferLength += rowBytes;
  36223. };
  36224. return PredictorStream;
  36225. })();
  36226. /**
  36227. * Depending on the type of JPEG a JpegStream is handled in different ways. For
  36228. * JPEG's that are supported natively such as DeviceGray and DeviceRGB the image
  36229. * data is stored and then loaded by the browser. For unsupported JPEG's we use
  36230. * a library to decode these images and the stream behaves like all the other
  36231. * DecodeStreams.
  36232. */
  36233. var JpegStream = (function JpegStreamClosure() {
  36234. function JpegStream(stream, maybeLength, dict, xref) {
  36235. // Some images may contain 'junk' before the SOI (start-of-image) marker.
  36236. // Note: this seems to mainly affect inline images.
  36237. var ch;
  36238. while ((ch = stream.getByte()) !== -1) {
  36239. if (ch === 0xFF) { // Find the first byte of the SOI marker (0xFFD8).
  36240. stream.skip(-1); // Reset the stream position to the SOI.
  36241. break;
  36242. }
  36243. }
  36244. this.stream = stream;
  36245. this.maybeLength = maybeLength;
  36246. this.dict = dict;
  36247. DecodeStream.call(this, maybeLength);
  36248. }
  36249. JpegStream.prototype = Object.create(DecodeStream.prototype);
  36250. Object.defineProperty(JpegStream.prototype, 'bytes', {
  36251. get: function JpegStream_bytes() {
  36252. // If this.maybeLength is null, we'll get the entire stream.
  36253. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  36254. },
  36255. configurable: true
  36256. });
  36257. JpegStream.prototype.ensureBuffer = function JpegStream_ensureBuffer(req) {
  36258. if (this.bufferLength) {
  36259. return;
  36260. }
  36261. try {
  36262. var jpegImage = new JpegImage();
  36263. // checking if values needs to be transformed before conversion
  36264. if (this.forceRGB && this.dict && isArray(this.dict.get('Decode'))) {
  36265. var decodeArr = this.dict.get('Decode');
  36266. var bitsPerComponent = this.dict.get('BitsPerComponent') || 8;
  36267. var decodeArrLength = decodeArr.length;
  36268. var transform = new Int32Array(decodeArrLength);
  36269. var transformNeeded = false;
  36270. var maxValue = (1 << bitsPerComponent) - 1;
  36271. for (var i = 0; i < decodeArrLength; i += 2) {
  36272. transform[i] = ((decodeArr[i + 1] - decodeArr[i]) * 256) | 0;
  36273. transform[i + 1] = (decodeArr[i] * maxValue) | 0;
  36274. if (transform[i] !== 256 || transform[i + 1] !== 0) {
  36275. transformNeeded = true;
  36276. }
  36277. }
  36278. if (transformNeeded) {
  36279. jpegImage.decodeTransform = transform;
  36280. }
  36281. }
  36282. jpegImage.parse(this.bytes);
  36283. var data = jpegImage.getData(this.drawWidth, this.drawHeight,
  36284. this.forceRGB);
  36285. this.buffer = data;
  36286. this.bufferLength = data.length;
  36287. this.eof = true;
  36288. } catch (e) {
  36289. error('JPEG error: ' + e);
  36290. }
  36291. };
  36292. JpegStream.prototype.getBytes = function JpegStream_getBytes(length) {
  36293. this.ensureBuffer();
  36294. return this.buffer;
  36295. };
  36296. JpegStream.prototype.getIR = function JpegStream_getIR() {
  36297. return PDFJS.createObjectURL(this.bytes, 'image/jpeg');
  36298. };
  36299. /**
  36300. * Checks if the image can be decoded and displayed by the browser without any
  36301. * further processing such as color space conversions.
  36302. */
  36303. JpegStream.prototype.isNativelySupported =
  36304. function JpegStream_isNativelySupported(xref, res) {
  36305. var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);
  36306. return cs.name === 'DeviceGray' || cs.name === 'DeviceRGB';
  36307. };
  36308. /**
  36309. * Checks if the image can be decoded by the browser.
  36310. */
  36311. JpegStream.prototype.isNativelyDecodable =
  36312. function JpegStream_isNativelyDecodable(xref, res) {
  36313. var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);
  36314. var numComps = cs.numComps;
  36315. return numComps === 1 || numComps === 3;
  36316. };
  36317. return JpegStream;
  36318. })();
  36319. /**
  36320. * For JPEG 2000's we use a library to decode these images and
  36321. * the stream behaves like all the other DecodeStreams.
  36322. */
  36323. var JpxStream = (function JpxStreamClosure() {
  36324. function JpxStream(stream, maybeLength, dict) {
  36325. this.stream = stream;
  36326. this.maybeLength = maybeLength;
  36327. this.dict = dict;
  36328. DecodeStream.call(this, maybeLength);
  36329. }
  36330. JpxStream.prototype = Object.create(DecodeStream.prototype);
  36331. Object.defineProperty(JpxStream.prototype, 'bytes', {
  36332. get: function JpxStream_bytes() {
  36333. // If this.maybeLength is null, we'll get the entire stream.
  36334. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  36335. },
  36336. configurable: true
  36337. });
  36338. JpxStream.prototype.ensureBuffer = function JpxStream_ensureBuffer(req) {
  36339. if (this.bufferLength) {
  36340. return;
  36341. }
  36342. var jpxImage = new JpxImage();
  36343. jpxImage.parse(this.bytes);
  36344. var width = jpxImage.width;
  36345. var height = jpxImage.height;
  36346. var componentsCount = jpxImage.componentsCount;
  36347. var tileCount = jpxImage.tiles.length;
  36348. if (tileCount === 1) {
  36349. this.buffer = jpxImage.tiles[0].items;
  36350. } else {
  36351. var data = new Uint8Array(width * height * componentsCount);
  36352. for (var k = 0; k < tileCount; k++) {
  36353. var tileComponents = jpxImage.tiles[k];
  36354. var tileWidth = tileComponents.width;
  36355. var tileHeight = tileComponents.height;
  36356. var tileLeft = tileComponents.left;
  36357. var tileTop = tileComponents.top;
  36358. var src = tileComponents.items;
  36359. var srcPosition = 0;
  36360. var dataPosition = (width * tileTop + tileLeft) * componentsCount;
  36361. var imgRowSize = width * componentsCount;
  36362. var tileRowSize = tileWidth * componentsCount;
  36363. for (var j = 0; j < tileHeight; j++) {
  36364. var rowBytes = src.subarray(srcPosition, srcPosition + tileRowSize);
  36365. data.set(rowBytes, dataPosition);
  36366. srcPosition += tileRowSize;
  36367. dataPosition += imgRowSize;
  36368. }
  36369. }
  36370. this.buffer = data;
  36371. }
  36372. this.bufferLength = this.buffer.length;
  36373. this.eof = true;
  36374. };
  36375. return JpxStream;
  36376. })();
  36377. /**
  36378. * For JBIG2's we use a library to decode these images and
  36379. * the stream behaves like all the other DecodeStreams.
  36380. */
  36381. var Jbig2Stream = (function Jbig2StreamClosure() {
  36382. function Jbig2Stream(stream, maybeLength, dict) {
  36383. this.stream = stream;
  36384. this.maybeLength = maybeLength;
  36385. this.dict = dict;
  36386. DecodeStream.call(this, maybeLength);
  36387. }
  36388. Jbig2Stream.prototype = Object.create(DecodeStream.prototype);
  36389. Object.defineProperty(Jbig2Stream.prototype, 'bytes', {
  36390. get: function Jbig2Stream_bytes() {
  36391. // If this.maybeLength is null, we'll get the entire stream.
  36392. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  36393. },
  36394. configurable: true
  36395. });
  36396. Jbig2Stream.prototype.ensureBuffer = function Jbig2Stream_ensureBuffer(req) {
  36397. if (this.bufferLength) {
  36398. return;
  36399. }
  36400. var jbig2Image = new Jbig2Image();
  36401. var chunks = [], xref = this.dict.xref;
  36402. var decodeParams = xref.fetchIfRef(this.dict.get('DecodeParms'));
  36403. // According to the PDF specification, DecodeParms can be either
  36404. // a dictionary, or an array whose elements are dictionaries.
  36405. if (isArray(decodeParams)) {
  36406. if (decodeParams.length > 1) {
  36407. warn('JBIG2 - \'DecodeParms\' array with multiple elements ' +
  36408. 'not supported.');
  36409. }
  36410. decodeParams = xref.fetchIfRef(decodeParams[0]);
  36411. }
  36412. if (decodeParams && decodeParams.has('JBIG2Globals')) {
  36413. var globalsStream = decodeParams.get('JBIG2Globals');
  36414. var globals = globalsStream.getBytes();
  36415. chunks.push({data: globals, start: 0, end: globals.length});
  36416. }
  36417. chunks.push({data: this.bytes, start: 0, end: this.bytes.length});
  36418. var data = jbig2Image.parseChunks(chunks);
  36419. var dataLength = data.length;
  36420. // JBIG2 had black as 1 and white as 0, inverting the colors
  36421. for (var i = 0; i < dataLength; i++) {
  36422. data[i] ^= 0xFF;
  36423. }
  36424. this.buffer = data;
  36425. this.bufferLength = dataLength;
  36426. this.eof = true;
  36427. };
  36428. return Jbig2Stream;
  36429. })();
  36430. var DecryptStream = (function DecryptStreamClosure() {
  36431. function DecryptStream(str, maybeLength, decrypt) {
  36432. this.str = str;
  36433. this.dict = str.dict;
  36434. this.decrypt = decrypt;
  36435. this.nextChunk = null;
  36436. this.initialized = false;
  36437. DecodeStream.call(this, maybeLength);
  36438. }
  36439. var chunkSize = 512;
  36440. DecryptStream.prototype = Object.create(DecodeStream.prototype);
  36441. DecryptStream.prototype.readBlock = function DecryptStream_readBlock() {
  36442. var chunk;
  36443. if (this.initialized) {
  36444. chunk = this.nextChunk;
  36445. } else {
  36446. chunk = this.str.getBytes(chunkSize);
  36447. this.initialized = true;
  36448. }
  36449. if (!chunk || chunk.length === 0) {
  36450. this.eof = true;
  36451. return;
  36452. }
  36453. this.nextChunk = this.str.getBytes(chunkSize);
  36454. var hasMoreData = this.nextChunk && this.nextChunk.length > 0;
  36455. var decrypt = this.decrypt;
  36456. chunk = decrypt(chunk, !hasMoreData);
  36457. var bufferLength = this.bufferLength;
  36458. var i, n = chunk.length;
  36459. var buffer = this.ensureBuffer(bufferLength + n);
  36460. for (i = 0; i < n; i++) {
  36461. buffer[bufferLength++] = chunk[i];
  36462. }
  36463. this.bufferLength = bufferLength;
  36464. };
  36465. return DecryptStream;
  36466. })();
  36467. var Ascii85Stream = (function Ascii85StreamClosure() {
  36468. function Ascii85Stream(str, maybeLength) {
  36469. this.str = str;
  36470. this.dict = str.dict;
  36471. this.input = new Uint8Array(5);
  36472. // Most streams increase in size when decoded, but Ascii85 streams
  36473. // typically shrink by ~20%.
  36474. if (maybeLength) {
  36475. maybeLength = 0.8 * maybeLength;
  36476. }
  36477. DecodeStream.call(this, maybeLength);
  36478. }
  36479. Ascii85Stream.prototype = Object.create(DecodeStream.prototype);
  36480. Ascii85Stream.prototype.readBlock = function Ascii85Stream_readBlock() {
  36481. var TILDA_CHAR = 0x7E; // '~'
  36482. var Z_LOWER_CHAR = 0x7A; // 'z'
  36483. var EOF = -1;
  36484. var str = this.str;
  36485. var c = str.getByte();
  36486. while (Lexer.isSpace(c)) {
  36487. c = str.getByte();
  36488. }
  36489. if (c === EOF || c === TILDA_CHAR) {
  36490. this.eof = true;
  36491. return;
  36492. }
  36493. var bufferLength = this.bufferLength, buffer;
  36494. var i;
  36495. // special code for z
  36496. if (c === Z_LOWER_CHAR) {
  36497. buffer = this.ensureBuffer(bufferLength + 4);
  36498. for (i = 0; i < 4; ++i) {
  36499. buffer[bufferLength + i] = 0;
  36500. }
  36501. this.bufferLength += 4;
  36502. } else {
  36503. var input = this.input;
  36504. input[0] = c;
  36505. for (i = 1; i < 5; ++i) {
  36506. c = str.getByte();
  36507. while (Lexer.isSpace(c)) {
  36508. c = str.getByte();
  36509. }
  36510. input[i] = c;
  36511. if (c === EOF || c === TILDA_CHAR) {
  36512. break;
  36513. }
  36514. }
  36515. buffer = this.ensureBuffer(bufferLength + i - 1);
  36516. this.bufferLength += i - 1;
  36517. // partial ending;
  36518. if (i < 5) {
  36519. for (; i < 5; ++i) {
  36520. input[i] = 0x21 + 84;
  36521. }
  36522. this.eof = true;
  36523. }
  36524. var t = 0;
  36525. for (i = 0; i < 5; ++i) {
  36526. t = t * 85 + (input[i] - 0x21);
  36527. }
  36528. for (i = 3; i >= 0; --i) {
  36529. buffer[bufferLength + i] = t & 0xFF;
  36530. t >>= 8;
  36531. }
  36532. }
  36533. };
  36534. return Ascii85Stream;
  36535. })();
  36536. var AsciiHexStream = (function AsciiHexStreamClosure() {
  36537. function AsciiHexStream(str, maybeLength) {
  36538. this.str = str;
  36539. this.dict = str.dict;
  36540. this.firstDigit = -1;
  36541. // Most streams increase in size when decoded, but AsciiHex streams shrink
  36542. // by 50%.
  36543. if (maybeLength) {
  36544. maybeLength = 0.5 * maybeLength;
  36545. }
  36546. DecodeStream.call(this, maybeLength);
  36547. }
  36548. AsciiHexStream.prototype = Object.create(DecodeStream.prototype);
  36549. AsciiHexStream.prototype.readBlock = function AsciiHexStream_readBlock() {
  36550. var UPSTREAM_BLOCK_SIZE = 8000;
  36551. var bytes = this.str.getBytes(UPSTREAM_BLOCK_SIZE);
  36552. if (!bytes.length) {
  36553. this.eof = true;
  36554. return;
  36555. }
  36556. var maxDecodeLength = (bytes.length + 1) >> 1;
  36557. var buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);
  36558. var bufferLength = this.bufferLength;
  36559. var firstDigit = this.firstDigit;
  36560. for (var i = 0, ii = bytes.length; i < ii; i++) {
  36561. var ch = bytes[i], digit;
  36562. if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
  36563. digit = ch & 0x0F;
  36564. } else if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
  36565. // 'A'-'Z', 'a'-'z'
  36566. digit = (ch & 0x0F) + 9;
  36567. } else if (ch === 0x3E) { // '>'
  36568. this.eof = true;
  36569. break;
  36570. } else { // probably whitespace
  36571. continue; // ignoring
  36572. }
  36573. if (firstDigit < 0) {
  36574. firstDigit = digit;
  36575. } else {
  36576. buffer[bufferLength++] = (firstDigit << 4) | digit;
  36577. firstDigit = -1;
  36578. }
  36579. }
  36580. if (firstDigit >= 0 && this.eof) {
  36581. // incomplete byte
  36582. buffer[bufferLength++] = (firstDigit << 4);
  36583. firstDigit = -1;
  36584. }
  36585. this.firstDigit = firstDigit;
  36586. this.bufferLength = bufferLength;
  36587. };
  36588. return AsciiHexStream;
  36589. })();
  36590. var RunLengthStream = (function RunLengthStreamClosure() {
  36591. function RunLengthStream(str, maybeLength) {
  36592. this.str = str;
  36593. this.dict = str.dict;
  36594. DecodeStream.call(this, maybeLength);
  36595. }
  36596. RunLengthStream.prototype = Object.create(DecodeStream.prototype);
  36597. RunLengthStream.prototype.readBlock = function RunLengthStream_readBlock() {
  36598. // The repeatHeader has following format. The first byte defines type of run
  36599. // and amount of bytes to repeat/copy: n = 0 through 127 - copy next n bytes
  36600. // (in addition to the second byte from the header), n = 129 through 255 -
  36601. // duplicate the second byte from the header (257 - n) times, n = 128 - end.
  36602. var repeatHeader = this.str.getBytes(2);
  36603. if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] === 128) {
  36604. this.eof = true;
  36605. return;
  36606. }
  36607. var buffer;
  36608. var bufferLength = this.bufferLength;
  36609. var n = repeatHeader[0];
  36610. if (n < 128) {
  36611. // copy n bytes
  36612. buffer = this.ensureBuffer(bufferLength + n + 1);
  36613. buffer[bufferLength++] = repeatHeader[1];
  36614. if (n > 0) {
  36615. var source = this.str.getBytes(n);
  36616. buffer.set(source, bufferLength);
  36617. bufferLength += n;
  36618. }
  36619. } else {
  36620. n = 257 - n;
  36621. var b = repeatHeader[1];
  36622. buffer = this.ensureBuffer(bufferLength + n + 1);
  36623. for (var i = 0; i < n; i++) {
  36624. buffer[bufferLength++] = b;
  36625. }
  36626. }
  36627. this.bufferLength = bufferLength;
  36628. };
  36629. return RunLengthStream;
  36630. })();
  36631. var CCITTFaxStream = (function CCITTFaxStreamClosure() {
  36632. var ccittEOL = -2;
  36633. var twoDimPass = 0;
  36634. var twoDimHoriz = 1;
  36635. var twoDimVert0 = 2;
  36636. var twoDimVertR1 = 3;
  36637. var twoDimVertL1 = 4;
  36638. var twoDimVertR2 = 5;
  36639. var twoDimVertL2 = 6;
  36640. var twoDimVertR3 = 7;
  36641. var twoDimVertL3 = 8;
  36642. var twoDimTable = [
  36643. [-1, -1], [-1, -1], // 000000x
  36644. [7, twoDimVertL3], // 0000010
  36645. [7, twoDimVertR3], // 0000011
  36646. [6, twoDimVertL2], [6, twoDimVertL2], // 000010x
  36647. [6, twoDimVertR2], [6, twoDimVertR2], // 000011x
  36648. [4, twoDimPass], [4, twoDimPass], // 0001xxx
  36649. [4, twoDimPass], [4, twoDimPass],
  36650. [4, twoDimPass], [4, twoDimPass],
  36651. [4, twoDimPass], [4, twoDimPass],
  36652. [3, twoDimHoriz], [3, twoDimHoriz], // 001xxxx
  36653. [3, twoDimHoriz], [3, twoDimHoriz],
  36654. [3, twoDimHoriz], [3, twoDimHoriz],
  36655. [3, twoDimHoriz], [3, twoDimHoriz],
  36656. [3, twoDimHoriz], [3, twoDimHoriz],
  36657. [3, twoDimHoriz], [3, twoDimHoriz],
  36658. [3, twoDimHoriz], [3, twoDimHoriz],
  36659. [3, twoDimHoriz], [3, twoDimHoriz],
  36660. [3, twoDimVertL1], [3, twoDimVertL1], // 010xxxx
  36661. [3, twoDimVertL1], [3, twoDimVertL1],
  36662. [3, twoDimVertL1], [3, twoDimVertL1],
  36663. [3, twoDimVertL1], [3, twoDimVertL1],
  36664. [3, twoDimVertL1], [3, twoDimVertL1],
  36665. [3, twoDimVertL1], [3, twoDimVertL1],
  36666. [3, twoDimVertL1], [3, twoDimVertL1],
  36667. [3, twoDimVertL1], [3, twoDimVertL1],
  36668. [3, twoDimVertR1], [3, twoDimVertR1], // 011xxxx
  36669. [3, twoDimVertR1], [3, twoDimVertR1],
  36670. [3, twoDimVertR1], [3, twoDimVertR1],
  36671. [3, twoDimVertR1], [3, twoDimVertR1],
  36672. [3, twoDimVertR1], [3, twoDimVertR1],
  36673. [3, twoDimVertR1], [3, twoDimVertR1],
  36674. [3, twoDimVertR1], [3, twoDimVertR1],
  36675. [3, twoDimVertR1], [3, twoDimVertR1],
  36676. [1, twoDimVert0], [1, twoDimVert0], // 1xxxxxx
  36677. [1, twoDimVert0], [1, twoDimVert0],
  36678. [1, twoDimVert0], [1, twoDimVert0],
  36679. [1, twoDimVert0], [1, twoDimVert0],
  36680. [1, twoDimVert0], [1, twoDimVert0],
  36681. [1, twoDimVert0], [1, twoDimVert0],
  36682. [1, twoDimVert0], [1, twoDimVert0],
  36683. [1, twoDimVert0], [1, twoDimVert0],
  36684. [1, twoDimVert0], [1, twoDimVert0],
  36685. [1, twoDimVert0], [1, twoDimVert0],
  36686. [1, twoDimVert0], [1, twoDimVert0],
  36687. [1, twoDimVert0], [1, twoDimVert0],
  36688. [1, twoDimVert0], [1, twoDimVert0],
  36689. [1, twoDimVert0], [1, twoDimVert0],
  36690. [1, twoDimVert0], [1, twoDimVert0],
  36691. [1, twoDimVert0], [1, twoDimVert0],
  36692. [1, twoDimVert0], [1, twoDimVert0],
  36693. [1, twoDimVert0], [1, twoDimVert0],
  36694. [1, twoDimVert0], [1, twoDimVert0],
  36695. [1, twoDimVert0], [1, twoDimVert0],
  36696. [1, twoDimVert0], [1, twoDimVert0],
  36697. [1, twoDimVert0], [1, twoDimVert0],
  36698. [1, twoDimVert0], [1, twoDimVert0],
  36699. [1, twoDimVert0], [1, twoDimVert0],
  36700. [1, twoDimVert0], [1, twoDimVert0],
  36701. [1, twoDimVert0], [1, twoDimVert0],
  36702. [1, twoDimVert0], [1, twoDimVert0],
  36703. [1, twoDimVert0], [1, twoDimVert0],
  36704. [1, twoDimVert0], [1, twoDimVert0],
  36705. [1, twoDimVert0], [1, twoDimVert0],
  36706. [1, twoDimVert0], [1, twoDimVert0],
  36707. [1, twoDimVert0], [1, twoDimVert0]
  36708. ];
  36709. var whiteTable1 = [
  36710. [-1, -1], // 00000
  36711. [12, ccittEOL], // 00001
  36712. [-1, -1], [-1, -1], // 0001x
  36713. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 001xx
  36714. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 010xx
  36715. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 011xx
  36716. [11, 1792], [11, 1792], // 1000x
  36717. [12, 1984], // 10010
  36718. [12, 2048], // 10011
  36719. [12, 2112], // 10100
  36720. [12, 2176], // 10101
  36721. [12, 2240], // 10110
  36722. [12, 2304], // 10111
  36723. [11, 1856], [11, 1856], // 1100x
  36724. [11, 1920], [11, 1920], // 1101x
  36725. [12, 2368], // 11100
  36726. [12, 2432], // 11101
  36727. [12, 2496], // 11110
  36728. [12, 2560] // 11111
  36729. ];
  36730. var whiteTable2 = [
  36731. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 0000000xx
  36732. [8, 29], [8, 29], // 00000010x
  36733. [8, 30], [8, 30], // 00000011x
  36734. [8, 45], [8, 45], // 00000100x
  36735. [8, 46], [8, 46], // 00000101x
  36736. [7, 22], [7, 22], [7, 22], [7, 22], // 0000011xx
  36737. [7, 23], [7, 23], [7, 23], [7, 23], // 0000100xx
  36738. [8, 47], [8, 47], // 00001010x
  36739. [8, 48], [8, 48], // 00001011x
  36740. [6, 13], [6, 13], [6, 13], [6, 13], // 000011xxx
  36741. [6, 13], [6, 13], [6, 13], [6, 13],
  36742. [7, 20], [7, 20], [7, 20], [7, 20], // 0001000xx
  36743. [8, 33], [8, 33], // 00010010x
  36744. [8, 34], [8, 34], // 00010011x
  36745. [8, 35], [8, 35], // 00010100x
  36746. [8, 36], [8, 36], // 00010101x
  36747. [8, 37], [8, 37], // 00010110x
  36748. [8, 38], [8, 38], // 00010111x
  36749. [7, 19], [7, 19], [7, 19], [7, 19], // 0001100xx
  36750. [8, 31], [8, 31], // 00011010x
  36751. [8, 32], [8, 32], // 00011011x
  36752. [6, 1], [6, 1], [6, 1], [6, 1], // 000111xxx
  36753. [6, 1], [6, 1], [6, 1], [6, 1],
  36754. [6, 12], [6, 12], [6, 12], [6, 12], // 001000xxx
  36755. [6, 12], [6, 12], [6, 12], [6, 12],
  36756. [8, 53], [8, 53], // 00100100x
  36757. [8, 54], [8, 54], // 00100101x
  36758. [7, 26], [7, 26], [7, 26], [7, 26], // 0010011xx
  36759. [8, 39], [8, 39], // 00101000x
  36760. [8, 40], [8, 40], // 00101001x
  36761. [8, 41], [8, 41], // 00101010x
  36762. [8, 42], [8, 42], // 00101011x
  36763. [8, 43], [8, 43], // 00101100x
  36764. [8, 44], [8, 44], // 00101101x
  36765. [7, 21], [7, 21], [7, 21], [7, 21], // 0010111xx
  36766. [7, 28], [7, 28], [7, 28], [7, 28], // 0011000xx
  36767. [8, 61], [8, 61], // 00110010x
  36768. [8, 62], [8, 62], // 00110011x
  36769. [8, 63], [8, 63], // 00110100x
  36770. [8, 0], [8, 0], // 00110101x
  36771. [8, 320], [8, 320], // 00110110x
  36772. [8, 384], [8, 384], // 00110111x
  36773. [5, 10], [5, 10], [5, 10], [5, 10], // 00111xxxx
  36774. [5, 10], [5, 10], [5, 10], [5, 10],
  36775. [5, 10], [5, 10], [5, 10], [5, 10],
  36776. [5, 10], [5, 10], [5, 10], [5, 10],
  36777. [5, 11], [5, 11], [5, 11], [5, 11], // 01000xxxx
  36778. [5, 11], [5, 11], [5, 11], [5, 11],
  36779. [5, 11], [5, 11], [5, 11], [5, 11],
  36780. [5, 11], [5, 11], [5, 11], [5, 11],
  36781. [7, 27], [7, 27], [7, 27], [7, 27], // 0100100xx
  36782. [8, 59], [8, 59], // 01001010x
  36783. [8, 60], [8, 60], // 01001011x
  36784. [9, 1472], // 010011000
  36785. [9, 1536], // 010011001
  36786. [9, 1600], // 010011010
  36787. [9, 1728], // 010011011
  36788. [7, 18], [7, 18], [7, 18], [7, 18], // 0100111xx
  36789. [7, 24], [7, 24], [7, 24], [7, 24], // 0101000xx
  36790. [8, 49], [8, 49], // 01010010x
  36791. [8, 50], [8, 50], // 01010011x
  36792. [8, 51], [8, 51], // 01010100x
  36793. [8, 52], [8, 52], // 01010101x
  36794. [7, 25], [7, 25], [7, 25], [7, 25], // 0101011xx
  36795. [8, 55], [8, 55], // 01011000x
  36796. [8, 56], [8, 56], // 01011001x
  36797. [8, 57], [8, 57], // 01011010x
  36798. [8, 58], [8, 58], // 01011011x
  36799. [6, 192], [6, 192], [6, 192], [6, 192], // 010111xxx
  36800. [6, 192], [6, 192], [6, 192], [6, 192],
  36801. [6, 1664], [6, 1664], [6, 1664], [6, 1664], // 011000xxx
  36802. [6, 1664], [6, 1664], [6, 1664], [6, 1664],
  36803. [8, 448], [8, 448], // 01100100x
  36804. [8, 512], [8, 512], // 01100101x
  36805. [9, 704], // 011001100
  36806. [9, 768], // 011001101
  36807. [8, 640], [8, 640], // 01100111x
  36808. [8, 576], [8, 576], // 01101000x
  36809. [9, 832], // 011010010
  36810. [9, 896], // 011010011
  36811. [9, 960], // 011010100
  36812. [9, 1024], // 011010101
  36813. [9, 1088], // 011010110
  36814. [9, 1152], // 011010111
  36815. [9, 1216], // 011011000
  36816. [9, 1280], // 011011001
  36817. [9, 1344], // 011011010
  36818. [9, 1408], // 011011011
  36819. [7, 256], [7, 256], [7, 256], [7, 256], // 0110111xx
  36820. [4, 2], [4, 2], [4, 2], [4, 2], // 0111xxxxx
  36821. [4, 2], [4, 2], [4, 2], [4, 2],
  36822. [4, 2], [4, 2], [4, 2], [4, 2],
  36823. [4, 2], [4, 2], [4, 2], [4, 2],
  36824. [4, 2], [4, 2], [4, 2], [4, 2],
  36825. [4, 2], [4, 2], [4, 2], [4, 2],
  36826. [4, 2], [4, 2], [4, 2], [4, 2],
  36827. [4, 2], [4, 2], [4, 2], [4, 2],
  36828. [4, 3], [4, 3], [4, 3], [4, 3], // 1000xxxxx
  36829. [4, 3], [4, 3], [4, 3], [4, 3],
  36830. [4, 3], [4, 3], [4, 3], [4, 3],
  36831. [4, 3], [4, 3], [4, 3], [4, 3],
  36832. [4, 3], [4, 3], [4, 3], [4, 3],
  36833. [4, 3], [4, 3], [4, 3], [4, 3],
  36834. [4, 3], [4, 3], [4, 3], [4, 3],
  36835. [4, 3], [4, 3], [4, 3], [4, 3],
  36836. [5, 128], [5, 128], [5, 128], [5, 128], // 10010xxxx
  36837. [5, 128], [5, 128], [5, 128], [5, 128],
  36838. [5, 128], [5, 128], [5, 128], [5, 128],
  36839. [5, 128], [5, 128], [5, 128], [5, 128],
  36840. [5, 8], [5, 8], [5, 8], [5, 8], // 10011xxxx
  36841. [5, 8], [5, 8], [5, 8], [5, 8],
  36842. [5, 8], [5, 8], [5, 8], [5, 8],
  36843. [5, 8], [5, 8], [5, 8], [5, 8],
  36844. [5, 9], [5, 9], [5, 9], [5, 9], // 10100xxxx
  36845. [5, 9], [5, 9], [5, 9], [5, 9],
  36846. [5, 9], [5, 9], [5, 9], [5, 9],
  36847. [5, 9], [5, 9], [5, 9], [5, 9],
  36848. [6, 16], [6, 16], [6, 16], [6, 16], // 101010xxx
  36849. [6, 16], [6, 16], [6, 16], [6, 16],
  36850. [6, 17], [6, 17], [6, 17], [6, 17], // 101011xxx
  36851. [6, 17], [6, 17], [6, 17], [6, 17],
  36852. [4, 4], [4, 4], [4, 4], [4, 4], // 1011xxxxx
  36853. [4, 4], [4, 4], [4, 4], [4, 4],
  36854. [4, 4], [4, 4], [4, 4], [4, 4],
  36855. [4, 4], [4, 4], [4, 4], [4, 4],
  36856. [4, 4], [4, 4], [4, 4], [4, 4],
  36857. [4, 4], [4, 4], [4, 4], [4, 4],
  36858. [4, 4], [4, 4], [4, 4], [4, 4],
  36859. [4, 4], [4, 4], [4, 4], [4, 4],
  36860. [4, 5], [4, 5], [4, 5], [4, 5], // 1100xxxxx
  36861. [4, 5], [4, 5], [4, 5], [4, 5],
  36862. [4, 5], [4, 5], [4, 5], [4, 5],
  36863. [4, 5], [4, 5], [4, 5], [4, 5],
  36864. [4, 5], [4, 5], [4, 5], [4, 5],
  36865. [4, 5], [4, 5], [4, 5], [4, 5],
  36866. [4, 5], [4, 5], [4, 5], [4, 5],
  36867. [4, 5], [4, 5], [4, 5], [4, 5],
  36868. [6, 14], [6, 14], [6, 14], [6, 14], // 110100xxx
  36869. [6, 14], [6, 14], [6, 14], [6, 14],
  36870. [6, 15], [6, 15], [6, 15], [6, 15], // 110101xxx
  36871. [6, 15], [6, 15], [6, 15], [6, 15],
  36872. [5, 64], [5, 64], [5, 64], [5, 64], // 11011xxxx
  36873. [5, 64], [5, 64], [5, 64], [5, 64],
  36874. [5, 64], [5, 64], [5, 64], [5, 64],
  36875. [5, 64], [5, 64], [5, 64], [5, 64],
  36876. [4, 6], [4, 6], [4, 6], [4, 6], // 1110xxxxx
  36877. [4, 6], [4, 6], [4, 6], [4, 6],
  36878. [4, 6], [4, 6], [4, 6], [4, 6],
  36879. [4, 6], [4, 6], [4, 6], [4, 6],
  36880. [4, 6], [4, 6], [4, 6], [4, 6],
  36881. [4, 6], [4, 6], [4, 6], [4, 6],
  36882. [4, 6], [4, 6], [4, 6], [4, 6],
  36883. [4, 6], [4, 6], [4, 6], [4, 6],
  36884. [4, 7], [4, 7], [4, 7], [4, 7], // 1111xxxxx
  36885. [4, 7], [4, 7], [4, 7], [4, 7],
  36886. [4, 7], [4, 7], [4, 7], [4, 7],
  36887. [4, 7], [4, 7], [4, 7], [4, 7],
  36888. [4, 7], [4, 7], [4, 7], [4, 7],
  36889. [4, 7], [4, 7], [4, 7], [4, 7],
  36890. [4, 7], [4, 7], [4, 7], [4, 7],
  36891. [4, 7], [4, 7], [4, 7], [4, 7]
  36892. ];
  36893. var blackTable1 = [
  36894. [-1, -1], [-1, -1], // 000000000000x
  36895. [12, ccittEOL], [12, ccittEOL], // 000000000001x
  36896. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000001xx
  36897. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000010xx
  36898. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000011xx
  36899. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000100xx
  36900. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000101xx
  36901. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000110xx
  36902. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000111xx
  36903. [11, 1792], [11, 1792], [11, 1792], [11, 1792], // 00000001000xx
  36904. [12, 1984], [12, 1984], // 000000010010x
  36905. [12, 2048], [12, 2048], // 000000010011x
  36906. [12, 2112], [12, 2112], // 000000010100x
  36907. [12, 2176], [12, 2176], // 000000010101x
  36908. [12, 2240], [12, 2240], // 000000010110x
  36909. [12, 2304], [12, 2304], // 000000010111x
  36910. [11, 1856], [11, 1856], [11, 1856], [11, 1856], // 00000001100xx
  36911. [11, 1920], [11, 1920], [11, 1920], [11, 1920], // 00000001101xx
  36912. [12, 2368], [12, 2368], // 000000011100x
  36913. [12, 2432], [12, 2432], // 000000011101x
  36914. [12, 2496], [12, 2496], // 000000011110x
  36915. [12, 2560], [12, 2560], // 000000011111x
  36916. [10, 18], [10, 18], [10, 18], [10, 18], // 0000001000xxx
  36917. [10, 18], [10, 18], [10, 18], [10, 18],
  36918. [12, 52], [12, 52], // 000000100100x
  36919. [13, 640], // 0000001001010
  36920. [13, 704], // 0000001001011
  36921. [13, 768], // 0000001001100
  36922. [13, 832], // 0000001001101
  36923. [12, 55], [12, 55], // 000000100111x
  36924. [12, 56], [12, 56], // 000000101000x
  36925. [13, 1280], // 0000001010010
  36926. [13, 1344], // 0000001010011
  36927. [13, 1408], // 0000001010100
  36928. [13, 1472], // 0000001010101
  36929. [12, 59], [12, 59], // 000000101011x
  36930. [12, 60], [12, 60], // 000000101100x
  36931. [13, 1536], // 0000001011010
  36932. [13, 1600], // 0000001011011
  36933. [11, 24], [11, 24], [11, 24], [11, 24], // 00000010111xx
  36934. [11, 25], [11, 25], [11, 25], [11, 25], // 00000011000xx
  36935. [13, 1664], // 0000001100100
  36936. [13, 1728], // 0000001100101
  36937. [12, 320], [12, 320], // 000000110011x
  36938. [12, 384], [12, 384], // 000000110100x
  36939. [12, 448], [12, 448], // 000000110101x
  36940. [13, 512], // 0000001101100
  36941. [13, 576], // 0000001101101
  36942. [12, 53], [12, 53], // 000000110111x
  36943. [12, 54], [12, 54], // 000000111000x
  36944. [13, 896], // 0000001110010
  36945. [13, 960], // 0000001110011
  36946. [13, 1024], // 0000001110100
  36947. [13, 1088], // 0000001110101
  36948. [13, 1152], // 0000001110110
  36949. [13, 1216], // 0000001110111
  36950. [10, 64], [10, 64], [10, 64], [10, 64], // 0000001111xxx
  36951. [10, 64], [10, 64], [10, 64], [10, 64]
  36952. ];
  36953. var blackTable2 = [
  36954. [8, 13], [8, 13], [8, 13], [8, 13], // 00000100xxxx
  36955. [8, 13], [8, 13], [8, 13], [8, 13],
  36956. [8, 13], [8, 13], [8, 13], [8, 13],
  36957. [8, 13], [8, 13], [8, 13], [8, 13],
  36958. [11, 23], [11, 23], // 00000101000x
  36959. [12, 50], // 000001010010
  36960. [12, 51], // 000001010011
  36961. [12, 44], // 000001010100
  36962. [12, 45], // 000001010101
  36963. [12, 46], // 000001010110
  36964. [12, 47], // 000001010111
  36965. [12, 57], // 000001011000
  36966. [12, 58], // 000001011001
  36967. [12, 61], // 000001011010
  36968. [12, 256], // 000001011011
  36969. [10, 16], [10, 16], [10, 16], [10, 16], // 0000010111xx
  36970. [10, 17], [10, 17], [10, 17], [10, 17], // 0000011000xx
  36971. [12, 48], // 000001100100
  36972. [12, 49], // 000001100101
  36973. [12, 62], // 000001100110
  36974. [12, 63], // 000001100111
  36975. [12, 30], // 000001101000
  36976. [12, 31], // 000001101001
  36977. [12, 32], // 000001101010
  36978. [12, 33], // 000001101011
  36979. [12, 40], // 000001101100
  36980. [12, 41], // 000001101101
  36981. [11, 22], [11, 22], // 00000110111x
  36982. [8, 14], [8, 14], [8, 14], [8, 14], // 00000111xxxx
  36983. [8, 14], [8, 14], [8, 14], [8, 14],
  36984. [8, 14], [8, 14], [8, 14], [8, 14],
  36985. [8, 14], [8, 14], [8, 14], [8, 14],
  36986. [7, 10], [7, 10], [7, 10], [7, 10], // 0000100xxxxx
  36987. [7, 10], [7, 10], [7, 10], [7, 10],
  36988. [7, 10], [7, 10], [7, 10], [7, 10],
  36989. [7, 10], [7, 10], [7, 10], [7, 10],
  36990. [7, 10], [7, 10], [7, 10], [7, 10],
  36991. [7, 10], [7, 10], [7, 10], [7, 10],
  36992. [7, 10], [7, 10], [7, 10], [7, 10],
  36993. [7, 10], [7, 10], [7, 10], [7, 10],
  36994. [7, 11], [7, 11], [7, 11], [7, 11], // 0000101xxxxx
  36995. [7, 11], [7, 11], [7, 11], [7, 11],
  36996. [7, 11], [7, 11], [7, 11], [7, 11],
  36997. [7, 11], [7, 11], [7, 11], [7, 11],
  36998. [7, 11], [7, 11], [7, 11], [7, 11],
  36999. [7, 11], [7, 11], [7, 11], [7, 11],
  37000. [7, 11], [7, 11], [7, 11], [7, 11],
  37001. [7, 11], [7, 11], [7, 11], [7, 11],
  37002. [9, 15], [9, 15], [9, 15], [9, 15], // 000011000xxx
  37003. [9, 15], [9, 15], [9, 15], [9, 15],
  37004. [12, 128], // 000011001000
  37005. [12, 192], // 000011001001
  37006. [12, 26], // 000011001010
  37007. [12, 27], // 000011001011
  37008. [12, 28], // 000011001100
  37009. [12, 29], // 000011001101
  37010. [11, 19], [11, 19], // 00001100111x
  37011. [11, 20], [11, 20], // 00001101000x
  37012. [12, 34], // 000011010010
  37013. [12, 35], // 000011010011
  37014. [12, 36], // 000011010100
  37015. [12, 37], // 000011010101
  37016. [12, 38], // 000011010110
  37017. [12, 39], // 000011010111
  37018. [11, 21], [11, 21], // 00001101100x
  37019. [12, 42], // 000011011010
  37020. [12, 43], // 000011011011
  37021. [10, 0], [10, 0], [10, 0], [10, 0], // 0000110111xx
  37022. [7, 12], [7, 12], [7, 12], [7, 12], // 0000111xxxxx
  37023. [7, 12], [7, 12], [7, 12], [7, 12],
  37024. [7, 12], [7, 12], [7, 12], [7, 12],
  37025. [7, 12], [7, 12], [7, 12], [7, 12],
  37026. [7, 12], [7, 12], [7, 12], [7, 12],
  37027. [7, 12], [7, 12], [7, 12], [7, 12],
  37028. [7, 12], [7, 12], [7, 12], [7, 12],
  37029. [7, 12], [7, 12], [7, 12], [7, 12]
  37030. ];
  37031. var blackTable3 = [
  37032. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 0000xx
  37033. [6, 9], // 000100
  37034. [6, 8], // 000101
  37035. [5, 7], [5, 7], // 00011x
  37036. [4, 6], [4, 6], [4, 6], [4, 6], // 0010xx
  37037. [4, 5], [4, 5], [4, 5], [4, 5], // 0011xx
  37038. [3, 1], [3, 1], [3, 1], [3, 1], // 010xxx
  37039. [3, 1], [3, 1], [3, 1], [3, 1],
  37040. [3, 4], [3, 4], [3, 4], [3, 4], // 011xxx
  37041. [3, 4], [3, 4], [3, 4], [3, 4],
  37042. [2, 3], [2, 3], [2, 3], [2, 3], // 10xxxx
  37043. [2, 3], [2, 3], [2, 3], [2, 3],
  37044. [2, 3], [2, 3], [2, 3], [2, 3],
  37045. [2, 3], [2, 3], [2, 3], [2, 3],
  37046. [2, 2], [2, 2], [2, 2], [2, 2], // 11xxxx
  37047. [2, 2], [2, 2], [2, 2], [2, 2],
  37048. [2, 2], [2, 2], [2, 2], [2, 2],
  37049. [2, 2], [2, 2], [2, 2], [2, 2]
  37050. ];
  37051. function CCITTFaxStream(str, maybeLength, params) {
  37052. this.str = str;
  37053. this.dict = str.dict;
  37054. params = params || Dict.empty;
  37055. this.encoding = params.get('K') || 0;
  37056. this.eoline = params.get('EndOfLine') || false;
  37057. this.byteAlign = params.get('EncodedByteAlign') || false;
  37058. this.columns = params.get('Columns') || 1728;
  37059. this.rows = params.get('Rows') || 0;
  37060. var eoblock = params.get('EndOfBlock');
  37061. if (eoblock === null || eoblock === undefined) {
  37062. eoblock = true;
  37063. }
  37064. this.eoblock = eoblock;
  37065. this.black = params.get('BlackIs1') || false;
  37066. this.codingLine = new Uint32Array(this.columns + 1);
  37067. this.refLine = new Uint32Array(this.columns + 2);
  37068. this.codingLine[0] = this.columns;
  37069. this.codingPos = 0;
  37070. this.row = 0;
  37071. this.nextLine2D = this.encoding < 0;
  37072. this.inputBits = 0;
  37073. this.inputBuf = 0;
  37074. this.outputBits = 0;
  37075. var code1;
  37076. while ((code1 = this.lookBits(12)) === 0) {
  37077. this.eatBits(1);
  37078. }
  37079. if (code1 === 1) {
  37080. this.eatBits(12);
  37081. }
  37082. if (this.encoding > 0) {
  37083. this.nextLine2D = !this.lookBits(1);
  37084. this.eatBits(1);
  37085. }
  37086. DecodeStream.call(this, maybeLength);
  37087. }
  37088. CCITTFaxStream.prototype = Object.create(DecodeStream.prototype);
  37089. CCITTFaxStream.prototype.readBlock = function CCITTFaxStream_readBlock() {
  37090. while (!this.eof) {
  37091. var c = this.lookChar();
  37092. this.ensureBuffer(this.bufferLength + 1);
  37093. this.buffer[this.bufferLength++] = c;
  37094. }
  37095. };
  37096. CCITTFaxStream.prototype.addPixels =
  37097. function ccittFaxStreamAddPixels(a1, blackPixels) {
  37098. var codingLine = this.codingLine;
  37099. var codingPos = this.codingPos;
  37100. if (a1 > codingLine[codingPos]) {
  37101. if (a1 > this.columns) {
  37102. info('row is wrong length');
  37103. this.err = true;
  37104. a1 = this.columns;
  37105. }
  37106. if ((codingPos & 1) ^ blackPixels) {
  37107. ++codingPos;
  37108. }
  37109. codingLine[codingPos] = a1;
  37110. }
  37111. this.codingPos = codingPos;
  37112. };
  37113. CCITTFaxStream.prototype.addPixelsNeg =
  37114. function ccittFaxStreamAddPixelsNeg(a1, blackPixels) {
  37115. var codingLine = this.codingLine;
  37116. var codingPos = this.codingPos;
  37117. if (a1 > codingLine[codingPos]) {
  37118. if (a1 > this.columns) {
  37119. info('row is wrong length');
  37120. this.err = true;
  37121. a1 = this.columns;
  37122. }
  37123. if ((codingPos & 1) ^ blackPixels) {
  37124. ++codingPos;
  37125. }
  37126. codingLine[codingPos] = a1;
  37127. } else if (a1 < codingLine[codingPos]) {
  37128. if (a1 < 0) {
  37129. info('invalid code');
  37130. this.err = true;
  37131. a1 = 0;
  37132. }
  37133. while (codingPos > 0 && a1 < codingLine[codingPos - 1]) {
  37134. --codingPos;
  37135. }
  37136. codingLine[codingPos] = a1;
  37137. }
  37138. this.codingPos = codingPos;
  37139. };
  37140. CCITTFaxStream.prototype.lookChar = function CCITTFaxStream_lookChar() {
  37141. var refLine = this.refLine;
  37142. var codingLine = this.codingLine;
  37143. var columns = this.columns;
  37144. var refPos, blackPixels, bits, i;
  37145. if (this.outputBits === 0) {
  37146. if (this.eof) {
  37147. return null;
  37148. }
  37149. this.err = false;
  37150. var code1, code2, code3;
  37151. if (this.nextLine2D) {
  37152. for (i = 0; codingLine[i] < columns; ++i) {
  37153. refLine[i] = codingLine[i];
  37154. }
  37155. refLine[i++] = columns;
  37156. refLine[i] = columns;
  37157. codingLine[0] = 0;
  37158. this.codingPos = 0;
  37159. refPos = 0;
  37160. blackPixels = 0;
  37161. while (codingLine[this.codingPos] < columns) {
  37162. code1 = this.getTwoDimCode();
  37163. switch (code1) {
  37164. case twoDimPass:
  37165. this.addPixels(refLine[refPos + 1], blackPixels);
  37166. if (refLine[refPos + 1] < columns) {
  37167. refPos += 2;
  37168. }
  37169. break;
  37170. case twoDimHoriz:
  37171. code1 = code2 = 0;
  37172. if (blackPixels) {
  37173. do {
  37174. code1 += (code3 = this.getBlackCode());
  37175. } while (code3 >= 64);
  37176. do {
  37177. code2 += (code3 = this.getWhiteCode());
  37178. } while (code3 >= 64);
  37179. } else {
  37180. do {
  37181. code1 += (code3 = this.getWhiteCode());
  37182. } while (code3 >= 64);
  37183. do {
  37184. code2 += (code3 = this.getBlackCode());
  37185. } while (code3 >= 64);
  37186. }
  37187. this.addPixels(codingLine[this.codingPos] +
  37188. code1, blackPixels);
  37189. if (codingLine[this.codingPos] < columns) {
  37190. this.addPixels(codingLine[this.codingPos] + code2,
  37191. blackPixels ^ 1);
  37192. }
  37193. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37194. refLine[refPos] < columns) {
  37195. refPos += 2;
  37196. }
  37197. break;
  37198. case twoDimVertR3:
  37199. this.addPixels(refLine[refPos] + 3, blackPixels);
  37200. blackPixels ^= 1;
  37201. if (codingLine[this.codingPos] < columns) {
  37202. ++refPos;
  37203. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37204. refLine[refPos] < columns) {
  37205. refPos += 2;
  37206. }
  37207. }
  37208. break;
  37209. case twoDimVertR2:
  37210. this.addPixels(refLine[refPos] + 2, blackPixels);
  37211. blackPixels ^= 1;
  37212. if (codingLine[this.codingPos] < columns) {
  37213. ++refPos;
  37214. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37215. refLine[refPos] < columns) {
  37216. refPos += 2;
  37217. }
  37218. }
  37219. break;
  37220. case twoDimVertR1:
  37221. this.addPixels(refLine[refPos] + 1, blackPixels);
  37222. blackPixels ^= 1;
  37223. if (codingLine[this.codingPos] < columns) {
  37224. ++refPos;
  37225. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37226. refLine[refPos] < columns) {
  37227. refPos += 2;
  37228. }
  37229. }
  37230. break;
  37231. case twoDimVert0:
  37232. this.addPixels(refLine[refPos], blackPixels);
  37233. blackPixels ^= 1;
  37234. if (codingLine[this.codingPos] < columns) {
  37235. ++refPos;
  37236. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37237. refLine[refPos] < columns) {
  37238. refPos += 2;
  37239. }
  37240. }
  37241. break;
  37242. case twoDimVertL3:
  37243. this.addPixelsNeg(refLine[refPos] - 3, blackPixels);
  37244. blackPixels ^= 1;
  37245. if (codingLine[this.codingPos] < columns) {
  37246. if (refPos > 0) {
  37247. --refPos;
  37248. } else {
  37249. ++refPos;
  37250. }
  37251. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37252. refLine[refPos] < columns) {
  37253. refPos += 2;
  37254. }
  37255. }
  37256. break;
  37257. case twoDimVertL2:
  37258. this.addPixelsNeg(refLine[refPos] - 2, blackPixels);
  37259. blackPixels ^= 1;
  37260. if (codingLine[this.codingPos] < columns) {
  37261. if (refPos > 0) {
  37262. --refPos;
  37263. } else {
  37264. ++refPos;
  37265. }
  37266. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37267. refLine[refPos] < columns) {
  37268. refPos += 2;
  37269. }
  37270. }
  37271. break;
  37272. case twoDimVertL1:
  37273. this.addPixelsNeg(refLine[refPos] - 1, blackPixels);
  37274. blackPixels ^= 1;
  37275. if (codingLine[this.codingPos] < columns) {
  37276. if (refPos > 0) {
  37277. --refPos;
  37278. } else {
  37279. ++refPos;
  37280. }
  37281. while (refLine[refPos] <= codingLine[this.codingPos] &&
  37282. refLine[refPos] < columns) {
  37283. refPos += 2;
  37284. }
  37285. }
  37286. break;
  37287. case EOF:
  37288. this.addPixels(columns, 0);
  37289. this.eof = true;
  37290. break;
  37291. default:
  37292. info('bad 2d code');
  37293. this.addPixels(columns, 0);
  37294. this.err = true;
  37295. }
  37296. }
  37297. } else {
  37298. codingLine[0] = 0;
  37299. this.codingPos = 0;
  37300. blackPixels = 0;
  37301. while (codingLine[this.codingPos] < columns) {
  37302. code1 = 0;
  37303. if (blackPixels) {
  37304. do {
  37305. code1 += (code3 = this.getBlackCode());
  37306. } while (code3 >= 64);
  37307. } else {
  37308. do {
  37309. code1 += (code3 = this.getWhiteCode());
  37310. } while (code3 >= 64);
  37311. }
  37312. this.addPixels(codingLine[this.codingPos] + code1, blackPixels);
  37313. blackPixels ^= 1;
  37314. }
  37315. }
  37316. var gotEOL = false;
  37317. if (this.byteAlign) {
  37318. this.inputBits &= ~7;
  37319. }
  37320. if (!this.eoblock && this.row === this.rows - 1) {
  37321. this.eof = true;
  37322. } else {
  37323. code1 = this.lookBits(12);
  37324. if (this.eoline) {
  37325. while (code1 !== EOF && code1 !== 1) {
  37326. this.eatBits(1);
  37327. code1 = this.lookBits(12);
  37328. }
  37329. } else {
  37330. while (code1 === 0) {
  37331. this.eatBits(1);
  37332. code1 = this.lookBits(12);
  37333. }
  37334. }
  37335. if (code1 === 1) {
  37336. this.eatBits(12);
  37337. gotEOL = true;
  37338. } else if (code1 === EOF) {
  37339. this.eof = true;
  37340. }
  37341. }
  37342. if (!this.eof && this.encoding > 0) {
  37343. this.nextLine2D = !this.lookBits(1);
  37344. this.eatBits(1);
  37345. }
  37346. if (this.eoblock && gotEOL && this.byteAlign) {
  37347. code1 = this.lookBits(12);
  37348. if (code1 === 1) {
  37349. this.eatBits(12);
  37350. if (this.encoding > 0) {
  37351. this.lookBits(1);
  37352. this.eatBits(1);
  37353. }
  37354. if (this.encoding >= 0) {
  37355. for (i = 0; i < 4; ++i) {
  37356. code1 = this.lookBits(12);
  37357. if (code1 !== 1) {
  37358. info('bad rtc code: ' + code1);
  37359. }
  37360. this.eatBits(12);
  37361. if (this.encoding > 0) {
  37362. this.lookBits(1);
  37363. this.eatBits(1);
  37364. }
  37365. }
  37366. }
  37367. this.eof = true;
  37368. }
  37369. } else if (this.err && this.eoline) {
  37370. while (true) {
  37371. code1 = this.lookBits(13);
  37372. if (code1 === EOF) {
  37373. this.eof = true;
  37374. return null;
  37375. }
  37376. if ((code1 >> 1) === 1) {
  37377. break;
  37378. }
  37379. this.eatBits(1);
  37380. }
  37381. this.eatBits(12);
  37382. if (this.encoding > 0) {
  37383. this.eatBits(1);
  37384. this.nextLine2D = !(code1 & 1);
  37385. }
  37386. }
  37387. if (codingLine[0] > 0) {
  37388. this.outputBits = codingLine[this.codingPos = 0];
  37389. } else {
  37390. this.outputBits = codingLine[this.codingPos = 1];
  37391. }
  37392. this.row++;
  37393. }
  37394. var c;
  37395. if (this.outputBits >= 8) {
  37396. c = (this.codingPos & 1) ? 0 : 0xFF;
  37397. this.outputBits -= 8;
  37398. if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {
  37399. this.codingPos++;
  37400. this.outputBits = (codingLine[this.codingPos] -
  37401. codingLine[this.codingPos - 1]);
  37402. }
  37403. } else {
  37404. bits = 8;
  37405. c = 0;
  37406. do {
  37407. if (this.outputBits > bits) {
  37408. c <<= bits;
  37409. if (!(this.codingPos & 1)) {
  37410. c |= 0xFF >> (8 - bits);
  37411. }
  37412. this.outputBits -= bits;
  37413. bits = 0;
  37414. } else {
  37415. c <<= this.outputBits;
  37416. if (!(this.codingPos & 1)) {
  37417. c |= 0xFF >> (8 - this.outputBits);
  37418. }
  37419. bits -= this.outputBits;
  37420. this.outputBits = 0;
  37421. if (codingLine[this.codingPos] < columns) {
  37422. this.codingPos++;
  37423. this.outputBits = (codingLine[this.codingPos] -
  37424. codingLine[this.codingPos - 1]);
  37425. } else if (bits > 0) {
  37426. c <<= bits;
  37427. bits = 0;
  37428. }
  37429. }
  37430. } while (bits);
  37431. }
  37432. if (this.black) {
  37433. c ^= 0xFF;
  37434. }
  37435. return c;
  37436. };
  37437. // This functions returns the code found from the table.
  37438. // The start and end parameters set the boundaries for searching the table.
  37439. // The limit parameter is optional. Function returns an array with three
  37440. // values. The first array element indicates whether a valid code is being
  37441. // returned. The second array element is the actual code. The third array
  37442. // element indicates whether EOF was reached.
  37443. CCITTFaxStream.prototype.findTableCode =
  37444. function ccittFaxStreamFindTableCode(start, end, table, limit) {
  37445. var limitValue = limit || 0;
  37446. for (var i = start; i <= end; ++i) {
  37447. var code = this.lookBits(i);
  37448. if (code === EOF) {
  37449. return [true, 1, false];
  37450. }
  37451. if (i < end) {
  37452. code <<= end - i;
  37453. }
  37454. if (!limitValue || code >= limitValue) {
  37455. var p = table[code - limitValue];
  37456. if (p[0] === i) {
  37457. this.eatBits(i);
  37458. return [true, p[1], true];
  37459. }
  37460. }
  37461. }
  37462. return [false, 0, false];
  37463. };
  37464. CCITTFaxStream.prototype.getTwoDimCode =
  37465. function ccittFaxStreamGetTwoDimCode() {
  37466. var code = 0;
  37467. var p;
  37468. if (this.eoblock) {
  37469. code = this.lookBits(7);
  37470. p = twoDimTable[code];
  37471. if (p && p[0] > 0) {
  37472. this.eatBits(p[0]);
  37473. return p[1];
  37474. }
  37475. } else {
  37476. var result = this.findTableCode(1, 7, twoDimTable);
  37477. if (result[0] && result[2]) {
  37478. return result[1];
  37479. }
  37480. }
  37481. info('Bad two dim code');
  37482. return EOF;
  37483. };
  37484. CCITTFaxStream.prototype.getWhiteCode =
  37485. function ccittFaxStreamGetWhiteCode() {
  37486. var code = 0;
  37487. var p;
  37488. if (this.eoblock) {
  37489. code = this.lookBits(12);
  37490. if (code === EOF) {
  37491. return 1;
  37492. }
  37493. if ((code >> 5) === 0) {
  37494. p = whiteTable1[code];
  37495. } else {
  37496. p = whiteTable2[code >> 3];
  37497. }
  37498. if (p[0] > 0) {
  37499. this.eatBits(p[0]);
  37500. return p[1];
  37501. }
  37502. } else {
  37503. var result = this.findTableCode(1, 9, whiteTable2);
  37504. if (result[0]) {
  37505. return result[1];
  37506. }
  37507. result = this.findTableCode(11, 12, whiteTable1);
  37508. if (result[0]) {
  37509. return result[1];
  37510. }
  37511. }
  37512. info('bad white code');
  37513. this.eatBits(1);
  37514. return 1;
  37515. };
  37516. CCITTFaxStream.prototype.getBlackCode =
  37517. function ccittFaxStreamGetBlackCode() {
  37518. var code, p;
  37519. if (this.eoblock) {
  37520. code = this.lookBits(13);
  37521. if (code === EOF) {
  37522. return 1;
  37523. }
  37524. if ((code >> 7) === 0) {
  37525. p = blackTable1[code];
  37526. } else if ((code >> 9) === 0 && (code >> 7) !== 0) {
  37527. p = blackTable2[(code >> 1) - 64];
  37528. } else {
  37529. p = blackTable3[code >> 7];
  37530. }
  37531. if (p[0] > 0) {
  37532. this.eatBits(p[0]);
  37533. return p[1];
  37534. }
  37535. } else {
  37536. var result = this.findTableCode(2, 6, blackTable3);
  37537. if (result[0]) {
  37538. return result[1];
  37539. }
  37540. result = this.findTableCode(7, 12, blackTable2, 64);
  37541. if (result[0]) {
  37542. return result[1];
  37543. }
  37544. result = this.findTableCode(10, 13, blackTable1);
  37545. if (result[0]) {
  37546. return result[1];
  37547. }
  37548. }
  37549. info('bad black code');
  37550. this.eatBits(1);
  37551. return 1;
  37552. };
  37553. CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) {
  37554. var c;
  37555. while (this.inputBits < n) {
  37556. if ((c = this.str.getByte()) === -1) {
  37557. if (this.inputBits === 0) {
  37558. return EOF;
  37559. }
  37560. return ((this.inputBuf << (n - this.inputBits)) &
  37561. (0xFFFF >> (16 - n)));
  37562. }
  37563. this.inputBuf = (this.inputBuf << 8) + c;
  37564. this.inputBits += 8;
  37565. }
  37566. return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n));
  37567. };
  37568. CCITTFaxStream.prototype.eatBits = function CCITTFaxStream_eatBits(n) {
  37569. if ((this.inputBits -= n) < 0) {
  37570. this.inputBits = 0;
  37571. }
  37572. };
  37573. return CCITTFaxStream;
  37574. })();
  37575. var LZWStream = (function LZWStreamClosure() {
  37576. function LZWStream(str, maybeLength, earlyChange) {
  37577. this.str = str;
  37578. this.dict = str.dict;
  37579. this.cachedData = 0;
  37580. this.bitsCached = 0;
  37581. var maxLzwDictionarySize = 4096;
  37582. var lzwState = {
  37583. earlyChange: earlyChange,
  37584. codeLength: 9,
  37585. nextCode: 258,
  37586. dictionaryValues: new Uint8Array(maxLzwDictionarySize),
  37587. dictionaryLengths: new Uint16Array(maxLzwDictionarySize),
  37588. dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize),
  37589. currentSequence: new Uint8Array(maxLzwDictionarySize),
  37590. currentSequenceLength: 0
  37591. };
  37592. for (var i = 0; i < 256; ++i) {
  37593. lzwState.dictionaryValues[i] = i;
  37594. lzwState.dictionaryLengths[i] = 1;
  37595. }
  37596. this.lzwState = lzwState;
  37597. DecodeStream.call(this, maybeLength);
  37598. }
  37599. LZWStream.prototype = Object.create(DecodeStream.prototype);
  37600. LZWStream.prototype.readBits = function LZWStream_readBits(n) {
  37601. var bitsCached = this.bitsCached;
  37602. var cachedData = this.cachedData;
  37603. while (bitsCached < n) {
  37604. var c = this.str.getByte();
  37605. if (c === -1) {
  37606. this.eof = true;
  37607. return null;
  37608. }
  37609. cachedData = (cachedData << 8) | c;
  37610. bitsCached += 8;
  37611. }
  37612. this.bitsCached = (bitsCached -= n);
  37613. this.cachedData = cachedData;
  37614. this.lastCode = null;
  37615. return (cachedData >>> bitsCached) & ((1 << n) - 1);
  37616. };
  37617. LZWStream.prototype.readBlock = function LZWStream_readBlock() {
  37618. var blockSize = 512;
  37619. var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize;
  37620. var i, j, q;
  37621. var lzwState = this.lzwState;
  37622. if (!lzwState) {
  37623. return; // eof was found
  37624. }
  37625. var earlyChange = lzwState.earlyChange;
  37626. var nextCode = lzwState.nextCode;
  37627. var dictionaryValues = lzwState.dictionaryValues;
  37628. var dictionaryLengths = lzwState.dictionaryLengths;
  37629. var dictionaryPrevCodes = lzwState.dictionaryPrevCodes;
  37630. var codeLength = lzwState.codeLength;
  37631. var prevCode = lzwState.prevCode;
  37632. var currentSequence = lzwState.currentSequence;
  37633. var currentSequenceLength = lzwState.currentSequenceLength;
  37634. var decodedLength = 0;
  37635. var currentBufferLength = this.bufferLength;
  37636. var buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
  37637. for (i = 0; i < blockSize; i++) {
  37638. var code = this.readBits(codeLength);
  37639. var hasPrev = currentSequenceLength > 0;
  37640. if (code < 256) {
  37641. currentSequence[0] = code;
  37642. currentSequenceLength = 1;
  37643. } else if (code >= 258) {
  37644. if (code < nextCode) {
  37645. currentSequenceLength = dictionaryLengths[code];
  37646. for (j = currentSequenceLength - 1, q = code; j >= 0; j--) {
  37647. currentSequence[j] = dictionaryValues[q];
  37648. q = dictionaryPrevCodes[q];
  37649. }
  37650. } else {
  37651. currentSequence[currentSequenceLength++] = currentSequence[0];
  37652. }
  37653. } else if (code === 256) {
  37654. codeLength = 9;
  37655. nextCode = 258;
  37656. currentSequenceLength = 0;
  37657. continue;
  37658. } else {
  37659. this.eof = true;
  37660. delete this.lzwState;
  37661. break;
  37662. }
  37663. if (hasPrev) {
  37664. dictionaryPrevCodes[nextCode] = prevCode;
  37665. dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1;
  37666. dictionaryValues[nextCode] = currentSequence[0];
  37667. nextCode++;
  37668. codeLength = (nextCode + earlyChange) & (nextCode + earlyChange - 1) ?
  37669. codeLength : Math.min(Math.log(nextCode + earlyChange) /
  37670. 0.6931471805599453 + 1, 12) | 0;
  37671. }
  37672. prevCode = code;
  37673. decodedLength += currentSequenceLength;
  37674. if (estimatedDecodedSize < decodedLength) {
  37675. do {
  37676. estimatedDecodedSize += decodedSizeDelta;
  37677. } while (estimatedDecodedSize < decodedLength);
  37678. buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
  37679. }
  37680. for (j = 0; j < currentSequenceLength; j++) {
  37681. buffer[currentBufferLength++] = currentSequence[j];
  37682. }
  37683. }
  37684. lzwState.nextCode = nextCode;
  37685. lzwState.codeLength = codeLength;
  37686. lzwState.prevCode = prevCode;
  37687. lzwState.currentSequenceLength = currentSequenceLength;
  37688. this.bufferLength = currentBufferLength;
  37689. };
  37690. return LZWStream;
  37691. })();
  37692. var NullStream = (function NullStreamClosure() {
  37693. function NullStream() {
  37694. Stream.call(this, new Uint8Array(0));
  37695. }
  37696. NullStream.prototype = Stream.prototype;
  37697. return NullStream;
  37698. })();
  37699. var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
  37700. setup: function wphSetup(handler) {
  37701. var pdfManager;
  37702. function loadDocument(recoveryMode) {
  37703. var loadDocumentCapability = createPromiseCapability();
  37704. var parseSuccess = function parseSuccess() {
  37705. var numPagesPromise = pdfManager.ensureDoc('numPages');
  37706. var fingerprintPromise = pdfManager.ensureDoc('fingerprint');
  37707. var encryptedPromise = pdfManager.ensureXRef('encrypt');
  37708. Promise.all([numPagesPromise, fingerprintPromise,
  37709. encryptedPromise]).then(function onDocReady(results) {
  37710. var doc = {
  37711. numPages: results[0],
  37712. fingerprint: results[1],
  37713. encrypted: !!results[2],
  37714. };
  37715. loadDocumentCapability.resolve(doc);
  37716. },
  37717. parseFailure);
  37718. };
  37719. var parseFailure = function parseFailure(e) {
  37720. loadDocumentCapability.reject(e);
  37721. };
  37722. pdfManager.ensureDoc('checkHeader', []).then(function() {
  37723. pdfManager.ensureDoc('parseStartXRef', []).then(function() {
  37724. pdfManager.ensureDoc('parse', [recoveryMode]).then(
  37725. parseSuccess, parseFailure);
  37726. }, parseFailure);
  37727. }, parseFailure);
  37728. return loadDocumentCapability.promise;
  37729. }
  37730. function getPdfManager(data) {
  37731. var pdfManagerCapability = createPromiseCapability();
  37732. var source = data.source;
  37733. var disableRange = data.disableRange;
  37734. if (source.data) {
  37735. try {
  37736. pdfManager = new LocalPdfManager(source.data, source.password);
  37737. pdfManagerCapability.resolve();
  37738. } catch (ex) {
  37739. pdfManagerCapability.reject(ex);
  37740. }
  37741. return pdfManagerCapability.promise;
  37742. } else if (source.chunkedViewerLoading) {
  37743. try {
  37744. pdfManager = new NetworkPdfManager(source, handler);
  37745. pdfManagerCapability.resolve();
  37746. } catch (ex) {
  37747. pdfManagerCapability.reject(ex);
  37748. }
  37749. return pdfManagerCapability.promise;
  37750. }
  37751. var networkManager = new NetworkManager(source.url, {
  37752. httpHeaders: source.httpHeaders,
  37753. withCredentials: source.withCredentials
  37754. });
  37755. var cachedChunks = [];
  37756. var fullRequestXhrId = networkManager.requestFull({
  37757. onHeadersReceived: function onHeadersReceived() {
  37758. if (disableRange) {
  37759. return;
  37760. }
  37761. var fullRequestXhr = networkManager.getRequestXhr(fullRequestXhrId);
  37762. if (fullRequestXhr.getResponseHeader('Accept-Ranges') !== 'bytes') {
  37763. return;
  37764. }
  37765. var contentEncoding =
  37766. fullRequestXhr.getResponseHeader('Content-Encoding') || 'identity';
  37767. if (contentEncoding !== 'identity') {
  37768. return;
  37769. }
  37770. var length = fullRequestXhr.getResponseHeader('Content-Length');
  37771. length = parseInt(length, 10);
  37772. if (!isInt(length)) {
  37773. return;
  37774. }
  37775. source.length = length;
  37776. if (length <= 2 * RANGE_CHUNK_SIZE) {
  37777. // The file size is smaller than the size of two chunks, so it does
  37778. // not make any sense to abort the request and retry with a range
  37779. // request.
  37780. return;
  37781. }
  37782. if (networkManager.isStreamingRequest(fullRequestXhrId)) {
  37783. // We can continue fetching when progressive loading is enabled,
  37784. // and we don't need the autoFetch feature.
  37785. source.disableAutoFetch = true;
  37786. } else {
  37787. // NOTE: by cancelling the full request, and then issuing range
  37788. // requests, there will be an issue for sites where you can only
  37789. // request the pdf once. However, if this is the case, then the
  37790. // server should not be returning that it can support range
  37791. // requests.
  37792. networkManager.abortRequest(fullRequestXhrId);
  37793. }
  37794. try {
  37795. pdfManager = new NetworkPdfManager(source, handler);
  37796. pdfManagerCapability.resolve(pdfManager);
  37797. } catch (ex) {
  37798. pdfManagerCapability.reject(ex);
  37799. }
  37800. },
  37801. onProgressiveData: source.disableStream ? null :
  37802. function onProgressiveData(chunk) {
  37803. if (!pdfManager) {
  37804. cachedChunks.push(chunk);
  37805. return;
  37806. }
  37807. pdfManager.sendProgressiveData(chunk);
  37808. },
  37809. onDone: function onDone(args) {
  37810. if (pdfManager) {
  37811. return; // already processed
  37812. }
  37813. var pdfFile;
  37814. if (args === null) {
  37815. // TODO add some streaming manager, e.g. for unknown length files.
  37816. // The data was returned in the onProgressiveData, combining...
  37817. var pdfFileLength = 0, pos = 0;
  37818. cachedChunks.forEach(function (chunk) {
  37819. pdfFileLength += chunk.byteLength;
  37820. });
  37821. if (source.length && pdfFileLength !== source.length) {
  37822. warn('reported HTTP length is different from actual');
  37823. }
  37824. var pdfFileArray = new Uint8Array(pdfFileLength);
  37825. cachedChunks.forEach(function (chunk) {
  37826. pdfFileArray.set(new Uint8Array(chunk), pos);
  37827. pos += chunk.byteLength;
  37828. });
  37829. pdfFile = pdfFileArray.buffer;
  37830. } else {
  37831. pdfFile = args.chunk;
  37832. }
  37833. // the data is array, instantiating directly from it
  37834. try {
  37835. pdfManager = new LocalPdfManager(pdfFile, source.password);
  37836. pdfManagerCapability.resolve();
  37837. } catch (ex) {
  37838. pdfManagerCapability.reject(ex);
  37839. }
  37840. },
  37841. onError: function onError(status) {
  37842. var exception;
  37843. if (status === 404) {
  37844. exception = new MissingPDFException('Missing PDF "' +
  37845. source.url + '".');
  37846. handler.send('MissingPDF', exception);
  37847. } else {
  37848. exception = new UnexpectedResponseException(
  37849. 'Unexpected server response (' + status +
  37850. ') while retrieving PDF "' + source.url + '".', status);
  37851. handler.send('UnexpectedResponse', exception);
  37852. }
  37853. },
  37854. onProgress: function onProgress(evt) {
  37855. handler.send('DocProgress', {
  37856. loaded: evt.loaded,
  37857. total: evt.lengthComputable ? evt.total : source.length
  37858. });
  37859. }
  37860. });
  37861. return pdfManagerCapability.promise;
  37862. }
  37863. handler.on('test', function wphSetupTest(data) {
  37864. // check if Uint8Array can be sent to worker
  37865. if (!(data instanceof Uint8Array)) {
  37866. handler.send('test', false);
  37867. return;
  37868. }
  37869. // making sure postMessage transfers are working
  37870. var supportTransfers = data[0] === 255;
  37871. handler.postMessageTransfers = supportTransfers;
  37872. // check if the response property is supported by xhr
  37873. var xhr = new XMLHttpRequest();
  37874. var responseExists = 'response' in xhr;
  37875. // check if the property is actually implemented
  37876. try {
  37877. var dummy = xhr.responseType;
  37878. } catch (e) {
  37879. responseExists = false;
  37880. }
  37881. if (!responseExists) {
  37882. handler.send('test', false);
  37883. return;
  37884. }
  37885. handler.send('test', {
  37886. supportTypedArray: true,
  37887. supportTransfers: supportTransfers
  37888. });
  37889. });
  37890. handler.on('GetDocRequest', function wphSetupDoc(data) {
  37891. var onSuccess = function(doc) {
  37892. handler.send('GetDoc', { pdfInfo: doc });
  37893. };
  37894. var onFailure = function(e) {
  37895. if (e instanceof PasswordException) {
  37896. if (e.code === PasswordResponses.NEED_PASSWORD) {
  37897. handler.send('NeedPassword', e);
  37898. } else if (e.code === PasswordResponses.INCORRECT_PASSWORD) {
  37899. handler.send('IncorrectPassword', e);
  37900. }
  37901. } else if (e instanceof InvalidPDFException) {
  37902. handler.send('InvalidPDF', e);
  37903. } else if (e instanceof MissingPDFException) {
  37904. handler.send('MissingPDF', e);
  37905. } else if (e instanceof UnexpectedResponseException) {
  37906. handler.send('UnexpectedResponse', e);
  37907. } else {
  37908. handler.send('UnknownError',
  37909. new UnknownErrorException(e.message, e.toString()));
  37910. }
  37911. };
  37912. PDFJS.maxImageSize = data.maxImageSize === undefined ?
  37913. -1 : data.maxImageSize;
  37914. PDFJS.disableFontFace = data.disableFontFace;
  37915. PDFJS.disableCreateObjectURL = data.disableCreateObjectURL;
  37916. PDFJS.verbosity = data.verbosity;
  37917. PDFJS.cMapUrl = data.cMapUrl === undefined ?
  37918. null : data.cMapUrl;
  37919. PDFJS.cMapPacked = data.cMapPacked === true;
  37920. getPdfManager(data).then(function () {
  37921. handler.send('PDFManagerReady', null);
  37922. pdfManager.onLoadedStream().then(function(stream) {
  37923. handler.send('DataLoaded', { length: stream.bytes.byteLength });
  37924. });
  37925. }).then(function pdfManagerReady() {
  37926. loadDocument(false).then(onSuccess, function loadFailure(ex) {
  37927. // Try again with recoveryMode == true
  37928. if (!(ex instanceof XRefParseException)) {
  37929. if (ex instanceof PasswordException) {
  37930. // after password exception prepare to receive a new password
  37931. // to repeat loading
  37932. pdfManager.passwordChanged().then(pdfManagerReady);
  37933. }
  37934. onFailure(ex);
  37935. return;
  37936. }
  37937. pdfManager.requestLoadedStream();
  37938. pdfManager.onLoadedStream().then(function() {
  37939. loadDocument(true).then(onSuccess, onFailure);
  37940. });
  37941. }, onFailure);
  37942. }, onFailure);
  37943. });
  37944. handler.on('GetPage', function wphSetupGetPage(data) {
  37945. return pdfManager.getPage(data.pageIndex).then(function(page) {
  37946. var rotatePromise = pdfManager.ensure(page, 'rotate');
  37947. var refPromise = pdfManager.ensure(page, 'ref');
  37948. var viewPromise = pdfManager.ensure(page, 'view');
  37949. return Promise.all([rotatePromise, refPromise, viewPromise]).then(
  37950. function(results) {
  37951. return {
  37952. rotate: results[0],
  37953. ref: results[1],
  37954. view: results[2]
  37955. };
  37956. });
  37957. });
  37958. });
  37959. handler.on('GetPageIndex', function wphSetupGetPageIndex(data) {
  37960. var ref = new Ref(data.ref.num, data.ref.gen);
  37961. var catalog = pdfManager.pdfDocument.catalog;
  37962. return catalog.getPageIndex(ref);
  37963. });
  37964. handler.on('GetDestinations',
  37965. function wphSetupGetDestinations(data) {
  37966. return pdfManager.ensureCatalog('destinations');
  37967. }
  37968. );
  37969. handler.on('GetDestination',
  37970. function wphSetupGetDestination(data) {
  37971. return pdfManager.ensureCatalog('getDestination', [ data.id ]);
  37972. }
  37973. );
  37974. handler.on('GetAttachments',
  37975. function wphSetupGetAttachments(data) {
  37976. return pdfManager.ensureCatalog('attachments');
  37977. }
  37978. );
  37979. handler.on('GetJavaScript',
  37980. function wphSetupGetJavaScript(data) {
  37981. return pdfManager.ensureCatalog('javaScript');
  37982. }
  37983. );
  37984. handler.on('GetOutline',
  37985. function wphSetupGetOutline(data) {
  37986. return pdfManager.ensureCatalog('documentOutline');
  37987. }
  37988. );
  37989. handler.on('GetMetadata',
  37990. function wphSetupGetMetadata(data) {
  37991. return Promise.all([pdfManager.ensureDoc('documentInfo'),
  37992. pdfManager.ensureCatalog('metadata')]);
  37993. }
  37994. );
  37995. handler.on('GetData', function wphSetupGetData(data) {
  37996. pdfManager.requestLoadedStream();
  37997. return pdfManager.onLoadedStream().then(function(stream) {
  37998. return stream.bytes;
  37999. });
  38000. });
  38001. handler.on('GetStats',
  38002. function wphSetupGetStats(data) {
  38003. return pdfManager.pdfDocument.xref.stats;
  38004. }
  38005. );
  38006. handler.on('UpdatePassword', function wphSetupUpdatePassword(data) {
  38007. pdfManager.updatePassword(data);
  38008. });
  38009. handler.on('GetAnnotations', function wphSetupGetAnnotations(data) {
  38010. return pdfManager.getPage(data.pageIndex).then(function(page) {
  38011. return pdfManager.ensure(page, 'getAnnotationsData', []);
  38012. });
  38013. });
  38014. handler.on('RenderPageRequest', function wphSetupRenderPage(data) {
  38015. pdfManager.getPage(data.pageIndex).then(function(page) {
  38016. var pageNum = data.pageIndex + 1;
  38017. var start = Date.now();
  38018. // Pre compile the pdf page and fetch the fonts/images.
  38019. page.getOperatorList(handler, data.intent).then(function(operatorList) {
  38020. info('page=' + pageNum + ' - getOperatorList: time=' +
  38021. (Date.now() - start) + 'ms, len=' + operatorList.fnArray.length);
  38022. }, function(e) {
  38023. var minimumStackMessage =
  38024. 'worker.js: while trying to getPage() and getOperatorList()';
  38025. var wrappedException;
  38026. // Turn the error into an obj that can be serialized
  38027. if (typeof e === 'string') {
  38028. wrappedException = {
  38029. message: e,
  38030. stack: minimumStackMessage
  38031. };
  38032. } else if (typeof e === 'object') {
  38033. wrappedException = {
  38034. message: e.message || e.toString(),
  38035. stack: e.stack || minimumStackMessage
  38036. };
  38037. } else {
  38038. wrappedException = {
  38039. message: 'Unknown exception type: ' + (typeof e),
  38040. stack: minimumStackMessage
  38041. };
  38042. }
  38043. handler.send('PageError', {
  38044. pageNum: pageNum,
  38045. error: wrappedException,
  38046. intent: data.intent
  38047. });
  38048. });
  38049. });
  38050. }, this);
  38051. handler.on('GetTextContent', function wphExtractText(data) {
  38052. return pdfManager.getPage(data.pageIndex).then(function(page) {
  38053. var pageNum = data.pageIndex + 1;
  38054. var start = Date.now();
  38055. return page.extractTextContent().then(function(textContent) {
  38056. info('text indexing: page=' + pageNum + ' - time=' +
  38057. (Date.now() - start) + 'ms');
  38058. return textContent;
  38059. });
  38060. });
  38061. });
  38062. handler.on('Cleanup', function wphCleanup(data) {
  38063. return pdfManager.cleanup();
  38064. });
  38065. handler.on('Terminate', function wphTerminate(data) {
  38066. pdfManager.terminate();
  38067. });
  38068. }
  38069. };
  38070. var consoleTimer = {};
  38071. var workerConsole = {
  38072. log: function log() {
  38073. var args = Array.prototype.slice.call(arguments);
  38074. globalScope.postMessage({
  38075. action: 'console_log',
  38076. data: args
  38077. });
  38078. },
  38079. error: function error() {
  38080. var args = Array.prototype.slice.call(arguments);
  38081. globalScope.postMessage({
  38082. action: 'console_error',
  38083. data: args
  38084. });
  38085. throw 'pdf.js execution error';
  38086. },
  38087. time: function time(name) {
  38088. consoleTimer[name] = Date.now();
  38089. },
  38090. timeEnd: function timeEnd(name) {
  38091. var time = consoleTimer[name];
  38092. if (!time) {
  38093. error('Unknown timer name ' + name);
  38094. }
  38095. this.log('Timer:', name, Date.now() - time);
  38096. }
  38097. };
  38098. // Worker thread?
  38099. if (typeof window === 'undefined') {
  38100. if (!('console' in globalScope)) {
  38101. globalScope.console = workerConsole;
  38102. }
  38103. // Listen for unsupported features so we can pass them on to the main thread.
  38104. PDFJS.UnsupportedManager.listen(function (msg) {
  38105. globalScope.postMessage({
  38106. action: '_unsupported_feature',
  38107. data: msg
  38108. });
  38109. });
  38110. var handler = new MessageHandler('worker_processor', this);
  38111. WorkerMessageHandler.setup(handler);
  38112. }
  38113. /* This class implements the QM Coder decoding as defined in
  38114. * JPEG 2000 Part I Final Committee Draft Version 1.0
  38115. * Annex C.3 Arithmetic decoding procedure
  38116. * available at http://www.jpeg.org/public/fcd15444-1.pdf
  38117. *
  38118. * The arithmetic decoder is used in conjunction with context models to decode
  38119. * JPEG2000 and JBIG2 streams.
  38120. */
  38121. var ArithmeticDecoder = (function ArithmeticDecoderClosure() {
  38122. // Table C-2
  38123. var QeTable = [
  38124. {qe: 0x5601, nmps: 1, nlps: 1, switchFlag: 1},
  38125. {qe: 0x3401, nmps: 2, nlps: 6, switchFlag: 0},
  38126. {qe: 0x1801, nmps: 3, nlps: 9, switchFlag: 0},
  38127. {qe: 0x0AC1, nmps: 4, nlps: 12, switchFlag: 0},
  38128. {qe: 0x0521, nmps: 5, nlps: 29, switchFlag: 0},
  38129. {qe: 0x0221, nmps: 38, nlps: 33, switchFlag: 0},
  38130. {qe: 0x5601, nmps: 7, nlps: 6, switchFlag: 1},
  38131. {qe: 0x5401, nmps: 8, nlps: 14, switchFlag: 0},
  38132. {qe: 0x4801, nmps: 9, nlps: 14, switchFlag: 0},
  38133. {qe: 0x3801, nmps: 10, nlps: 14, switchFlag: 0},
  38134. {qe: 0x3001, nmps: 11, nlps: 17, switchFlag: 0},
  38135. {qe: 0x2401, nmps: 12, nlps: 18, switchFlag: 0},
  38136. {qe: 0x1C01, nmps: 13, nlps: 20, switchFlag: 0},
  38137. {qe: 0x1601, nmps: 29, nlps: 21, switchFlag: 0},
  38138. {qe: 0x5601, nmps: 15, nlps: 14, switchFlag: 1},
  38139. {qe: 0x5401, nmps: 16, nlps: 14, switchFlag: 0},
  38140. {qe: 0x5101, nmps: 17, nlps: 15, switchFlag: 0},
  38141. {qe: 0x4801, nmps: 18, nlps: 16, switchFlag: 0},
  38142. {qe: 0x3801, nmps: 19, nlps: 17, switchFlag: 0},
  38143. {qe: 0x3401, nmps: 20, nlps: 18, switchFlag: 0},
  38144. {qe: 0x3001, nmps: 21, nlps: 19, switchFlag: 0},
  38145. {qe: 0x2801, nmps: 22, nlps: 19, switchFlag: 0},
  38146. {qe: 0x2401, nmps: 23, nlps: 20, switchFlag: 0},
  38147. {qe: 0x2201, nmps: 24, nlps: 21, switchFlag: 0},
  38148. {qe: 0x1C01, nmps: 25, nlps: 22, switchFlag: 0},
  38149. {qe: 0x1801, nmps: 26, nlps: 23, switchFlag: 0},
  38150. {qe: 0x1601, nmps: 27, nlps: 24, switchFlag: 0},
  38151. {qe: 0x1401, nmps: 28, nlps: 25, switchFlag: 0},
  38152. {qe: 0x1201, nmps: 29, nlps: 26, switchFlag: 0},
  38153. {qe: 0x1101, nmps: 30, nlps: 27, switchFlag: 0},
  38154. {qe: 0x0AC1, nmps: 31, nlps: 28, switchFlag: 0},
  38155. {qe: 0x09C1, nmps: 32, nlps: 29, switchFlag: 0},
  38156. {qe: 0x08A1, nmps: 33, nlps: 30, switchFlag: 0},
  38157. {qe: 0x0521, nmps: 34, nlps: 31, switchFlag: 0},
  38158. {qe: 0x0441, nmps: 35, nlps: 32, switchFlag: 0},
  38159. {qe: 0x02A1, nmps: 36, nlps: 33, switchFlag: 0},
  38160. {qe: 0x0221, nmps: 37, nlps: 34, switchFlag: 0},
  38161. {qe: 0x0141, nmps: 38, nlps: 35, switchFlag: 0},
  38162. {qe: 0x0111, nmps: 39, nlps: 36, switchFlag: 0},
  38163. {qe: 0x0085, nmps: 40, nlps: 37, switchFlag: 0},
  38164. {qe: 0x0049, nmps: 41, nlps: 38, switchFlag: 0},
  38165. {qe: 0x0025, nmps: 42, nlps: 39, switchFlag: 0},
  38166. {qe: 0x0015, nmps: 43, nlps: 40, switchFlag: 0},
  38167. {qe: 0x0009, nmps: 44, nlps: 41, switchFlag: 0},
  38168. {qe: 0x0005, nmps: 45, nlps: 42, switchFlag: 0},
  38169. {qe: 0x0001, nmps: 45, nlps: 43, switchFlag: 0},
  38170. {qe: 0x5601, nmps: 46, nlps: 46, switchFlag: 0}
  38171. ];
  38172. // C.3.5 Initialisation of the decoder (INITDEC)
  38173. function ArithmeticDecoder(data, start, end) {
  38174. this.data = data;
  38175. this.bp = start;
  38176. this.dataEnd = end;
  38177. this.chigh = data[start];
  38178. this.clow = 0;
  38179. this.byteIn();
  38180. this.chigh = ((this.chigh << 7) & 0xFFFF) | ((this.clow >> 9) & 0x7F);
  38181. this.clow = (this.clow << 7) & 0xFFFF;
  38182. this.ct -= 7;
  38183. this.a = 0x8000;
  38184. }
  38185. ArithmeticDecoder.prototype = {
  38186. // C.3.4 Compressed data input (BYTEIN)
  38187. byteIn: function ArithmeticDecoder_byteIn() {
  38188. var data = this.data;
  38189. var bp = this.bp;
  38190. if (data[bp] === 0xFF) {
  38191. var b1 = data[bp + 1];
  38192. if (b1 > 0x8F) {
  38193. this.clow += 0xFF00;
  38194. this.ct = 8;
  38195. } else {
  38196. bp++;
  38197. this.clow += (data[bp] << 9);
  38198. this.ct = 7;
  38199. this.bp = bp;
  38200. }
  38201. } else {
  38202. bp++;
  38203. this.clow += bp < this.dataEnd ? (data[bp] << 8) : 0xFF00;
  38204. this.ct = 8;
  38205. this.bp = bp;
  38206. }
  38207. if (this.clow > 0xFFFF) {
  38208. this.chigh += (this.clow >> 16);
  38209. this.clow &= 0xFFFF;
  38210. }
  38211. },
  38212. // C.3.2 Decoding a decision (DECODE)
  38213. readBit: function ArithmeticDecoder_readBit(contexts, pos) {
  38214. // contexts are packed into 1 byte:
  38215. // highest 7 bits carry cx.index, lowest bit carries cx.mps
  38216. var cx_index = contexts[pos] >> 1, cx_mps = contexts[pos] & 1;
  38217. var qeTableIcx = QeTable[cx_index];
  38218. var qeIcx = qeTableIcx.qe;
  38219. var d;
  38220. var a = this.a - qeIcx;
  38221. if (this.chigh < qeIcx) {
  38222. // exchangeLps
  38223. if (a < qeIcx) {
  38224. a = qeIcx;
  38225. d = cx_mps;
  38226. cx_index = qeTableIcx.nmps;
  38227. } else {
  38228. a = qeIcx;
  38229. d = 1 ^ cx_mps;
  38230. if (qeTableIcx.switchFlag === 1) {
  38231. cx_mps = d;
  38232. }
  38233. cx_index = qeTableIcx.nlps;
  38234. }
  38235. } else {
  38236. this.chigh -= qeIcx;
  38237. if ((a & 0x8000) !== 0) {
  38238. this.a = a;
  38239. return cx_mps;
  38240. }
  38241. // exchangeMps
  38242. if (a < qeIcx) {
  38243. d = 1 ^ cx_mps;
  38244. if (qeTableIcx.switchFlag === 1) {
  38245. cx_mps = d;
  38246. }
  38247. cx_index = qeTableIcx.nlps;
  38248. } else {
  38249. d = cx_mps;
  38250. cx_index = qeTableIcx.nmps;
  38251. }
  38252. }
  38253. // C.3.3 renormD;
  38254. do {
  38255. if (this.ct === 0) {
  38256. this.byteIn();
  38257. }
  38258. a <<= 1;
  38259. this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1);
  38260. this.clow = (this.clow << 1) & 0xFFFF;
  38261. this.ct--;
  38262. } while ((a & 0x8000) === 0);
  38263. this.a = a;
  38264. contexts[pos] = cx_index << 1 | cx_mps;
  38265. return d;
  38266. }
  38267. };
  38268. return ArithmeticDecoder;
  38269. })();
  38270. var JpegImage = (function jpegImage() {
  38271. var dctZigZag = new Uint8Array([
  38272. 0,
  38273. 1, 8,
  38274. 16, 9, 2,
  38275. 3, 10, 17, 24,
  38276. 32, 25, 18, 11, 4,
  38277. 5, 12, 19, 26, 33, 40,
  38278. 48, 41, 34, 27, 20, 13, 6,
  38279. 7, 14, 21, 28, 35, 42, 49, 56,
  38280. 57, 50, 43, 36, 29, 22, 15,
  38281. 23, 30, 37, 44, 51, 58,
  38282. 59, 52, 45, 38, 31,
  38283. 39, 46, 53, 60,
  38284. 61, 54, 47,
  38285. 55, 62,
  38286. 63
  38287. ]);
  38288. var dctCos1 = 4017; // cos(pi/16)
  38289. var dctSin1 = 799; // sin(pi/16)
  38290. var dctCos3 = 3406; // cos(3*pi/16)
  38291. var dctSin3 = 2276; // sin(3*pi/16)
  38292. var dctCos6 = 1567; // cos(6*pi/16)
  38293. var dctSin6 = 3784; // sin(6*pi/16)
  38294. var dctSqrt2 = 5793; // sqrt(2)
  38295. var dctSqrt1d2 = 2896; // sqrt(2) / 2
  38296. function constructor() {
  38297. }
  38298. function buildHuffmanTable(codeLengths, values) {
  38299. var k = 0, code = [], i, j, length = 16;
  38300. while (length > 0 && !codeLengths[length - 1]) {
  38301. length--;
  38302. }
  38303. code.push({children: [], index: 0});
  38304. var p = code[0], q;
  38305. for (i = 0; i < length; i++) {
  38306. for (j = 0; j < codeLengths[i]; j++) {
  38307. p = code.pop();
  38308. p.children[p.index] = values[k];
  38309. while (p.index > 0) {
  38310. p = code.pop();
  38311. }
  38312. p.index++;
  38313. code.push(p);
  38314. while (code.length <= i) {
  38315. code.push(q = {children: [], index: 0});
  38316. p.children[p.index] = q.children;
  38317. p = q;
  38318. }
  38319. k++;
  38320. }
  38321. if (i + 1 < length) {
  38322. // p here points to last code
  38323. code.push(q = {children: [], index: 0});
  38324. p.children[p.index] = q.children;
  38325. p = q;
  38326. }
  38327. }
  38328. return code[0].children;
  38329. }
  38330. function getBlockBufferOffset(component, row, col) {
  38331. return 64 * ((component.blocksPerLine + 1) * row + col);
  38332. }
  38333. function decodeScan(data, offset, frame, components, resetInterval,
  38334. spectralStart, spectralEnd, successivePrev, successive) {
  38335. var precision = frame.precision;
  38336. var samplesPerLine = frame.samplesPerLine;
  38337. var scanLines = frame.scanLines;
  38338. var mcusPerLine = frame.mcusPerLine;
  38339. var progressive = frame.progressive;
  38340. var maxH = frame.maxH, maxV = frame.maxV;
  38341. var startOffset = offset, bitsData = 0, bitsCount = 0;
  38342. function readBit() {
  38343. if (bitsCount > 0) {
  38344. bitsCount--;
  38345. return (bitsData >> bitsCount) & 1;
  38346. }
  38347. bitsData = data[offset++];
  38348. if (bitsData === 0xFF) {
  38349. var nextByte = data[offset++];
  38350. if (nextByte) {
  38351. throw 'unexpected marker: ' +
  38352. ((bitsData << 8) | nextByte).toString(16);
  38353. }
  38354. // unstuff 0
  38355. }
  38356. bitsCount = 7;
  38357. return bitsData >>> 7;
  38358. }
  38359. function decodeHuffman(tree) {
  38360. var node = tree;
  38361. while (true) {
  38362. node = node[readBit()];
  38363. if (typeof node === 'number') {
  38364. return node;
  38365. }
  38366. if (typeof node !== 'object') {
  38367. throw 'invalid huffman sequence';
  38368. }
  38369. }
  38370. }
  38371. function receive(length) {
  38372. var n = 0;
  38373. while (length > 0) {
  38374. n = (n << 1) | readBit();
  38375. length--;
  38376. }
  38377. return n;
  38378. }
  38379. function receiveAndExtend(length) {
  38380. if (length === 1) {
  38381. return readBit() === 1 ? 1 : -1;
  38382. }
  38383. var n = receive(length);
  38384. if (n >= 1 << (length - 1)) {
  38385. return n;
  38386. }
  38387. return n + (-1 << length) + 1;
  38388. }
  38389. function decodeBaseline(component, offset) {
  38390. var t = decodeHuffman(component.huffmanTableDC);
  38391. var diff = t === 0 ? 0 : receiveAndExtend(t);
  38392. component.blockData[offset] = (component.pred += diff);
  38393. var k = 1;
  38394. while (k < 64) {
  38395. var rs = decodeHuffman(component.huffmanTableAC);
  38396. var s = rs & 15, r = rs >> 4;
  38397. if (s === 0) {
  38398. if (r < 15) {
  38399. break;
  38400. }
  38401. k += 16;
  38402. continue;
  38403. }
  38404. k += r;
  38405. var z = dctZigZag[k];
  38406. component.blockData[offset + z] = receiveAndExtend(s);
  38407. k++;
  38408. }
  38409. }
  38410. function decodeDCFirst(component, offset) {
  38411. var t = decodeHuffman(component.huffmanTableDC);
  38412. var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
  38413. component.blockData[offset] = (component.pred += diff);
  38414. }
  38415. function decodeDCSuccessive(component, offset) {
  38416. component.blockData[offset] |= readBit() << successive;
  38417. }
  38418. var eobrun = 0;
  38419. function decodeACFirst(component, offset) {
  38420. if (eobrun > 0) {
  38421. eobrun--;
  38422. return;
  38423. }
  38424. var k = spectralStart, e = spectralEnd;
  38425. while (k <= e) {
  38426. var rs = decodeHuffman(component.huffmanTableAC);
  38427. var s = rs & 15, r = rs >> 4;
  38428. if (s === 0) {
  38429. if (r < 15) {
  38430. eobrun = receive(r) + (1 << r) - 1;
  38431. break;
  38432. }
  38433. k += 16;
  38434. continue;
  38435. }
  38436. k += r;
  38437. var z = dctZigZag[k];
  38438. component.blockData[offset + z] =
  38439. receiveAndExtend(s) * (1 << successive);
  38440. k++;
  38441. }
  38442. }
  38443. var successiveACState = 0, successiveACNextValue;
  38444. function decodeACSuccessive(component, offset) {
  38445. var k = spectralStart;
  38446. var e = spectralEnd;
  38447. var r = 0;
  38448. var s;
  38449. var rs;
  38450. while (k <= e) {
  38451. var z = dctZigZag[k];
  38452. switch (successiveACState) {
  38453. case 0: // initial state
  38454. rs = decodeHuffman(component.huffmanTableAC);
  38455. s = rs & 15;
  38456. r = rs >> 4;
  38457. if (s === 0) {
  38458. if (r < 15) {
  38459. eobrun = receive(r) + (1 << r);
  38460. successiveACState = 4;
  38461. } else {
  38462. r = 16;
  38463. successiveACState = 1;
  38464. }
  38465. } else {
  38466. if (s !== 1) {
  38467. throw 'invalid ACn encoding';
  38468. }
  38469. successiveACNextValue = receiveAndExtend(s);
  38470. successiveACState = r ? 2 : 3;
  38471. }
  38472. continue;
  38473. case 1: // skipping r zero items
  38474. case 2:
  38475. if (component.blockData[offset + z]) {
  38476. component.blockData[offset + z] += (readBit() << successive);
  38477. } else {
  38478. r--;
  38479. if (r === 0) {
  38480. successiveACState = successiveACState === 2 ? 3 : 0;
  38481. }
  38482. }
  38483. break;
  38484. case 3: // set value for a zero item
  38485. if (component.blockData[offset + z]) {
  38486. component.blockData[offset + z] += (readBit() << successive);
  38487. } else {
  38488. component.blockData[offset + z] =
  38489. successiveACNextValue << successive;
  38490. successiveACState = 0;
  38491. }
  38492. break;
  38493. case 4: // eob
  38494. if (component.blockData[offset + z]) {
  38495. component.blockData[offset + z] += (readBit() << successive);
  38496. }
  38497. break;
  38498. }
  38499. k++;
  38500. }
  38501. if (successiveACState === 4) {
  38502. eobrun--;
  38503. if (eobrun === 0) {
  38504. successiveACState = 0;
  38505. }
  38506. }
  38507. }
  38508. function decodeMcu(component, decode, mcu, row, col) {
  38509. var mcuRow = (mcu / mcusPerLine) | 0;
  38510. var mcuCol = mcu % mcusPerLine;
  38511. var blockRow = mcuRow * component.v + row;
  38512. var blockCol = mcuCol * component.h + col;
  38513. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  38514. decode(component, offset);
  38515. }
  38516. function decodeBlock(component, decode, mcu) {
  38517. var blockRow = (mcu / component.blocksPerLine) | 0;
  38518. var blockCol = mcu % component.blocksPerLine;
  38519. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  38520. decode(component, offset);
  38521. }
  38522. var componentsLength = components.length;
  38523. var component, i, j, k, n;
  38524. var decodeFn;
  38525. if (progressive) {
  38526. if (spectralStart === 0) {
  38527. decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
  38528. } else {
  38529. decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
  38530. }
  38531. } else {
  38532. decodeFn = decodeBaseline;
  38533. }
  38534. var mcu = 0, marker;
  38535. var mcuExpected;
  38536. if (componentsLength === 1) {
  38537. mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
  38538. } else {
  38539. mcuExpected = mcusPerLine * frame.mcusPerColumn;
  38540. }
  38541. if (!resetInterval) {
  38542. resetInterval = mcuExpected;
  38543. }
  38544. var h, v;
  38545. while (mcu < mcuExpected) {
  38546. // reset interval stuff
  38547. for (i = 0; i < componentsLength; i++) {
  38548. components[i].pred = 0;
  38549. }
  38550. eobrun = 0;
  38551. if (componentsLength === 1) {
  38552. component = components[0];
  38553. for (n = 0; n < resetInterval; n++) {
  38554. decodeBlock(component, decodeFn, mcu);
  38555. mcu++;
  38556. }
  38557. } else {
  38558. for (n = 0; n < resetInterval; n++) {
  38559. for (i = 0; i < componentsLength; i++) {
  38560. component = components[i];
  38561. h = component.h;
  38562. v = component.v;
  38563. for (j = 0; j < v; j++) {
  38564. for (k = 0; k < h; k++) {
  38565. decodeMcu(component, decodeFn, mcu, j, k);
  38566. }
  38567. }
  38568. }
  38569. mcu++;
  38570. }
  38571. }
  38572. // find marker
  38573. bitsCount = 0;
  38574. marker = (data[offset] << 8) | data[offset + 1];
  38575. if (marker <= 0xFF00) {
  38576. throw 'marker was not found';
  38577. }
  38578. if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
  38579. offset += 2;
  38580. } else {
  38581. break;
  38582. }
  38583. }
  38584. return offset - startOffset;
  38585. }
  38586. // A port of poppler's IDCT method which in turn is taken from:
  38587. // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
  38588. // 'Practical Fast 1-D DCT Algorithms with 11 Multiplications',
  38589. // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
  38590. // 988-991.
  38591. function quantizeAndInverse(component, blockBufferOffset, p) {
  38592. var qt = component.quantizationTable, blockData = component.blockData;
  38593. var v0, v1, v2, v3, v4, v5, v6, v7;
  38594. var p0, p1, p2, p3, p4, p5, p6, p7;
  38595. var t;
  38596. // inverse DCT on rows
  38597. for (var row = 0; row < 64; row += 8) {
  38598. // gather block data
  38599. p0 = blockData[blockBufferOffset + row];
  38600. p1 = blockData[blockBufferOffset + row + 1];
  38601. p2 = blockData[blockBufferOffset + row + 2];
  38602. p3 = blockData[blockBufferOffset + row + 3];
  38603. p4 = blockData[blockBufferOffset + row + 4];
  38604. p5 = blockData[blockBufferOffset + row + 5];
  38605. p6 = blockData[blockBufferOffset + row + 6];
  38606. p7 = blockData[blockBufferOffset + row + 7];
  38607. // dequant p0
  38608. p0 *= qt[row];
  38609. // check for all-zero AC coefficients
  38610. if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
  38611. t = (dctSqrt2 * p0 + 512) >> 10;
  38612. p[row] = t;
  38613. p[row + 1] = t;
  38614. p[row + 2] = t;
  38615. p[row + 3] = t;
  38616. p[row + 4] = t;
  38617. p[row + 5] = t;
  38618. p[row + 6] = t;
  38619. p[row + 7] = t;
  38620. continue;
  38621. }
  38622. // dequant p1 ... p7
  38623. p1 *= qt[row + 1];
  38624. p2 *= qt[row + 2];
  38625. p3 *= qt[row + 3];
  38626. p4 *= qt[row + 4];
  38627. p5 *= qt[row + 5];
  38628. p6 *= qt[row + 6];
  38629. p7 *= qt[row + 7];
  38630. // stage 4
  38631. v0 = (dctSqrt2 * p0 + 128) >> 8;
  38632. v1 = (dctSqrt2 * p4 + 128) >> 8;
  38633. v2 = p2;
  38634. v3 = p6;
  38635. v4 = (dctSqrt1d2 * (p1 - p7) + 128) >> 8;
  38636. v7 = (dctSqrt1d2 * (p1 + p7) + 128) >> 8;
  38637. v5 = p3 << 4;
  38638. v6 = p5 << 4;
  38639. // stage 3
  38640. v0 = (v0 + v1 + 1) >> 1;
  38641. v1 = v0 - v1;
  38642. t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
  38643. v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
  38644. v3 = t;
  38645. v4 = (v4 + v6 + 1) >> 1;
  38646. v6 = v4 - v6;
  38647. v7 = (v7 + v5 + 1) >> 1;
  38648. v5 = v7 - v5;
  38649. // stage 2
  38650. v0 = (v0 + v3 + 1) >> 1;
  38651. v3 = v0 - v3;
  38652. v1 = (v1 + v2 + 1) >> 1;
  38653. v2 = v1 - v2;
  38654. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  38655. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  38656. v7 = t;
  38657. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  38658. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  38659. v6 = t;
  38660. // stage 1
  38661. p[row] = v0 + v7;
  38662. p[row + 7] = v0 - v7;
  38663. p[row + 1] = v1 + v6;
  38664. p[row + 6] = v1 - v6;
  38665. p[row + 2] = v2 + v5;
  38666. p[row + 5] = v2 - v5;
  38667. p[row + 3] = v3 + v4;
  38668. p[row + 4] = v3 - v4;
  38669. }
  38670. // inverse DCT on columns
  38671. for (var col = 0; col < 8; ++col) {
  38672. p0 = p[col];
  38673. p1 = p[col + 8];
  38674. p2 = p[col + 16];
  38675. p3 = p[col + 24];
  38676. p4 = p[col + 32];
  38677. p5 = p[col + 40];
  38678. p6 = p[col + 48];
  38679. p7 = p[col + 56];
  38680. // check for all-zero AC coefficients
  38681. if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
  38682. t = (dctSqrt2 * p0 + 8192) >> 14;
  38683. // convert to 8 bit
  38684. t = (t < -2040) ? 0 : (t >= 2024) ? 255 : (t + 2056) >> 4;
  38685. blockData[blockBufferOffset + col] = t;
  38686. blockData[blockBufferOffset + col + 8] = t;
  38687. blockData[blockBufferOffset + col + 16] = t;
  38688. blockData[blockBufferOffset + col + 24] = t;
  38689. blockData[blockBufferOffset + col + 32] = t;
  38690. blockData[blockBufferOffset + col + 40] = t;
  38691. blockData[blockBufferOffset + col + 48] = t;
  38692. blockData[blockBufferOffset + col + 56] = t;
  38693. continue;
  38694. }
  38695. // stage 4
  38696. v0 = (dctSqrt2 * p0 + 2048) >> 12;
  38697. v1 = (dctSqrt2 * p4 + 2048) >> 12;
  38698. v2 = p2;
  38699. v3 = p6;
  38700. v4 = (dctSqrt1d2 * (p1 - p7) + 2048) >> 12;
  38701. v7 = (dctSqrt1d2 * (p1 + p7) + 2048) >> 12;
  38702. v5 = p3;
  38703. v6 = p5;
  38704. // stage 3
  38705. // Shift v0 by 128.5 << 5 here, so we don't need to shift p0...p7 when
  38706. // converting to UInt8 range later.
  38707. v0 = ((v0 + v1 + 1) >> 1) + 4112;
  38708. v1 = v0 - v1;
  38709. t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
  38710. v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
  38711. v3 = t;
  38712. v4 = (v4 + v6 + 1) >> 1;
  38713. v6 = v4 - v6;
  38714. v7 = (v7 + v5 + 1) >> 1;
  38715. v5 = v7 - v5;
  38716. // stage 2
  38717. v0 = (v0 + v3 + 1) >> 1;
  38718. v3 = v0 - v3;
  38719. v1 = (v1 + v2 + 1) >> 1;
  38720. v2 = v1 - v2;
  38721. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  38722. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  38723. v7 = t;
  38724. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  38725. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  38726. v6 = t;
  38727. // stage 1
  38728. p0 = v0 + v7;
  38729. p7 = v0 - v7;
  38730. p1 = v1 + v6;
  38731. p6 = v1 - v6;
  38732. p2 = v2 + v5;
  38733. p5 = v2 - v5;
  38734. p3 = v3 + v4;
  38735. p4 = v3 - v4;
  38736. // convert to 8-bit integers
  38737. p0 = (p0 < 16) ? 0 : (p0 >= 4080) ? 255 : p0 >> 4;
  38738. p1 = (p1 < 16) ? 0 : (p1 >= 4080) ? 255 : p1 >> 4;
  38739. p2 = (p2 < 16) ? 0 : (p2 >= 4080) ? 255 : p2 >> 4;
  38740. p3 = (p3 < 16) ? 0 : (p3 >= 4080) ? 255 : p3 >> 4;
  38741. p4 = (p4 < 16) ? 0 : (p4 >= 4080) ? 255 : p4 >> 4;
  38742. p5 = (p5 < 16) ? 0 : (p5 >= 4080) ? 255 : p5 >> 4;
  38743. p6 = (p6 < 16) ? 0 : (p6 >= 4080) ? 255 : p6 >> 4;
  38744. p7 = (p7 < 16) ? 0 : (p7 >= 4080) ? 255 : p7 >> 4;
  38745. // store block data
  38746. blockData[blockBufferOffset + col] = p0;
  38747. blockData[blockBufferOffset + col + 8] = p1;
  38748. blockData[blockBufferOffset + col + 16] = p2;
  38749. blockData[blockBufferOffset + col + 24] = p3;
  38750. blockData[blockBufferOffset + col + 32] = p4;
  38751. blockData[blockBufferOffset + col + 40] = p5;
  38752. blockData[blockBufferOffset + col + 48] = p6;
  38753. blockData[blockBufferOffset + col + 56] = p7;
  38754. }
  38755. }
  38756. function buildComponentData(frame, component) {
  38757. var blocksPerLine = component.blocksPerLine;
  38758. var blocksPerColumn = component.blocksPerColumn;
  38759. var computationBuffer = new Int16Array(64);
  38760. for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
  38761. for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
  38762. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  38763. quantizeAndInverse(component, offset, computationBuffer);
  38764. }
  38765. }
  38766. return component.blockData;
  38767. }
  38768. function clamp0to255(a) {
  38769. return a <= 0 ? 0 : a >= 255 ? 255 : a;
  38770. }
  38771. constructor.prototype = {
  38772. parse: function parse(data) {
  38773. function readUint16() {
  38774. var value = (data[offset] << 8) | data[offset + 1];
  38775. offset += 2;
  38776. return value;
  38777. }
  38778. function readDataBlock() {
  38779. var length = readUint16();
  38780. var array = data.subarray(offset, offset + length - 2);
  38781. offset += array.length;
  38782. return array;
  38783. }
  38784. function prepareComponents(frame) {
  38785. var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH);
  38786. var mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV);
  38787. for (var i = 0; i < frame.components.length; i++) {
  38788. component = frame.components[i];
  38789. var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) *
  38790. component.h / frame.maxH);
  38791. var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) *
  38792. component.v / frame.maxV);
  38793. var blocksPerLineForMcu = mcusPerLine * component.h;
  38794. var blocksPerColumnForMcu = mcusPerColumn * component.v;
  38795. var blocksBufferSize = 64 * blocksPerColumnForMcu *
  38796. (blocksPerLineForMcu + 1);
  38797. component.blockData = new Int16Array(blocksBufferSize);
  38798. component.blocksPerLine = blocksPerLine;
  38799. component.blocksPerColumn = blocksPerColumn;
  38800. }
  38801. frame.mcusPerLine = mcusPerLine;
  38802. frame.mcusPerColumn = mcusPerColumn;
  38803. }
  38804. var offset = 0, length = data.length;
  38805. var jfif = null;
  38806. var adobe = null;
  38807. var pixels = null;
  38808. var frame, resetInterval;
  38809. var quantizationTables = [];
  38810. var huffmanTablesAC = [], huffmanTablesDC = [];
  38811. var fileMarker = readUint16();
  38812. if (fileMarker !== 0xFFD8) { // SOI (Start of Image)
  38813. throw 'SOI not found';
  38814. }
  38815. fileMarker = readUint16();
  38816. while (fileMarker !== 0xFFD9) { // EOI (End of image)
  38817. var i, j, l;
  38818. switch(fileMarker) {
  38819. case 0xFFE0: // APP0 (Application Specific)
  38820. case 0xFFE1: // APP1
  38821. case 0xFFE2: // APP2
  38822. case 0xFFE3: // APP3
  38823. case 0xFFE4: // APP4
  38824. case 0xFFE5: // APP5
  38825. case 0xFFE6: // APP6
  38826. case 0xFFE7: // APP7
  38827. case 0xFFE8: // APP8
  38828. case 0xFFE9: // APP9
  38829. case 0xFFEA: // APP10
  38830. case 0xFFEB: // APP11
  38831. case 0xFFEC: // APP12
  38832. case 0xFFED: // APP13
  38833. case 0xFFEE: // APP14
  38834. case 0xFFEF: // APP15
  38835. case 0xFFFE: // COM (Comment)
  38836. var appData = readDataBlock();
  38837. if (fileMarker === 0xFFE0) {
  38838. if (appData[0] === 0x4A && appData[1] === 0x46 &&
  38839. appData[2] === 0x49 && appData[3] === 0x46 &&
  38840. appData[4] === 0) { // 'JFIF\x00'
  38841. jfif = {
  38842. version: { major: appData[5], minor: appData[6] },
  38843. densityUnits: appData[7],
  38844. xDensity: (appData[8] << 8) | appData[9],
  38845. yDensity: (appData[10] << 8) | appData[11],
  38846. thumbWidth: appData[12],
  38847. thumbHeight: appData[13],
  38848. thumbData: appData.subarray(14, 14 +
  38849. 3 * appData[12] * appData[13])
  38850. };
  38851. }
  38852. }
  38853. // TODO APP1 - Exif
  38854. if (fileMarker === 0xFFEE) {
  38855. if (appData[0] === 0x41 && appData[1] === 0x64 &&
  38856. appData[2] === 0x6F && appData[3] === 0x62 &&
  38857. appData[4] === 0x65) { // 'Adobe'
  38858. adobe = {
  38859. version: (appData[5] << 8) | appData[6],
  38860. flags0: (appData[7] << 8) | appData[8],
  38861. flags1: (appData[9] << 8) | appData[10],
  38862. transformCode: appData[11]
  38863. };
  38864. }
  38865. }
  38866. break;
  38867. case 0xFFDB: // DQT (Define Quantization Tables)
  38868. var quantizationTablesLength = readUint16();
  38869. var quantizationTablesEnd = quantizationTablesLength + offset - 2;
  38870. var z;
  38871. while (offset < quantizationTablesEnd) {
  38872. var quantizationTableSpec = data[offset++];
  38873. var tableData = new Uint16Array(64);
  38874. if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
  38875. for (j = 0; j < 64; j++) {
  38876. z = dctZigZag[j];
  38877. tableData[z] = data[offset++];
  38878. }
  38879. } else if ((quantizationTableSpec >> 4) === 1) { //16 bit
  38880. for (j = 0; j < 64; j++) {
  38881. z = dctZigZag[j];
  38882. tableData[z] = readUint16();
  38883. }
  38884. } else {
  38885. throw 'DQT: invalid table spec';
  38886. }
  38887. quantizationTables[quantizationTableSpec & 15] = tableData;
  38888. }
  38889. break;
  38890. case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
  38891. case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
  38892. case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
  38893. if (frame) {
  38894. throw 'Only single frame JPEGs supported';
  38895. }
  38896. readUint16(); // skip data length
  38897. frame = {};
  38898. frame.extended = (fileMarker === 0xFFC1);
  38899. frame.progressive = (fileMarker === 0xFFC2);
  38900. frame.precision = data[offset++];
  38901. frame.scanLines = readUint16();
  38902. frame.samplesPerLine = readUint16();
  38903. frame.components = [];
  38904. frame.componentIds = {};
  38905. var componentsCount = data[offset++], componentId;
  38906. var maxH = 0, maxV = 0;
  38907. for (i = 0; i < componentsCount; i++) {
  38908. componentId = data[offset];
  38909. var h = data[offset + 1] >> 4;
  38910. var v = data[offset + 1] & 15;
  38911. if (maxH < h) {
  38912. maxH = h;
  38913. }
  38914. if (maxV < v) {
  38915. maxV = v;
  38916. }
  38917. var qId = data[offset + 2];
  38918. l = frame.components.push({
  38919. h: h,
  38920. v: v,
  38921. quantizationTable: quantizationTables[qId]
  38922. });
  38923. frame.componentIds[componentId] = l - 1;
  38924. offset += 3;
  38925. }
  38926. frame.maxH = maxH;
  38927. frame.maxV = maxV;
  38928. prepareComponents(frame);
  38929. break;
  38930. case 0xFFC4: // DHT (Define Huffman Tables)
  38931. var huffmanLength = readUint16();
  38932. for (i = 2; i < huffmanLength;) {
  38933. var huffmanTableSpec = data[offset++];
  38934. var codeLengths = new Uint8Array(16);
  38935. var codeLengthSum = 0;
  38936. for (j = 0; j < 16; j++, offset++) {
  38937. codeLengthSum += (codeLengths[j] = data[offset]);
  38938. }
  38939. var huffmanValues = new Uint8Array(codeLengthSum);
  38940. for (j = 0; j < codeLengthSum; j++, offset++) {
  38941. huffmanValues[j] = data[offset];
  38942. }
  38943. i += 17 + codeLengthSum;
  38944. ((huffmanTableSpec >> 4) === 0 ?
  38945. huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
  38946. buildHuffmanTable(codeLengths, huffmanValues);
  38947. }
  38948. break;
  38949. case 0xFFDD: // DRI (Define Restart Interval)
  38950. readUint16(); // skip data length
  38951. resetInterval = readUint16();
  38952. break;
  38953. case 0xFFDA: // SOS (Start of Scan)
  38954. var scanLength = readUint16();
  38955. var selectorsCount = data[offset++];
  38956. var components = [], component;
  38957. for (i = 0; i < selectorsCount; i++) {
  38958. var componentIndex = frame.componentIds[data[offset++]];
  38959. component = frame.components[componentIndex];
  38960. var tableSpec = data[offset++];
  38961. component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
  38962. component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
  38963. components.push(component);
  38964. }
  38965. var spectralStart = data[offset++];
  38966. var spectralEnd = data[offset++];
  38967. var successiveApproximation = data[offset++];
  38968. var processed = decodeScan(data, offset,
  38969. frame, components, resetInterval,
  38970. spectralStart, spectralEnd,
  38971. successiveApproximation >> 4, successiveApproximation & 15);
  38972. offset += processed;
  38973. break;
  38974. case 0xFFFF: // Fill bytes
  38975. if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
  38976. offset--;
  38977. }
  38978. break;
  38979. default:
  38980. if (data[offset - 3] === 0xFF &&
  38981. data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
  38982. // could be incorrect encoding -- last 0xFF byte of the previous
  38983. // block was eaten by the encoder
  38984. offset -= 3;
  38985. break;
  38986. }
  38987. throw 'unknown JPEG marker ' + fileMarker.toString(16);
  38988. }
  38989. fileMarker = readUint16();
  38990. }
  38991. this.width = frame.samplesPerLine;
  38992. this.height = frame.scanLines;
  38993. this.jfif = jfif;
  38994. this.adobe = adobe;
  38995. this.components = [];
  38996. for (i = 0; i < frame.components.length; i++) {
  38997. component = frame.components[i];
  38998. this.components.push({
  38999. output: buildComponentData(frame, component),
  39000. scaleX: component.h / frame.maxH,
  39001. scaleY: component.v / frame.maxV,
  39002. blocksPerLine: component.blocksPerLine,
  39003. blocksPerColumn: component.blocksPerColumn
  39004. });
  39005. }
  39006. this.numComponents = this.components.length;
  39007. },
  39008. _getLinearizedBlockData: function getLinearizedBlockData(width, height) {
  39009. var scaleX = this.width / width, scaleY = this.height / height;
  39010. var component, componentScaleX, componentScaleY, blocksPerScanline;
  39011. var x, y, i, j, k;
  39012. var index;
  39013. var offset = 0;
  39014. var output;
  39015. var numComponents = this.components.length;
  39016. var dataLength = width * height * numComponents;
  39017. var data = new Uint8Array(dataLength);
  39018. var xScaleBlockOffset = new Uint32Array(width);
  39019. var mask3LSB = 0xfffffff8; // used to clear the 3 LSBs
  39020. for (i = 0; i < numComponents; i++) {
  39021. component = this.components[i];
  39022. componentScaleX = component.scaleX * scaleX;
  39023. componentScaleY = component.scaleY * scaleY;
  39024. offset = i;
  39025. output = component.output;
  39026. blocksPerScanline = (component.blocksPerLine + 1) << 3;
  39027. // precalculate the xScaleBlockOffset
  39028. for (x = 0; x < width; x++) {
  39029. j = 0 | (x * componentScaleX);
  39030. xScaleBlockOffset[x] = ((j & mask3LSB) << 3) | (j & 7);
  39031. }
  39032. // linearize the blocks of the component
  39033. for (y = 0; y < height; y++) {
  39034. j = 0 | (y * componentScaleY);
  39035. index = blocksPerScanline * (j & mask3LSB) | ((j & 7) << 3);
  39036. for (x = 0; x < width; x++) {
  39037. data[offset] = output[index + xScaleBlockOffset[x]];
  39038. offset += numComponents;
  39039. }
  39040. }
  39041. }
  39042. // decodeTransform contains pairs of multiplier (-256..256) and additive
  39043. var transform = this.decodeTransform;
  39044. if (transform) {
  39045. for (i = 0; i < dataLength;) {
  39046. for (j = 0, k = 0; j < numComponents; j++, i++, k += 2) {
  39047. data[i] = ((data[i] * transform[k]) >> 8) + transform[k + 1];
  39048. }
  39049. }
  39050. }
  39051. return data;
  39052. },
  39053. _isColorConversionNeeded: function isColorConversionNeeded() {
  39054. if (this.adobe && this.adobe.transformCode) {
  39055. // The adobe transform marker overrides any previous setting
  39056. return true;
  39057. } else if (this.numComponents === 3) {
  39058. return true;
  39059. } else {
  39060. return false;
  39061. }
  39062. },
  39063. _convertYccToRgb: function convertYccToRgb(data) {
  39064. var Y, Cb, Cr;
  39065. for (var i = 0, length = data.length; i < length; i += 3) {
  39066. Y = data[i ];
  39067. Cb = data[i + 1];
  39068. Cr = data[i + 2];
  39069. data[i ] = clamp0to255(Y - 179.456 + 1.402 * Cr);
  39070. data[i + 1] = clamp0to255(Y + 135.459 - 0.344 * Cb - 0.714 * Cr);
  39071. data[i + 2] = clamp0to255(Y - 226.816 + 1.772 * Cb);
  39072. }
  39073. return data;
  39074. },
  39075. _convertYcckToRgb: function convertYcckToRgb(data) {
  39076. var Y, Cb, Cr, k;
  39077. var offset = 0;
  39078. for (var i = 0, length = data.length; i < length; i += 4) {
  39079. Y = data[i];
  39080. Cb = data[i + 1];
  39081. Cr = data[i + 2];
  39082. k = data[i + 3];
  39083. var r = -122.67195406894 +
  39084. Cb * (-6.60635669420364e-5 * Cb + 0.000437130475926232 * Cr -
  39085. 5.4080610064599e-5 * Y + 0.00048449797120281 * k -
  39086. 0.154362151871126) +
  39087. Cr * (-0.000957964378445773 * Cr + 0.000817076911346625 * Y -
  39088. 0.00477271405408747 * k + 1.53380253221734) +
  39089. Y * (0.000961250184130688 * Y - 0.00266257332283933 * k +
  39090. 0.48357088451265) +
  39091. k * (-0.000336197177618394 * k + 0.484791561490776);
  39092. var g = 107.268039397724 +
  39093. Cb * (2.19927104525741e-5 * Cb - 0.000640992018297945 * Cr +
  39094. 0.000659397001245577 * Y + 0.000426105652938837 * k -
  39095. 0.176491792462875) +
  39096. Cr * (-0.000778269941513683 * Cr + 0.00130872261408275 * Y +
  39097. 0.000770482631801132 * k - 0.151051492775562) +
  39098. Y * (0.00126935368114843 * Y - 0.00265090189010898 * k +
  39099. 0.25802910206845) +
  39100. k * (-0.000318913117588328 * k - 0.213742400323665);
  39101. var b = -20.810012546947 +
  39102. Cb * (-0.000570115196973677 * Cb - 2.63409051004589e-5 * Cr +
  39103. 0.0020741088115012 * Y - 0.00288260236853442 * k +
  39104. 0.814272968359295) +
  39105. Cr * (-1.53496057440975e-5 * Cr - 0.000132689043961446 * Y +
  39106. 0.000560833691242812 * k - 0.195152027534049) +
  39107. Y * (0.00174418132927582 * Y - 0.00255243321439347 * k +
  39108. 0.116935020465145) +
  39109. k * (-0.000343531996510555 * k + 0.24165260232407);
  39110. data[offset++] = clamp0to255(r);
  39111. data[offset++] = clamp0to255(g);
  39112. data[offset++] = clamp0to255(b);
  39113. }
  39114. return data;
  39115. },
  39116. _convertYcckToCmyk: function convertYcckToCmyk(data) {
  39117. var Y, Cb, Cr;
  39118. for (var i = 0, length = data.length; i < length; i += 4) {
  39119. Y = data[i];
  39120. Cb = data[i + 1];
  39121. Cr = data[i + 2];
  39122. data[i ] = clamp0to255(434.456 - Y - 1.402 * Cr);
  39123. data[i + 1] = clamp0to255(119.541 - Y + 0.344 * Cb + 0.714 * Cr);
  39124. data[i + 2] = clamp0to255(481.816 - Y - 1.772 * Cb);
  39125. // K in data[i + 3] is unchanged
  39126. }
  39127. return data;
  39128. },
  39129. _convertCmykToRgb: function convertCmykToRgb(data) {
  39130. var c, m, y, k;
  39131. var offset = 0;
  39132. var min = -255 * 255 * 255;
  39133. var scale = 1 / 255 / 255;
  39134. for (var i = 0, length = data.length; i < length; i += 4) {
  39135. c = data[i];
  39136. m = data[i + 1];
  39137. y = data[i + 2];
  39138. k = data[i + 3];
  39139. var r =
  39140. c * (-4.387332384609988 * c + 54.48615194189176 * m +
  39141. 18.82290502165302 * y + 212.25662451639585 * k -
  39142. 72734.4411664936) +
  39143. m * (1.7149763477362134 * m - 5.6096736904047315 * y -
  39144. 17.873870861415444 * k - 1401.7366389350734) +
  39145. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  39146. 4465.541406466231) -
  39147. k * (21.86122147463605 * k + 48317.86113160301);
  39148. var g =
  39149. c * (8.841041422036149 * c + 60.118027045597366 * m +
  39150. 6.871425592049007 * y + 31.159100130055922 * k -
  39151. 20220.756542821975) +
  39152. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  39153. 131.35250912493976 * k - 48691.05921601825) +
  39154. y * (4.444339102852739 * y + 9.8632861493405 * k -
  39155. 6341.191035517494) -
  39156. k * (20.737325471181034 * k + 47890.15695978492);
  39157. var b =
  39158. c * (0.8842522430003296 * c + 8.078677503112928 * m +
  39159. 30.89978309703729 * y - 0.23883238689178934 * k -
  39160. 3616.812083916688) +
  39161. m * (10.49593273432072 * m + 63.02378494754052 * y +
  39162. 50.606957656360734 * k - 28620.90484698408) +
  39163. y * (0.03296041114873217 * y + 115.60384449646641 * k -
  39164. 49363.43385999684) -
  39165. k * (22.33816807309886 * k + 45932.16563550634);
  39166. data[offset++] = r >= 0 ? 255 : r <= min ? 0 : 255 + r * scale | 0;
  39167. data[offset++] = g >= 0 ? 255 : g <= min ? 0 : 255 + g * scale | 0;
  39168. data[offset++] = b >= 0 ? 255 : b <= min ? 0 : 255 + b * scale | 0;
  39169. }
  39170. return data;
  39171. },
  39172. getData: function getData(width, height, forceRGBoutput) {
  39173. if (this.numComponents > 4) {
  39174. throw 'Unsupported color mode';
  39175. }
  39176. // type of data: Uint8Array(width * height * numComponents)
  39177. var data = this._getLinearizedBlockData(width, height);
  39178. if (this.numComponents === 3) {
  39179. return this._convertYccToRgb(data);
  39180. } else if (this.numComponents === 4) {
  39181. if (this._isColorConversionNeeded()) {
  39182. if (forceRGBoutput) {
  39183. return this._convertYcckToRgb(data);
  39184. } else {
  39185. return this._convertYcckToCmyk(data);
  39186. }
  39187. } else if (forceRGBoutput) {
  39188. return this._convertCmykToRgb(data);
  39189. }
  39190. }
  39191. return data;
  39192. }
  39193. };
  39194. return constructor;
  39195. })();
  39196. var JpxImage = (function JpxImageClosure() {
  39197. // Table E.1
  39198. var SubbandsGainLog2 = {
  39199. 'LL': 0,
  39200. 'LH': 1,
  39201. 'HL': 1,
  39202. 'HH': 2
  39203. };
  39204. function JpxImage() {
  39205. this.failOnCorruptedImage = false;
  39206. }
  39207. JpxImage.prototype = {
  39208. parse: function JpxImage_parse(data) {
  39209. var head = readUint16(data, 0);
  39210. // No box header, immediate start of codestream (SOC)
  39211. if (head === 0xFF4F) {
  39212. this.parseCodestream(data, 0, data.length);
  39213. return;
  39214. }
  39215. var position = 0, length = data.length;
  39216. while (position < length) {
  39217. var headerSize = 8;
  39218. var lbox = readUint32(data, position);
  39219. var tbox = readUint32(data, position + 4);
  39220. position += headerSize;
  39221. if (lbox === 1) {
  39222. // XLBox: read UInt64 according to spec.
  39223. // JavaScript's int precision of 53 bit should be sufficient here.
  39224. lbox = readUint32(data, position) * 4294967296 +
  39225. readUint32(data, position + 4);
  39226. position += 8;
  39227. headerSize += 8;
  39228. }
  39229. if (lbox === 0) {
  39230. lbox = length - position + headerSize;
  39231. }
  39232. if (lbox < headerSize) {
  39233. throw new Error('JPX Error: Invalid box field size');
  39234. }
  39235. var dataLength = lbox - headerSize;
  39236. var jumpDataLength = true;
  39237. switch (tbox) {
  39238. case 0x6A703268: // 'jp2h'
  39239. jumpDataLength = false; // parsing child boxes
  39240. break;
  39241. case 0x636F6C72: // 'colr'
  39242. // Colorspaces are not used, the CS from the PDF is used.
  39243. var method = data[position];
  39244. var precedence = data[position + 1];
  39245. var approximation = data[position + 2];
  39246. if (method === 1) {
  39247. // enumerated colorspace
  39248. var colorspace = readUint32(data, position + 3);
  39249. switch (colorspace) {
  39250. case 16: // this indicates a sRGB colorspace
  39251. case 17: // this indicates a grayscale colorspace
  39252. case 18: // this indicates a YUV colorspace
  39253. break;
  39254. default:
  39255. warn('Unknown colorspace ' + colorspace);
  39256. break;
  39257. }
  39258. } else if (method === 2) {
  39259. info('ICC profile not supported');
  39260. }
  39261. break;
  39262. case 0x6A703263: // 'jp2c'
  39263. this.parseCodestream(data, position, position + dataLength);
  39264. break;
  39265. case 0x6A502020: // 'jP\024\024'
  39266. if (0x0d0a870a !== readUint32(data, position)) {
  39267. warn('Invalid JP2 signature');
  39268. }
  39269. break;
  39270. // The following header types are valid but currently not used:
  39271. case 0x6A501A1A: // 'jP\032\032'
  39272. case 0x66747970: // 'ftyp'
  39273. case 0x72726571: // 'rreq'
  39274. case 0x72657320: // 'res '
  39275. case 0x69686472: // 'ihdr'
  39276. break;
  39277. default:
  39278. var headerType = String.fromCharCode((tbox >> 24) & 0xFF,
  39279. (tbox >> 16) & 0xFF,
  39280. (tbox >> 8) & 0xFF,
  39281. tbox & 0xFF);
  39282. warn('Unsupported header type ' + tbox + ' (' + headerType + ')');
  39283. break;
  39284. }
  39285. if (jumpDataLength) {
  39286. position += dataLength;
  39287. }
  39288. }
  39289. },
  39290. parseImageProperties: function JpxImage_parseImageProperties(stream) {
  39291. var newByte = stream.getByte();
  39292. while (newByte >= 0) {
  39293. var oldByte = newByte;
  39294. newByte = stream.getByte();
  39295. var code = (oldByte << 8) | newByte;
  39296. // Image and tile size (SIZ)
  39297. if (code === 0xFF51) {
  39298. stream.skip(4);
  39299. var Xsiz = stream.getInt32() >>> 0; // Byte 4
  39300. var Ysiz = stream.getInt32() >>> 0; // Byte 8
  39301. var XOsiz = stream.getInt32() >>> 0; // Byte 12
  39302. var YOsiz = stream.getInt32() >>> 0; // Byte 16
  39303. stream.skip(16);
  39304. var Csiz = stream.getUint16(); // Byte 36
  39305. this.width = Xsiz - XOsiz;
  39306. this.height = Ysiz - YOsiz;
  39307. this.componentsCount = Csiz;
  39308. // Results are always returned as Uint8Arrays
  39309. this.bitsPerComponent = 8;
  39310. return;
  39311. }
  39312. }
  39313. throw new Error('JPX Error: No size marker found in JPX stream');
  39314. },
  39315. parseCodestream: function JpxImage_parseCodestream(data, start, end) {
  39316. var context = {};
  39317. try {
  39318. var doNotRecover = false;
  39319. var position = start;
  39320. while (position + 1 < end) {
  39321. var code = readUint16(data, position);
  39322. position += 2;
  39323. var length = 0, j, sqcd, spqcds, spqcdSize, scalarExpounded, tile;
  39324. switch (code) {
  39325. case 0xFF4F: // Start of codestream (SOC)
  39326. context.mainHeader = true;
  39327. break;
  39328. case 0xFFD9: // End of codestream (EOC)
  39329. break;
  39330. case 0xFF51: // Image and tile size (SIZ)
  39331. length = readUint16(data, position);
  39332. var siz = {};
  39333. siz.Xsiz = readUint32(data, position + 4);
  39334. siz.Ysiz = readUint32(data, position + 8);
  39335. siz.XOsiz = readUint32(data, position + 12);
  39336. siz.YOsiz = readUint32(data, position + 16);
  39337. siz.XTsiz = readUint32(data, position + 20);
  39338. siz.YTsiz = readUint32(data, position + 24);
  39339. siz.XTOsiz = readUint32(data, position + 28);
  39340. siz.YTOsiz = readUint32(data, position + 32);
  39341. var componentsCount = readUint16(data, position + 36);
  39342. siz.Csiz = componentsCount;
  39343. var components = [];
  39344. j = position + 38;
  39345. for (var i = 0; i < componentsCount; i++) {
  39346. var component = {
  39347. precision: (data[j] & 0x7F) + 1,
  39348. isSigned: !!(data[j] & 0x80),
  39349. XRsiz: data[j + 1],
  39350. YRsiz: data[j + 1]
  39351. };
  39352. calculateComponentDimensions(component, siz);
  39353. components.push(component);
  39354. }
  39355. context.SIZ = siz;
  39356. context.components = components;
  39357. calculateTileGrids(context, components);
  39358. context.QCC = [];
  39359. context.COC = [];
  39360. break;
  39361. case 0xFF5C: // Quantization default (QCD)
  39362. length = readUint16(data, position);
  39363. var qcd = {};
  39364. j = position + 2;
  39365. sqcd = data[j++];
  39366. switch (sqcd & 0x1F) {
  39367. case 0:
  39368. spqcdSize = 8;
  39369. scalarExpounded = true;
  39370. break;
  39371. case 1:
  39372. spqcdSize = 16;
  39373. scalarExpounded = false;
  39374. break;
  39375. case 2:
  39376. spqcdSize = 16;
  39377. scalarExpounded = true;
  39378. break;
  39379. default:
  39380. throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
  39381. }
  39382. qcd.noQuantization = (spqcdSize === 8);
  39383. qcd.scalarExpounded = scalarExpounded;
  39384. qcd.guardBits = sqcd >> 5;
  39385. spqcds = [];
  39386. while (j < length + position) {
  39387. var spqcd = {};
  39388. if (spqcdSize === 8) {
  39389. spqcd.epsilon = data[j++] >> 3;
  39390. spqcd.mu = 0;
  39391. } else {
  39392. spqcd.epsilon = data[j] >> 3;
  39393. spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
  39394. j += 2;
  39395. }
  39396. spqcds.push(spqcd);
  39397. }
  39398. qcd.SPqcds = spqcds;
  39399. if (context.mainHeader) {
  39400. context.QCD = qcd;
  39401. } else {
  39402. context.currentTile.QCD = qcd;
  39403. context.currentTile.QCC = [];
  39404. }
  39405. break;
  39406. case 0xFF5D: // Quantization component (QCC)
  39407. length = readUint16(data, position);
  39408. var qcc = {};
  39409. j = position + 2;
  39410. var cqcc;
  39411. if (context.SIZ.Csiz < 257) {
  39412. cqcc = data[j++];
  39413. } else {
  39414. cqcc = readUint16(data, j);
  39415. j += 2;
  39416. }
  39417. sqcd = data[j++];
  39418. switch (sqcd & 0x1F) {
  39419. case 0:
  39420. spqcdSize = 8;
  39421. scalarExpounded = true;
  39422. break;
  39423. case 1:
  39424. spqcdSize = 16;
  39425. scalarExpounded = false;
  39426. break;
  39427. case 2:
  39428. spqcdSize = 16;
  39429. scalarExpounded = true;
  39430. break;
  39431. default:
  39432. throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
  39433. }
  39434. qcc.noQuantization = (spqcdSize === 8);
  39435. qcc.scalarExpounded = scalarExpounded;
  39436. qcc.guardBits = sqcd >> 5;
  39437. spqcds = [];
  39438. while (j < (length + position)) {
  39439. spqcd = {};
  39440. if (spqcdSize === 8) {
  39441. spqcd.epsilon = data[j++] >> 3;
  39442. spqcd.mu = 0;
  39443. } else {
  39444. spqcd.epsilon = data[j] >> 3;
  39445. spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
  39446. j += 2;
  39447. }
  39448. spqcds.push(spqcd);
  39449. }
  39450. qcc.SPqcds = spqcds;
  39451. if (context.mainHeader) {
  39452. context.QCC[cqcc] = qcc;
  39453. } else {
  39454. context.currentTile.QCC[cqcc] = qcc;
  39455. }
  39456. break;
  39457. case 0xFF52: // Coding style default (COD)
  39458. length = readUint16(data, position);
  39459. var cod = {};
  39460. j = position + 2;
  39461. var scod = data[j++];
  39462. cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
  39463. cod.sopMarkerUsed = !!(scod & 2);
  39464. cod.ephMarkerUsed = !!(scod & 4);
  39465. cod.progressionOrder = data[j++];
  39466. cod.layersCount = readUint16(data, j);
  39467. j += 2;
  39468. cod.multipleComponentTransform = data[j++];
  39469. cod.decompositionLevelsCount = data[j++];
  39470. cod.xcb = (data[j++] & 0xF) + 2;
  39471. cod.ycb = (data[j++] & 0xF) + 2;
  39472. var blockStyle = data[j++];
  39473. cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
  39474. cod.resetContextProbabilities = !!(blockStyle & 2);
  39475. cod.terminationOnEachCodingPass = !!(blockStyle & 4);
  39476. cod.verticalyStripe = !!(blockStyle & 8);
  39477. cod.predictableTermination = !!(blockStyle & 16);
  39478. cod.segmentationSymbolUsed = !!(blockStyle & 32);
  39479. cod.reversibleTransformation = data[j++];
  39480. if (cod.entropyCoderWithCustomPrecincts) {
  39481. var precinctsSizes = [];
  39482. while (j < length + position) {
  39483. var precinctsSize = data[j++];
  39484. precinctsSizes.push({
  39485. PPx: precinctsSize & 0xF,
  39486. PPy: precinctsSize >> 4
  39487. });
  39488. }
  39489. cod.precinctsSizes = precinctsSizes;
  39490. }
  39491. var unsupported = [];
  39492. if (cod.selectiveArithmeticCodingBypass) {
  39493. unsupported.push('selectiveArithmeticCodingBypass');
  39494. }
  39495. if (cod.resetContextProbabilities) {
  39496. unsupported.push('resetContextProbabilities');
  39497. }
  39498. if (cod.terminationOnEachCodingPass) {
  39499. unsupported.push('terminationOnEachCodingPass');
  39500. }
  39501. if (cod.verticalyStripe) {
  39502. unsupported.push('verticalyStripe');
  39503. }
  39504. if (cod.predictableTermination) {
  39505. unsupported.push('predictableTermination');
  39506. }
  39507. if (unsupported.length > 0) {
  39508. doNotRecover = true;
  39509. throw new Error('JPX Error: Unsupported COD options (' +
  39510. unsupported.join(', ') + ')');
  39511. }
  39512. if (context.mainHeader) {
  39513. context.COD = cod;
  39514. } else {
  39515. context.currentTile.COD = cod;
  39516. context.currentTile.COC = [];
  39517. }
  39518. break;
  39519. case 0xFF90: // Start of tile-part (SOT)
  39520. length = readUint16(data, position);
  39521. tile = {};
  39522. tile.index = readUint16(data, position + 2);
  39523. tile.length = readUint32(data, position + 4);
  39524. tile.dataEnd = tile.length + position - 2;
  39525. tile.partIndex = data[position + 8];
  39526. tile.partsCount = data[position + 9];
  39527. context.mainHeader = false;
  39528. if (tile.partIndex === 0) {
  39529. // reset component specific settings
  39530. tile.COD = context.COD;
  39531. tile.COC = context.COC.slice(0); // clone of the global COC
  39532. tile.QCD = context.QCD;
  39533. tile.QCC = context.QCC.slice(0); // clone of the global COC
  39534. }
  39535. context.currentTile = tile;
  39536. break;
  39537. case 0xFF93: // Start of data (SOD)
  39538. tile = context.currentTile;
  39539. if (tile.partIndex === 0) {
  39540. initializeTile(context, tile.index);
  39541. buildPackets(context);
  39542. }
  39543. // moving to the end of the data
  39544. length = tile.dataEnd - position;
  39545. parseTilePackets(context, data, position, length);
  39546. break;
  39547. case 0xFF55: // Tile-part lengths, main header (TLM)
  39548. case 0xFF57: // Packet length, main header (PLM)
  39549. case 0xFF58: // Packet length, tile-part header (PLT)
  39550. case 0xFF64: // Comment (COM)
  39551. length = readUint16(data, position);
  39552. // skipping content
  39553. break;
  39554. case 0xFF53: // Coding style component (COC)
  39555. throw new Error('JPX Error: Codestream code 0xFF53 (COC) is ' +
  39556. 'not implemented');
  39557. default:
  39558. throw new Error('JPX Error: Unknown codestream code: ' +
  39559. code.toString(16));
  39560. }
  39561. position += length;
  39562. }
  39563. } catch (e) {
  39564. if (doNotRecover || this.failOnCorruptedImage) {
  39565. throw e;
  39566. } else {
  39567. warn('Trying to recover from ' + e.message);
  39568. }
  39569. }
  39570. this.tiles = transformComponents(context);
  39571. this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
  39572. this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
  39573. this.componentsCount = context.SIZ.Csiz;
  39574. }
  39575. };
  39576. function calculateComponentDimensions(component, siz) {
  39577. // Section B.2 Component mapping
  39578. component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
  39579. component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
  39580. component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
  39581. component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
  39582. component.width = component.x1 - component.x0;
  39583. component.height = component.y1 - component.y0;
  39584. }
  39585. function calculateTileGrids(context, components) {
  39586. var siz = context.SIZ;
  39587. // Section B.3 Division into tile and tile-components
  39588. var tile, tiles = [];
  39589. var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
  39590. var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
  39591. for (var q = 0; q < numYtiles; q++) {
  39592. for (var p = 0; p < numXtiles; p++) {
  39593. tile = {};
  39594. tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
  39595. tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
  39596. tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
  39597. tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
  39598. tile.width = tile.tx1 - tile.tx0;
  39599. tile.height = tile.ty1 - tile.ty0;
  39600. tile.components = [];
  39601. tiles.push(tile);
  39602. }
  39603. }
  39604. context.tiles = tiles;
  39605. var componentsCount = siz.Csiz;
  39606. for (var i = 0, ii = componentsCount; i < ii; i++) {
  39607. var component = components[i];
  39608. for (var j = 0, jj = tiles.length; j < jj; j++) {
  39609. var tileComponent = {};
  39610. tile = tiles[j];
  39611. tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
  39612. tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
  39613. tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
  39614. tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
  39615. tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
  39616. tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
  39617. tile.components[i] = tileComponent;
  39618. }
  39619. }
  39620. }
  39621. function getBlocksDimensions(context, component, r) {
  39622. var codOrCoc = component.codingStyleParameters;
  39623. var result = {};
  39624. if (!codOrCoc.entropyCoderWithCustomPrecincts) {
  39625. result.PPx = 15;
  39626. result.PPy = 15;
  39627. } else {
  39628. result.PPx = codOrCoc.precinctsSizes[r].PPx;
  39629. result.PPy = codOrCoc.precinctsSizes[r].PPy;
  39630. }
  39631. // calculate codeblock size as described in section B.7
  39632. result.xcb_ = (r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) :
  39633. Math.min(codOrCoc.xcb, result.PPx));
  39634. result.ycb_ = (r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) :
  39635. Math.min(codOrCoc.ycb, result.PPy));
  39636. return result;
  39637. }
  39638. function buildPrecincts(context, resolution, dimensions) {
  39639. // Section B.6 Division resolution to precincts
  39640. var precinctWidth = 1 << dimensions.PPx;
  39641. var precinctHeight = 1 << dimensions.PPy;
  39642. // Jasper introduces codeblock groups for mapping each subband codeblocks
  39643. // to precincts. Precinct partition divides a resolution according to width
  39644. // and height parameters. The subband that belongs to the resolution level
  39645. // has a different size than the level, unless it is the zero resolution.
  39646. // From Jasper documentation: jpeg2000.pdf, section K: Tier-2 coding:
  39647. // The precinct partitioning for a particular subband is derived from a
  39648. // partitioning of its parent LL band (i.e., the LL band at the next higher
  39649. // resolution level)... The LL band associated with each resolution level is
  39650. // divided into precincts... Each of the resulting precinct regions is then
  39651. // mapped into its child subbands (if any) at the next lower resolution
  39652. // level. This is accomplished by using the coordinate transformation
  39653. // (u, v) = (ceil(x/2), ceil(y/2)) where (x, y) and (u, v) are the
  39654. // coordinates of a point in the LL band and child subband, respectively.
  39655. var isZeroRes = resolution.resLevel === 0;
  39656. var precinctWidthInSubband = 1 << (dimensions.PPx + (isZeroRes ? 0 : -1));
  39657. var precinctHeightInSubband = 1 << (dimensions.PPy + (isZeroRes ? 0 : -1));
  39658. var numprecinctswide = (resolution.trx1 > resolution.trx0 ?
  39659. Math.ceil(resolution.trx1 / precinctWidth) -
  39660. Math.floor(resolution.trx0 / precinctWidth) : 0);
  39661. var numprecinctshigh = (resolution.try1 > resolution.try0 ?
  39662. Math.ceil(resolution.try1 / precinctHeight) -
  39663. Math.floor(resolution.try0 / precinctHeight) : 0);
  39664. var numprecincts = numprecinctswide * numprecinctshigh;
  39665. resolution.precinctParameters = {
  39666. precinctWidth: precinctWidth,
  39667. precinctHeight: precinctHeight,
  39668. numprecinctswide: numprecinctswide,
  39669. numprecinctshigh: numprecinctshigh,
  39670. numprecincts: numprecincts,
  39671. precinctWidthInSubband: precinctWidthInSubband,
  39672. precinctHeightInSubband: precinctHeightInSubband
  39673. };
  39674. }
  39675. function buildCodeblocks(context, subband, dimensions) {
  39676. // Section B.7 Division sub-band into code-blocks
  39677. var xcb_ = dimensions.xcb_;
  39678. var ycb_ = dimensions.ycb_;
  39679. var codeblockWidth = 1 << xcb_;
  39680. var codeblockHeight = 1 << ycb_;
  39681. var cbx0 = subband.tbx0 >> xcb_;
  39682. var cby0 = subband.tby0 >> ycb_;
  39683. var cbx1 = (subband.tbx1 + codeblockWidth - 1) >> xcb_;
  39684. var cby1 = (subband.tby1 + codeblockHeight - 1) >> ycb_;
  39685. var precinctParameters = subband.resolution.precinctParameters;
  39686. var codeblocks = [];
  39687. var precincts = [];
  39688. var i, j, codeblock, precinctNumber;
  39689. for (j = cby0; j < cby1; j++) {
  39690. for (i = cbx0; i < cbx1; i++) {
  39691. codeblock = {
  39692. cbx: i,
  39693. cby: j,
  39694. tbx0: codeblockWidth * i,
  39695. tby0: codeblockHeight * j,
  39696. tbx1: codeblockWidth * (i + 1),
  39697. tby1: codeblockHeight * (j + 1)
  39698. };
  39699. codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
  39700. codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
  39701. codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
  39702. codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
  39703. // Calculate precinct number for this codeblock, codeblock position
  39704. // should be relative to its subband, use actual dimension and position
  39705. // See comment about codeblock group width and height
  39706. var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) /
  39707. precinctParameters.precinctWidthInSubband);
  39708. var pj = Math.floor((codeblock.tby0_ - subband.tby0) /
  39709. precinctParameters.precinctHeightInSubband);
  39710. precinctNumber = pi + (pj * precinctParameters.numprecinctswide);
  39711. codeblock.precinctNumber = precinctNumber;
  39712. codeblock.subbandType = subband.type;
  39713. codeblock.Lblock = 3;
  39714. if (codeblock.tbx1_ <= codeblock.tbx0_ ||
  39715. codeblock.tby1_ <= codeblock.tby0_) {
  39716. continue;
  39717. }
  39718. codeblocks.push(codeblock);
  39719. // building precinct for the sub-band
  39720. var precinct = precincts[precinctNumber];
  39721. if (precinct !== undefined) {
  39722. if (i < precinct.cbxMin) {
  39723. precinct.cbxMin = i;
  39724. } else if (i > precinct.cbxMax) {
  39725. precinct.cbxMax = i;
  39726. }
  39727. if (j < precinct.cbyMin) {
  39728. precinct.cbxMin = j;
  39729. } else if (j > precinct.cbyMax) {
  39730. precinct.cbyMax = j;
  39731. }
  39732. } else {
  39733. precincts[precinctNumber] = precinct = {
  39734. cbxMin: i,
  39735. cbyMin: j,
  39736. cbxMax: i,
  39737. cbyMax: j
  39738. };
  39739. }
  39740. codeblock.precinct = precinct;
  39741. }
  39742. }
  39743. subband.codeblockParameters = {
  39744. codeblockWidth: xcb_,
  39745. codeblockHeight: ycb_,
  39746. numcodeblockwide: cbx1 - cbx0 + 1,
  39747. numcodeblockhigh: cby1 - cby0 + 1
  39748. };
  39749. subband.codeblocks = codeblocks;
  39750. subband.precincts = precincts;
  39751. }
  39752. function createPacket(resolution, precinctNumber, layerNumber) {
  39753. var precinctCodeblocks = [];
  39754. // Section B.10.8 Order of info in packet
  39755. var subbands = resolution.subbands;
  39756. // sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence
  39757. for (var i = 0, ii = subbands.length; i < ii; i++) {
  39758. var subband = subbands[i];
  39759. var codeblocks = subband.codeblocks;
  39760. for (var j = 0, jj = codeblocks.length; j < jj; j++) {
  39761. var codeblock = codeblocks[j];
  39762. if (codeblock.precinctNumber !== precinctNumber) {
  39763. continue;
  39764. }
  39765. precinctCodeblocks.push(codeblock);
  39766. }
  39767. }
  39768. return {
  39769. layerNumber: layerNumber,
  39770. codeblocks: precinctCodeblocks
  39771. };
  39772. }
  39773. function LayerResolutionComponentPositionIterator(context) {
  39774. var siz = context.SIZ;
  39775. var tileIndex = context.currentTile.index;
  39776. var tile = context.tiles[tileIndex];
  39777. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39778. var componentsCount = siz.Csiz;
  39779. var maxDecompositionLevelsCount = 0;
  39780. for (var q = 0; q < componentsCount; q++) {
  39781. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39782. tile.components[q].codingStyleParameters.decompositionLevelsCount);
  39783. }
  39784. var l = 0, r = 0, i = 0, k = 0;
  39785. this.nextPacket = function JpxImage_nextPacket() {
  39786. // Section B.12.1.1 Layer-resolution-component-position
  39787. for (; l < layersCount; l++) {
  39788. for (; r <= maxDecompositionLevelsCount; r++) {
  39789. for (; i < componentsCount; i++) {
  39790. var component = tile.components[i];
  39791. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39792. continue;
  39793. }
  39794. var resolution = component.resolutions[r];
  39795. var numprecincts = resolution.precinctParameters.numprecincts;
  39796. for (; k < numprecincts;) {
  39797. var packet = createPacket(resolution, k, l);
  39798. k++;
  39799. return packet;
  39800. }
  39801. k = 0;
  39802. }
  39803. i = 0;
  39804. }
  39805. r = 0;
  39806. }
  39807. throw new Error('JPX Error: Out of packets');
  39808. };
  39809. }
  39810. function ResolutionLayerComponentPositionIterator(context) {
  39811. var siz = context.SIZ;
  39812. var tileIndex = context.currentTile.index;
  39813. var tile = context.tiles[tileIndex];
  39814. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39815. var componentsCount = siz.Csiz;
  39816. var maxDecompositionLevelsCount = 0;
  39817. for (var q = 0; q < componentsCount; q++) {
  39818. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39819. tile.components[q].codingStyleParameters.decompositionLevelsCount);
  39820. }
  39821. var r = 0, l = 0, i = 0, k = 0;
  39822. this.nextPacket = function JpxImage_nextPacket() {
  39823. // Section B.12.1.2 Resolution-layer-component-position
  39824. for (; r <= maxDecompositionLevelsCount; r++) {
  39825. for (; l < layersCount; l++) {
  39826. for (; i < componentsCount; i++) {
  39827. var component = tile.components[i];
  39828. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39829. continue;
  39830. }
  39831. var resolution = component.resolutions[r];
  39832. var numprecincts = resolution.precinctParameters.numprecincts;
  39833. for (; k < numprecincts;) {
  39834. var packet = createPacket(resolution, k, l);
  39835. k++;
  39836. return packet;
  39837. }
  39838. k = 0;
  39839. }
  39840. i = 0;
  39841. }
  39842. l = 0;
  39843. }
  39844. throw new Error('JPX Error: Out of packets');
  39845. };
  39846. }
  39847. function ResolutionPositionComponentLayerIterator(context) {
  39848. var siz = context.SIZ;
  39849. var tileIndex = context.currentTile.index;
  39850. var tile = context.tiles[tileIndex];
  39851. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39852. var componentsCount = siz.Csiz;
  39853. var l, r, c, p;
  39854. var maxDecompositionLevelsCount = 0;
  39855. for (c = 0; c < componentsCount; c++) {
  39856. var component = tile.components[c];
  39857. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39858. component.codingStyleParameters.decompositionLevelsCount);
  39859. }
  39860. var maxNumPrecinctsInLevel = new Int32Array(
  39861. maxDecompositionLevelsCount + 1);
  39862. for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
  39863. var maxNumPrecincts = 0;
  39864. for (c = 0; c < componentsCount; ++c) {
  39865. var resolutions = tile.components[c].resolutions;
  39866. if (r < resolutions.length) {
  39867. maxNumPrecincts = Math.max(maxNumPrecincts,
  39868. resolutions[r].precinctParameters.numprecincts);
  39869. }
  39870. }
  39871. maxNumPrecinctsInLevel[r] = maxNumPrecincts;
  39872. }
  39873. l = 0;
  39874. r = 0;
  39875. c = 0;
  39876. p = 0;
  39877. this.nextPacket = function JpxImage_nextPacket() {
  39878. // Section B.12.1.3 Resolution-position-component-layer
  39879. for (; r <= maxDecompositionLevelsCount; r++) {
  39880. for (; p < maxNumPrecinctsInLevel[r]; p++) {
  39881. for (; c < componentsCount; c++) {
  39882. var component = tile.components[c];
  39883. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39884. continue;
  39885. }
  39886. var resolution = component.resolutions[r];
  39887. var numprecincts = resolution.precinctParameters.numprecincts;
  39888. if (p >= numprecincts) {
  39889. continue;
  39890. }
  39891. for (; l < layersCount;) {
  39892. var packet = createPacket(resolution, p, l);
  39893. l++;
  39894. return packet;
  39895. }
  39896. l = 0;
  39897. }
  39898. c = 0;
  39899. }
  39900. p = 0;
  39901. }
  39902. throw new Error('JPX Error: Out of packets');
  39903. };
  39904. }
  39905. function PositionComponentResolutionLayerIterator(context) {
  39906. var siz = context.SIZ;
  39907. var tileIndex = context.currentTile.index;
  39908. var tile = context.tiles[tileIndex];
  39909. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39910. var componentsCount = siz.Csiz;
  39911. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  39912. var precinctsIterationSizes = precinctsSizes;
  39913. var l = 0, r = 0, c = 0, px = 0, py = 0;
  39914. this.nextPacket = function JpxImage_nextPacket() {
  39915. // Section B.12.1.4 Position-component-resolution-layer
  39916. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  39917. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  39918. for (; c < componentsCount; c++) {
  39919. var component = tile.components[c];
  39920. var decompositionLevelsCount =
  39921. component.codingStyleParameters.decompositionLevelsCount;
  39922. for (; r <= decompositionLevelsCount; r++) {
  39923. var resolution = component.resolutions[r];
  39924. var sizeInImageScale =
  39925. precinctsSizes.components[c].resolutions[r];
  39926. var k = getPrecinctIndexIfExist(
  39927. px,
  39928. py,
  39929. sizeInImageScale,
  39930. precinctsIterationSizes,
  39931. resolution);
  39932. if (k === null) {
  39933. continue;
  39934. }
  39935. for (; l < layersCount;) {
  39936. var packet = createPacket(resolution, k, l);
  39937. l++;
  39938. return packet;
  39939. }
  39940. l = 0;
  39941. }
  39942. r = 0;
  39943. }
  39944. c = 0;
  39945. }
  39946. px = 0;
  39947. }
  39948. throw new Error('JPX Error: Out of packets');
  39949. };
  39950. }
  39951. function ComponentPositionResolutionLayerIterator(context) {
  39952. var siz = context.SIZ;
  39953. var tileIndex = context.currentTile.index;
  39954. var tile = context.tiles[tileIndex];
  39955. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39956. var componentsCount = siz.Csiz;
  39957. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  39958. var l = 0, r = 0, c = 0, px = 0, py = 0;
  39959. this.nextPacket = function JpxImage_nextPacket() {
  39960. // Section B.12.1.5 Component-position-resolution-layer
  39961. for (; c < componentsCount; ++c) {
  39962. var component = tile.components[c];
  39963. var precinctsIterationSizes = precinctsSizes.components[c];
  39964. var decompositionLevelsCount =
  39965. component.codingStyleParameters.decompositionLevelsCount;
  39966. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  39967. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  39968. for (; r <= decompositionLevelsCount; r++) {
  39969. var resolution = component.resolutions[r];
  39970. var sizeInImageScale = precinctsIterationSizes.resolutions[r];
  39971. var k = getPrecinctIndexIfExist(
  39972. px,
  39973. py,
  39974. sizeInImageScale,
  39975. precinctsIterationSizes,
  39976. resolution);
  39977. if (k === null) {
  39978. continue;
  39979. }
  39980. for (; l < layersCount;) {
  39981. var packet = createPacket(resolution, k, l);
  39982. l++;
  39983. return packet;
  39984. }
  39985. l = 0;
  39986. }
  39987. r = 0;
  39988. }
  39989. px = 0;
  39990. }
  39991. py = 0;
  39992. }
  39993. throw new Error('JPX Error: Out of packets');
  39994. };
  39995. }
  39996. function getPrecinctIndexIfExist(
  39997. pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
  39998. var posX = pxIndex * precinctIterationSizes.minWidth;
  39999. var posY = pyIndex * precinctIterationSizes.minHeight;
  40000. if (posX % sizeInImageScale.width !== 0 ||
  40001. posY % sizeInImageScale.height !== 0) {
  40002. return null;
  40003. }
  40004. var startPrecinctRowIndex =
  40005. (posY / sizeInImageScale.width) *
  40006. resolution.precinctParameters.numprecinctswide;
  40007. return (posX / sizeInImageScale.height) + startPrecinctRowIndex;
  40008. }
  40009. function getPrecinctSizesInImageScale(tile) {
  40010. var componentsCount = tile.components.length;
  40011. var minWidth = Number.MAX_VALUE;
  40012. var minHeight = Number.MAX_VALUE;
  40013. var maxNumWide = 0;
  40014. var maxNumHigh = 0;
  40015. var sizePerComponent = new Array(componentsCount);
  40016. for (var c = 0; c < componentsCount; c++) {
  40017. var component = tile.components[c];
  40018. var decompositionLevelsCount =
  40019. component.codingStyleParameters.decompositionLevelsCount;
  40020. var sizePerResolution = new Array(decompositionLevelsCount + 1);
  40021. var minWidthCurrentComponent = Number.MAX_VALUE;
  40022. var minHeightCurrentComponent = Number.MAX_VALUE;
  40023. var maxNumWideCurrentComponent = 0;
  40024. var maxNumHighCurrentComponent = 0;
  40025. var scale = 1;
  40026. for (var r = decompositionLevelsCount; r >= 0; --r) {
  40027. var resolution = component.resolutions[r];
  40028. var widthCurrentResolution =
  40029. scale * resolution.precinctParameters.precinctWidth;
  40030. var heightCurrentResolution =
  40031. scale * resolution.precinctParameters.precinctHeight;
  40032. minWidthCurrentComponent = Math.min(
  40033. minWidthCurrentComponent,
  40034. widthCurrentResolution);
  40035. minHeightCurrentComponent = Math.min(
  40036. minHeightCurrentComponent,
  40037. heightCurrentResolution);
  40038. maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent,
  40039. resolution.precinctParameters.numprecinctswide);
  40040. maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent,
  40041. resolution.precinctParameters.numprecinctshigh);
  40042. sizePerResolution[r] = {
  40043. width: widthCurrentResolution,
  40044. height: heightCurrentResolution
  40045. };
  40046. scale <<= 1;
  40047. }
  40048. minWidth = Math.min(minWidth, minWidthCurrentComponent);
  40049. minHeight = Math.min(minHeight, minHeightCurrentComponent);
  40050. maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
  40051. maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
  40052. sizePerComponent[c] = {
  40053. resolutions: sizePerResolution,
  40054. minWidth: minWidthCurrentComponent,
  40055. minHeight: minHeightCurrentComponent,
  40056. maxNumWide: maxNumWideCurrentComponent,
  40057. maxNumHigh: maxNumHighCurrentComponent
  40058. };
  40059. }
  40060. return {
  40061. components: sizePerComponent,
  40062. minWidth: minWidth,
  40063. minHeight: minHeight,
  40064. maxNumWide: maxNumWide,
  40065. maxNumHigh: maxNumHigh
  40066. };
  40067. }
  40068. function buildPackets(context) {
  40069. var siz = context.SIZ;
  40070. var tileIndex = context.currentTile.index;
  40071. var tile = context.tiles[tileIndex];
  40072. var componentsCount = siz.Csiz;
  40073. // Creating resolutions and sub-bands for each component
  40074. for (var c = 0; c < componentsCount; c++) {
  40075. var component = tile.components[c];
  40076. var decompositionLevelsCount =
  40077. component.codingStyleParameters.decompositionLevelsCount;
  40078. // Section B.5 Resolution levels and sub-bands
  40079. var resolutions = [];
  40080. var subbands = [];
  40081. for (var r = 0; r <= decompositionLevelsCount; r++) {
  40082. var blocksDimensions = getBlocksDimensions(context, component, r);
  40083. var resolution = {};
  40084. var scale = 1 << (decompositionLevelsCount - r);
  40085. resolution.trx0 = Math.ceil(component.tcx0 / scale);
  40086. resolution.try0 = Math.ceil(component.tcy0 / scale);
  40087. resolution.trx1 = Math.ceil(component.tcx1 / scale);
  40088. resolution.try1 = Math.ceil(component.tcy1 / scale);
  40089. resolution.resLevel = r;
  40090. buildPrecincts(context, resolution, blocksDimensions);
  40091. resolutions.push(resolution);
  40092. var subband;
  40093. if (r === 0) {
  40094. // one sub-band (LL) with last decomposition
  40095. subband = {};
  40096. subband.type = 'LL';
  40097. subband.tbx0 = Math.ceil(component.tcx0 / scale);
  40098. subband.tby0 = Math.ceil(component.tcy0 / scale);
  40099. subband.tbx1 = Math.ceil(component.tcx1 / scale);
  40100. subband.tby1 = Math.ceil(component.tcy1 / scale);
  40101. subband.resolution = resolution;
  40102. buildCodeblocks(context, subband, blocksDimensions);
  40103. subbands.push(subband);
  40104. resolution.subbands = [subband];
  40105. } else {
  40106. var bscale = 1 << (decompositionLevelsCount - r + 1);
  40107. var resolutionSubbands = [];
  40108. // three sub-bands (HL, LH and HH) with rest of decompositions
  40109. subband = {};
  40110. subband.type = 'HL';
  40111. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  40112. subband.tby0 = Math.ceil(component.tcy0 / bscale);
  40113. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  40114. subband.tby1 = Math.ceil(component.tcy1 / bscale);
  40115. subband.resolution = resolution;
  40116. buildCodeblocks(context, subband, blocksDimensions);
  40117. subbands.push(subband);
  40118. resolutionSubbands.push(subband);
  40119. subband = {};
  40120. subband.type = 'LH';
  40121. subband.tbx0 = Math.ceil(component.tcx0 / bscale);
  40122. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  40123. subband.tbx1 = Math.ceil(component.tcx1 / bscale);
  40124. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  40125. subband.resolution = resolution;
  40126. buildCodeblocks(context, subband, blocksDimensions);
  40127. subbands.push(subband);
  40128. resolutionSubbands.push(subband);
  40129. subband = {};
  40130. subband.type = 'HH';
  40131. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  40132. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  40133. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  40134. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  40135. subband.resolution = resolution;
  40136. buildCodeblocks(context, subband, blocksDimensions);
  40137. subbands.push(subband);
  40138. resolutionSubbands.push(subband);
  40139. resolution.subbands = resolutionSubbands;
  40140. }
  40141. }
  40142. component.resolutions = resolutions;
  40143. component.subbands = subbands;
  40144. }
  40145. // Generate the packets sequence
  40146. var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
  40147. switch (progressionOrder) {
  40148. case 0:
  40149. tile.packetsIterator =
  40150. new LayerResolutionComponentPositionIterator(context);
  40151. break;
  40152. case 1:
  40153. tile.packetsIterator =
  40154. new ResolutionLayerComponentPositionIterator(context);
  40155. break;
  40156. case 2:
  40157. tile.packetsIterator =
  40158. new ResolutionPositionComponentLayerIterator(context);
  40159. break;
  40160. case 3:
  40161. tile.packetsIterator =
  40162. new PositionComponentResolutionLayerIterator(context);
  40163. break;
  40164. case 4:
  40165. tile.packetsIterator =
  40166. new ComponentPositionResolutionLayerIterator(context);
  40167. break;
  40168. default:
  40169. throw new Error('JPX Error: Unsupported progression order ' +
  40170. progressionOrder);
  40171. }
  40172. }
  40173. function parseTilePackets(context, data, offset, dataLength) {
  40174. var position = 0;
  40175. var buffer, bufferSize = 0, skipNextBit = false;
  40176. function readBits(count) {
  40177. while (bufferSize < count) {
  40178. var b = data[offset + position];
  40179. position++;
  40180. if (skipNextBit) {
  40181. buffer = (buffer << 7) | b;
  40182. bufferSize += 7;
  40183. skipNextBit = false;
  40184. } else {
  40185. buffer = (buffer << 8) | b;
  40186. bufferSize += 8;
  40187. }
  40188. if (b === 0xFF) {
  40189. skipNextBit = true;
  40190. }
  40191. }
  40192. bufferSize -= count;
  40193. return (buffer >>> bufferSize) & ((1 << count) - 1);
  40194. }
  40195. function skipMarkerIfEqual(value) {
  40196. if (data[offset + position - 1] === 0xFF &&
  40197. data[offset + position] === value) {
  40198. skipBytes(1);
  40199. return true;
  40200. } else if (data[offset + position] === 0xFF &&
  40201. data[offset + position + 1] === value) {
  40202. skipBytes(2);
  40203. return true;
  40204. }
  40205. return false;
  40206. }
  40207. function skipBytes(count) {
  40208. position += count;
  40209. }
  40210. function alignToByte() {
  40211. bufferSize = 0;
  40212. if (skipNextBit) {
  40213. position++;
  40214. skipNextBit = false;
  40215. }
  40216. }
  40217. function readCodingpasses() {
  40218. if (readBits(1) === 0) {
  40219. return 1;
  40220. }
  40221. if (readBits(1) === 0) {
  40222. return 2;
  40223. }
  40224. var value = readBits(2);
  40225. if (value < 3) {
  40226. return value + 3;
  40227. }
  40228. value = readBits(5);
  40229. if (value < 31) {
  40230. return value + 6;
  40231. }
  40232. value = readBits(7);
  40233. return value + 37;
  40234. }
  40235. var tileIndex = context.currentTile.index;
  40236. var tile = context.tiles[tileIndex];
  40237. var sopMarkerUsed = context.COD.sopMarkerUsed;
  40238. var ephMarkerUsed = context.COD.ephMarkerUsed;
  40239. var packetsIterator = tile.packetsIterator;
  40240. while (position < dataLength) {
  40241. alignToByte();
  40242. if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
  40243. // Skip also marker segment length and packet sequence ID
  40244. skipBytes(4);
  40245. }
  40246. var packet = packetsIterator.nextPacket();
  40247. if (!readBits(1)) {
  40248. continue;
  40249. }
  40250. var layerNumber = packet.layerNumber;
  40251. var queue = [], codeblock;
  40252. for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
  40253. codeblock = packet.codeblocks[i];
  40254. var precinct = codeblock.precinct;
  40255. var codeblockColumn = codeblock.cbx - precinct.cbxMin;
  40256. var codeblockRow = codeblock.cby - precinct.cbyMin;
  40257. var codeblockIncluded = false;
  40258. var firstTimeInclusion = false;
  40259. var valueReady;
  40260. if (codeblock['included'] !== undefined) {
  40261. codeblockIncluded = !!readBits(1);
  40262. } else {
  40263. // reading inclusion tree
  40264. precinct = codeblock.precinct;
  40265. var inclusionTree, zeroBitPlanesTree;
  40266. if (precinct['inclusionTree'] !== undefined) {
  40267. inclusionTree = precinct.inclusionTree;
  40268. } else {
  40269. // building inclusion and zero bit-planes trees
  40270. var width = precinct.cbxMax - precinct.cbxMin + 1;
  40271. var height = precinct.cbyMax - precinct.cbyMin + 1;
  40272. inclusionTree = new InclusionTree(width, height, layerNumber);
  40273. zeroBitPlanesTree = new TagTree(width, height);
  40274. precinct.inclusionTree = inclusionTree;
  40275. precinct.zeroBitPlanesTree = zeroBitPlanesTree;
  40276. }
  40277. if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
  40278. while (true) {
  40279. if (readBits(1)) {
  40280. valueReady = !inclusionTree.nextLevel();
  40281. if (valueReady) {
  40282. codeblock.included = true;
  40283. codeblockIncluded = firstTimeInclusion = true;
  40284. break;
  40285. }
  40286. } else {
  40287. inclusionTree.incrementValue(layerNumber);
  40288. break;
  40289. }
  40290. }
  40291. }
  40292. }
  40293. if (!codeblockIncluded) {
  40294. continue;
  40295. }
  40296. if (firstTimeInclusion) {
  40297. zeroBitPlanesTree = precinct.zeroBitPlanesTree;
  40298. zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
  40299. while (true) {
  40300. if (readBits(1)) {
  40301. valueReady = !zeroBitPlanesTree.nextLevel();
  40302. if (valueReady) {
  40303. break;
  40304. }
  40305. } else {
  40306. zeroBitPlanesTree.incrementValue();
  40307. }
  40308. }
  40309. codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
  40310. }
  40311. var codingpasses = readCodingpasses();
  40312. while (readBits(1)) {
  40313. codeblock.Lblock++;
  40314. }
  40315. var codingpassesLog2 = log2(codingpasses);
  40316. // rounding down log2
  40317. var bits = ((codingpasses < (1 << codingpassesLog2)) ?
  40318. codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
  40319. var codedDataLength = readBits(bits);
  40320. queue.push({
  40321. codeblock: codeblock,
  40322. codingpasses: codingpasses,
  40323. dataLength: codedDataLength
  40324. });
  40325. }
  40326. alignToByte();
  40327. if (ephMarkerUsed) {
  40328. skipMarkerIfEqual(0x92);
  40329. }
  40330. while (queue.length > 0) {
  40331. var packetItem = queue.shift();
  40332. codeblock = packetItem.codeblock;
  40333. if (codeblock['data'] === undefined) {
  40334. codeblock.data = [];
  40335. }
  40336. codeblock.data.push({
  40337. data: data,
  40338. start: offset + position,
  40339. end: offset + position + packetItem.dataLength,
  40340. codingpasses: packetItem.codingpasses
  40341. });
  40342. position += packetItem.dataLength;
  40343. }
  40344. }
  40345. return position;
  40346. }
  40347. function copyCoefficients(coefficients, levelWidth, levelHeight, subband,
  40348. delta, mb, reversible, segmentationSymbolUsed) {
  40349. var x0 = subband.tbx0;
  40350. var y0 = subband.tby0;
  40351. var width = subband.tbx1 - subband.tbx0;
  40352. var codeblocks = subband.codeblocks;
  40353. var right = subband.type.charAt(0) === 'H' ? 1 : 0;
  40354. var bottom = subband.type.charAt(1) === 'H' ? levelWidth : 0;
  40355. for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
  40356. var codeblock = codeblocks[i];
  40357. var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
  40358. var blockHeight = codeblock.tby1_ - codeblock.tby0_;
  40359. if (blockWidth === 0 || blockHeight === 0) {
  40360. continue;
  40361. }
  40362. if (codeblock['data'] === undefined) {
  40363. continue;
  40364. }
  40365. var bitModel, currentCodingpassType;
  40366. bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType,
  40367. codeblock.zeroBitPlanes, mb);
  40368. currentCodingpassType = 2; // first bit plane starts from cleanup
  40369. // collect data
  40370. var data = codeblock.data, totalLength = 0, codingpasses = 0;
  40371. var j, jj, dataItem;
  40372. for (j = 0, jj = data.length; j < jj; j++) {
  40373. dataItem = data[j];
  40374. totalLength += dataItem.end - dataItem.start;
  40375. codingpasses += dataItem.codingpasses;
  40376. }
  40377. var encodedData = new Uint8Array(totalLength);
  40378. var position = 0;
  40379. for (j = 0, jj = data.length; j < jj; j++) {
  40380. dataItem = data[j];
  40381. var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
  40382. encodedData.set(chunk, position);
  40383. position += chunk.length;
  40384. }
  40385. // decoding the item
  40386. var decoder = new ArithmeticDecoder(encodedData, 0, totalLength);
  40387. bitModel.setDecoder(decoder);
  40388. for (j = 0; j < codingpasses; j++) {
  40389. switch (currentCodingpassType) {
  40390. case 0:
  40391. bitModel.runSignificancePropogationPass();
  40392. break;
  40393. case 1:
  40394. bitModel.runMagnitudeRefinementPass();
  40395. break;
  40396. case 2:
  40397. bitModel.runCleanupPass();
  40398. if (segmentationSymbolUsed) {
  40399. bitModel.checkSegmentationSymbol();
  40400. }
  40401. break;
  40402. }
  40403. currentCodingpassType = (currentCodingpassType + 1) % 3;
  40404. }
  40405. var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width;
  40406. var sign = bitModel.coefficentsSign;
  40407. var magnitude = bitModel.coefficentsMagnitude;
  40408. var bitsDecoded = bitModel.bitsDecoded;
  40409. var magnitudeCorrection = reversible ? 0 : 0.5;
  40410. var k, n, nb;
  40411. position = 0;
  40412. // Do the interleaving of Section F.3.3 here, so we do not need
  40413. // to copy later. LL level is not interleaved, just copied.
  40414. var interleave = (subband.type !== 'LL');
  40415. for (j = 0; j < blockHeight; j++) {
  40416. var row = (offset / width) | 0; // row in the non-interleaved subband
  40417. var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
  40418. for (k = 0; k < blockWidth; k++) {
  40419. n = magnitude[position];
  40420. if (n !== 0) {
  40421. n = (n + magnitudeCorrection) * delta;
  40422. if (sign[position] !== 0) {
  40423. n = -n;
  40424. }
  40425. nb = bitsDecoded[position];
  40426. var pos = interleave ? (levelOffset + (offset << 1)) : offset;
  40427. if (reversible && (nb >= mb)) {
  40428. coefficients[pos] = n;
  40429. } else {
  40430. coefficients[pos] = n * (1 << (mb - nb));
  40431. }
  40432. }
  40433. offset++;
  40434. position++;
  40435. }
  40436. offset += width - blockWidth;
  40437. }
  40438. }
  40439. }
  40440. function transformTile(context, tile, c) {
  40441. var component = tile.components[c];
  40442. var codingStyleParameters = component.codingStyleParameters;
  40443. var quantizationParameters = component.quantizationParameters;
  40444. var decompositionLevelsCount =
  40445. codingStyleParameters.decompositionLevelsCount;
  40446. var spqcds = quantizationParameters.SPqcds;
  40447. var scalarExpounded = quantizationParameters.scalarExpounded;
  40448. var guardBits = quantizationParameters.guardBits;
  40449. var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
  40450. var precision = context.components[c].precision;
  40451. var reversible = codingStyleParameters.reversibleTransformation;
  40452. var transform = (reversible ? new ReversibleTransform() :
  40453. new IrreversibleTransform());
  40454. var subbandCoefficients = [];
  40455. var b = 0;
  40456. for (var i = 0; i <= decompositionLevelsCount; i++) {
  40457. var resolution = component.resolutions[i];
  40458. var width = resolution.trx1 - resolution.trx0;
  40459. var height = resolution.try1 - resolution.try0;
  40460. // Allocate space for the whole sublevel.
  40461. var coefficients = new Float32Array(width * height);
  40462. for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
  40463. var mu, epsilon;
  40464. if (!scalarExpounded) {
  40465. // formula E-5
  40466. mu = spqcds[0].mu;
  40467. epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
  40468. } else {
  40469. mu = spqcds[b].mu;
  40470. epsilon = spqcds[b].epsilon;
  40471. b++;
  40472. }
  40473. var subband = resolution.subbands[j];
  40474. var gainLog2 = SubbandsGainLog2[subband.type];
  40475. // calulate quantization coefficient (Section E.1.1.1)
  40476. var delta = (reversible ? 1 :
  40477. Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048));
  40478. var mb = (guardBits + epsilon - 1);
  40479. // In the first resolution level, copyCoefficients will fill the
  40480. // whole array with coefficients. In the succeding passes,
  40481. // copyCoefficients will consecutively fill in the values that belong
  40482. // to the interleaved positions of the HL, LH, and HH coefficients.
  40483. // The LL coefficients will then be interleaved in Transform.iterate().
  40484. copyCoefficients(coefficients, width, height, subband, delta, mb,
  40485. reversible, segmentationSymbolUsed);
  40486. }
  40487. subbandCoefficients.push({
  40488. width: width,
  40489. height: height,
  40490. items: coefficients
  40491. });
  40492. }
  40493. var result = transform.calculate(subbandCoefficients,
  40494. component.tcx0, component.tcy0);
  40495. return {
  40496. left: component.tcx0,
  40497. top: component.tcy0,
  40498. width: result.width,
  40499. height: result.height,
  40500. items: result.items
  40501. };
  40502. }
  40503. function transformComponents(context) {
  40504. var siz = context.SIZ;
  40505. var components = context.components;
  40506. var componentsCount = siz.Csiz;
  40507. var resultImages = [];
  40508. for (var i = 0, ii = context.tiles.length; i < ii; i++) {
  40509. var tile = context.tiles[i];
  40510. var transformedTiles = [];
  40511. var c;
  40512. for (c = 0; c < componentsCount; c++) {
  40513. transformedTiles[c] = transformTile(context, tile, c);
  40514. }
  40515. var tile0 = transformedTiles[0];
  40516. var out = new Uint8Array(tile0.items.length * componentsCount);
  40517. var result = {
  40518. left: tile0.left,
  40519. top: tile0.top,
  40520. width: tile0.width,
  40521. height: tile0.height,
  40522. items: out
  40523. };
  40524. // Section G.2.2 Inverse multi component transform
  40525. var shift, offset, max, min, maxK;
  40526. var pos = 0, j, jj, y0, y1, y2, r, g, b, k, val;
  40527. if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
  40528. var fourComponents = componentsCount === 4;
  40529. var y0items = transformedTiles[0].items;
  40530. var y1items = transformedTiles[1].items;
  40531. var y2items = transformedTiles[2].items;
  40532. var y3items = fourComponents ? transformedTiles[3].items : null;
  40533. // HACK: The multiple component transform formulas below assume that
  40534. // all components have the same precision. With this in mind, we
  40535. // compute shift and offset only once.
  40536. shift = components[0].precision - 8;
  40537. offset = (128 << shift) + 0.5;
  40538. max = 255 * (1 << shift);
  40539. maxK = max * 0.5;
  40540. min = -maxK;
  40541. var component0 = tile.components[0];
  40542. var alpha01 = componentsCount - 3;
  40543. jj = y0items.length;
  40544. if (!component0.codingStyleParameters.reversibleTransformation) {
  40545. // inverse irreversible multiple component transform
  40546. for (j = 0; j < jj; j++, pos += alpha01) {
  40547. y0 = y0items[j] + offset;
  40548. y1 = y1items[j];
  40549. y2 = y2items[j];
  40550. r = y0 + 1.402 * y2;
  40551. g = y0 - 0.34413 * y1 - 0.71414 * y2;
  40552. b = y0 + 1.772 * y1;
  40553. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  40554. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  40555. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  40556. }
  40557. } else {
  40558. // inverse reversible multiple component transform
  40559. for (j = 0; j < jj; j++, pos += alpha01) {
  40560. y0 = y0items[j] + offset;
  40561. y1 = y1items[j];
  40562. y2 = y2items[j];
  40563. g = y0 - ((y2 + y1) >> 2);
  40564. r = g + y2;
  40565. b = g + y1;
  40566. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  40567. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  40568. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  40569. }
  40570. }
  40571. if (fourComponents) {
  40572. for (j = 0, pos = 3; j < jj; j++, pos += 4) {
  40573. k = y3items[j];
  40574. out[pos] = k <= min ? 0 : k >= maxK ? 255 : (k + offset) >> shift;
  40575. }
  40576. }
  40577. } else { // no multi-component transform
  40578. for (c = 0; c < componentsCount; c++) {
  40579. var items = transformedTiles[c].items;
  40580. shift = components[c].precision - 8;
  40581. offset = (128 << shift) + 0.5;
  40582. max = (127.5 * (1 << shift));
  40583. min = -max;
  40584. for (pos = c, j = 0, jj = items.length; j < jj; j++) {
  40585. val = items[j];
  40586. out[pos] = val <= min ? 0 :
  40587. val >= max ? 255 : (val + offset) >> shift;
  40588. pos += componentsCount;
  40589. }
  40590. }
  40591. }
  40592. resultImages.push(result);
  40593. }
  40594. return resultImages;
  40595. }
  40596. function initializeTile(context, tileIndex) {
  40597. var siz = context.SIZ;
  40598. var componentsCount = siz.Csiz;
  40599. var tile = context.tiles[tileIndex];
  40600. for (var c = 0; c < componentsCount; c++) {
  40601. var component = tile.components[c];
  40602. var qcdOrQcc = (context.currentTile.QCC[c] !== undefined ?
  40603. context.currentTile.QCC[c] : context.currentTile.QCD);
  40604. component.quantizationParameters = qcdOrQcc;
  40605. var codOrCoc = (context.currentTile.COC[c] !== undefined ?
  40606. context.currentTile.COC[c] : context.currentTile.COD);
  40607. component.codingStyleParameters = codOrCoc;
  40608. }
  40609. tile.codingStyleDefaultParameters = context.currentTile.COD;
  40610. }
  40611. // Section B.10.2 Tag trees
  40612. var TagTree = (function TagTreeClosure() {
  40613. function TagTree(width, height) {
  40614. var levelsLength = log2(Math.max(width, height)) + 1;
  40615. this.levels = [];
  40616. for (var i = 0; i < levelsLength; i++) {
  40617. var level = {
  40618. width: width,
  40619. height: height,
  40620. items: []
  40621. };
  40622. this.levels.push(level);
  40623. width = Math.ceil(width / 2);
  40624. height = Math.ceil(height / 2);
  40625. }
  40626. }
  40627. TagTree.prototype = {
  40628. reset: function TagTree_reset(i, j) {
  40629. var currentLevel = 0, value = 0, level;
  40630. while (currentLevel < this.levels.length) {
  40631. level = this.levels[currentLevel];
  40632. var index = i + j * level.width;
  40633. if (level.items[index] !== undefined) {
  40634. value = level.items[index];
  40635. break;
  40636. }
  40637. level.index = index;
  40638. i >>= 1;
  40639. j >>= 1;
  40640. currentLevel++;
  40641. }
  40642. currentLevel--;
  40643. level = this.levels[currentLevel];
  40644. level.items[level.index] = value;
  40645. this.currentLevel = currentLevel;
  40646. delete this.value;
  40647. },
  40648. incrementValue: function TagTree_incrementValue() {
  40649. var level = this.levels[this.currentLevel];
  40650. level.items[level.index]++;
  40651. },
  40652. nextLevel: function TagTree_nextLevel() {
  40653. var currentLevel = this.currentLevel;
  40654. var level = this.levels[currentLevel];
  40655. var value = level.items[level.index];
  40656. currentLevel--;
  40657. if (currentLevel < 0) {
  40658. this.value = value;
  40659. return false;
  40660. }
  40661. this.currentLevel = currentLevel;
  40662. level = this.levels[currentLevel];
  40663. level.items[level.index] = value;
  40664. return true;
  40665. }
  40666. };
  40667. return TagTree;
  40668. })();
  40669. var InclusionTree = (function InclusionTreeClosure() {
  40670. function InclusionTree(width, height, defaultValue) {
  40671. var levelsLength = log2(Math.max(width, height)) + 1;
  40672. this.levels = [];
  40673. for (var i = 0; i < levelsLength; i++) {
  40674. var items = new Uint8Array(width * height);
  40675. for (var j = 0, jj = items.length; j < jj; j++) {
  40676. items[j] = defaultValue;
  40677. }
  40678. var level = {
  40679. width: width,
  40680. height: height,
  40681. items: items
  40682. };
  40683. this.levels.push(level);
  40684. width = Math.ceil(width / 2);
  40685. height = Math.ceil(height / 2);
  40686. }
  40687. }
  40688. InclusionTree.prototype = {
  40689. reset: function InclusionTree_reset(i, j, stopValue) {
  40690. var currentLevel = 0;
  40691. while (currentLevel < this.levels.length) {
  40692. var level = this.levels[currentLevel];
  40693. var index = i + j * level.width;
  40694. level.index = index;
  40695. var value = level.items[index];
  40696. if (value === 0xFF) {
  40697. break;
  40698. }
  40699. if (value > stopValue) {
  40700. this.currentLevel = currentLevel;
  40701. // already know about this one, propagating the value to top levels
  40702. this.propagateValues();
  40703. return false;
  40704. }
  40705. i >>= 1;
  40706. j >>= 1;
  40707. currentLevel++;
  40708. }
  40709. this.currentLevel = currentLevel - 1;
  40710. return true;
  40711. },
  40712. incrementValue: function InclusionTree_incrementValue(stopValue) {
  40713. var level = this.levels[this.currentLevel];
  40714. level.items[level.index] = stopValue + 1;
  40715. this.propagateValues();
  40716. },
  40717. propagateValues: function InclusionTree_propagateValues() {
  40718. var levelIndex = this.currentLevel;
  40719. var level = this.levels[levelIndex];
  40720. var currentValue = level.items[level.index];
  40721. while (--levelIndex >= 0) {
  40722. level = this.levels[levelIndex];
  40723. level.items[level.index] = currentValue;
  40724. }
  40725. },
  40726. nextLevel: function InclusionTree_nextLevel() {
  40727. var currentLevel = this.currentLevel;
  40728. var level = this.levels[currentLevel];
  40729. var value = level.items[level.index];
  40730. level.items[level.index] = 0xFF;
  40731. currentLevel--;
  40732. if (currentLevel < 0) {
  40733. return false;
  40734. }
  40735. this.currentLevel = currentLevel;
  40736. level = this.levels[currentLevel];
  40737. level.items[level.index] = value;
  40738. return true;
  40739. }
  40740. };
  40741. return InclusionTree;
  40742. })();
  40743. // Section D. Coefficient bit modeling
  40744. var BitModel = (function BitModelClosure() {
  40745. var UNIFORM_CONTEXT = 17;
  40746. var RUNLENGTH_CONTEXT = 18;
  40747. // Table D-1
  40748. // The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4),
  40749. // vv - sum of Vi (0..2), and hh - sum of Hi (0..2)
  40750. var LLAndLHContextsLabel = new Uint8Array([
  40751. 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,
  40752. 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,
  40753. 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
  40754. ]);
  40755. var HLContextLabel = new Uint8Array([
  40756. 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,
  40757. 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,
  40758. 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
  40759. ]);
  40760. var HHContextLabel = new Uint8Array([
  40761. 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,
  40762. 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,
  40763. 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
  40764. ]);
  40765. function BitModel(width, height, subband, zeroBitPlanes, mb) {
  40766. this.width = width;
  40767. this.height = height;
  40768. this.contextLabelTable = (subband === 'HH' ? HHContextLabel :
  40769. (subband === 'HL' ? HLContextLabel : LLAndLHContextsLabel));
  40770. var coefficientCount = width * height;
  40771. // coefficients outside the encoding region treated as insignificant
  40772. // add border state cells for significanceState
  40773. this.neighborsSignificance = new Uint8Array(coefficientCount);
  40774. this.coefficentsSign = new Uint8Array(coefficientCount);
  40775. this.coefficentsMagnitude = mb > 14 ? new Uint32Array(coefficientCount) :
  40776. mb > 6 ? new Uint16Array(coefficientCount) :
  40777. new Uint8Array(coefficientCount);
  40778. this.processingFlags = new Uint8Array(coefficientCount);
  40779. var bitsDecoded = new Uint8Array(coefficientCount);
  40780. if (zeroBitPlanes !== 0) {
  40781. for (var i = 0; i < coefficientCount; i++) {
  40782. bitsDecoded[i] = zeroBitPlanes;
  40783. }
  40784. }
  40785. this.bitsDecoded = bitsDecoded;
  40786. this.reset();
  40787. }
  40788. BitModel.prototype = {
  40789. setDecoder: function BitModel_setDecoder(decoder) {
  40790. this.decoder = decoder;
  40791. },
  40792. reset: function BitModel_reset() {
  40793. // We have 17 contexts that are accessed via context labels,
  40794. // plus the uniform and runlength context.
  40795. this.contexts = new Int8Array(19);
  40796. // Contexts are packed into 1 byte:
  40797. // highest 7 bits carry the index, lowest bit carries mps
  40798. this.contexts[0] = (4 << 1) | 0;
  40799. this.contexts[UNIFORM_CONTEXT] = (46 << 1) | 0;
  40800. this.contexts[RUNLENGTH_CONTEXT] = (3 << 1) | 0;
  40801. },
  40802. setNeighborsSignificance:
  40803. function BitModel_setNeighborsSignificance(row, column, index) {
  40804. var neighborsSignificance = this.neighborsSignificance;
  40805. var width = this.width, height = this.height;
  40806. var left = (column > 0);
  40807. var right = (column + 1 < width);
  40808. var i;
  40809. if (row > 0) {
  40810. i = index - width;
  40811. if (left) {
  40812. neighborsSignificance[i - 1] += 0x10;
  40813. }
  40814. if (right) {
  40815. neighborsSignificance[i + 1] += 0x10;
  40816. }
  40817. neighborsSignificance[i] += 0x04;
  40818. }
  40819. if (row + 1 < height) {
  40820. i = index + width;
  40821. if (left) {
  40822. neighborsSignificance[i - 1] += 0x10;
  40823. }
  40824. if (right) {
  40825. neighborsSignificance[i + 1] += 0x10;
  40826. }
  40827. neighborsSignificance[i] += 0x04;
  40828. }
  40829. if (left) {
  40830. neighborsSignificance[index - 1] += 0x01;
  40831. }
  40832. if (right) {
  40833. neighborsSignificance[index + 1] += 0x01;
  40834. }
  40835. neighborsSignificance[index] |= 0x80;
  40836. },
  40837. runSignificancePropogationPass:
  40838. function BitModel_runSignificancePropogationPass() {
  40839. var decoder = this.decoder;
  40840. var width = this.width, height = this.height;
  40841. var coefficentsMagnitude = this.coefficentsMagnitude;
  40842. var coefficentsSign = this.coefficentsSign;
  40843. var neighborsSignificance = this.neighborsSignificance;
  40844. var processingFlags = this.processingFlags;
  40845. var contexts = this.contexts;
  40846. var labels = this.contextLabelTable;
  40847. var bitsDecoded = this.bitsDecoded;
  40848. var processedInverseMask = ~1;
  40849. var processedMask = 1;
  40850. var firstMagnitudeBitMask = 2;
  40851. for (var i0 = 0; i0 < height; i0 += 4) {
  40852. for (var j = 0; j < width; j++) {
  40853. var index = i0 * width + j;
  40854. for (var i1 = 0; i1 < 4; i1++, index += width) {
  40855. var i = i0 + i1;
  40856. if (i >= height) {
  40857. break;
  40858. }
  40859. // clear processed flag first
  40860. processingFlags[index] &= processedInverseMask;
  40861. if (coefficentsMagnitude[index] ||
  40862. !neighborsSignificance[index]) {
  40863. continue;
  40864. }
  40865. var contextLabel = labels[neighborsSignificance[index]];
  40866. var decision = decoder.readBit(contexts, contextLabel);
  40867. if (decision) {
  40868. var sign = this.decodeSignBit(i, j, index);
  40869. coefficentsSign[index] = sign;
  40870. coefficentsMagnitude[index] = 1;
  40871. this.setNeighborsSignificance(i, j, index);
  40872. processingFlags[index] |= firstMagnitudeBitMask;
  40873. }
  40874. bitsDecoded[index]++;
  40875. processingFlags[index] |= processedMask;
  40876. }
  40877. }
  40878. }
  40879. },
  40880. decodeSignBit: function BitModel_decodeSignBit(row, column, index) {
  40881. var width = this.width, height = this.height;
  40882. var coefficentsMagnitude = this.coefficentsMagnitude;
  40883. var coefficentsSign = this.coefficentsSign;
  40884. var contribution, sign0, sign1, significance1;
  40885. var contextLabel, decoded;
  40886. // calculate horizontal contribution
  40887. significance1 = (column > 0 && coefficentsMagnitude[index - 1] !== 0);
  40888. if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
  40889. sign1 = coefficentsSign[index + 1];
  40890. if (significance1) {
  40891. sign0 = coefficentsSign[index - 1];
  40892. contribution = 1 - sign1 - sign0;
  40893. } else {
  40894. contribution = 1 - sign1 - sign1;
  40895. }
  40896. } else if (significance1) {
  40897. sign0 = coefficentsSign[index - 1];
  40898. contribution = 1 - sign0 - sign0;
  40899. } else {
  40900. contribution = 0;
  40901. }
  40902. var horizontalContribution = 3 * contribution;
  40903. // calculate vertical contribution and combine with the horizontal
  40904. significance1 = (row > 0 && coefficentsMagnitude[index - width] !== 0);
  40905. if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
  40906. sign1 = coefficentsSign[index + width];
  40907. if (significance1) {
  40908. sign0 = coefficentsSign[index - width];
  40909. contribution = 1 - sign1 - sign0 + horizontalContribution;
  40910. } else {
  40911. contribution = 1 - sign1 - sign1 + horizontalContribution;
  40912. }
  40913. } else if (significance1) {
  40914. sign0 = coefficentsSign[index - width];
  40915. contribution = 1 - sign0 - sign0 + horizontalContribution;
  40916. } else {
  40917. contribution = horizontalContribution;
  40918. }
  40919. if (contribution >= 0) {
  40920. contextLabel = 9 + contribution;
  40921. decoded = this.decoder.readBit(this.contexts, contextLabel);
  40922. } else {
  40923. contextLabel = 9 - contribution;
  40924. decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
  40925. }
  40926. return decoded;
  40927. },
  40928. runMagnitudeRefinementPass:
  40929. function BitModel_runMagnitudeRefinementPass() {
  40930. var decoder = this.decoder;
  40931. var width = this.width, height = this.height;
  40932. var coefficentsMagnitude = this.coefficentsMagnitude;
  40933. var neighborsSignificance = this.neighborsSignificance;
  40934. var contexts = this.contexts;
  40935. var bitsDecoded = this.bitsDecoded;
  40936. var processingFlags = this.processingFlags;
  40937. var processedMask = 1;
  40938. var firstMagnitudeBitMask = 2;
  40939. var length = width * height;
  40940. var width4 = width * 4;
  40941. for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {
  40942. indexNext = Math.min(length, index0 + width4);
  40943. for (var j = 0; j < width; j++) {
  40944. for (var index = index0 + j; index < indexNext; index += width) {
  40945. // significant but not those that have just become
  40946. if (!coefficentsMagnitude[index] ||
  40947. (processingFlags[index] & processedMask) !== 0) {
  40948. continue;
  40949. }
  40950. var contextLabel = 16;
  40951. if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
  40952. processingFlags[index] ^= firstMagnitudeBitMask;
  40953. // first refinement
  40954. var significance = neighborsSignificance[index] & 127;
  40955. contextLabel = significance === 0 ? 15 : 14;
  40956. }
  40957. var bit = decoder.readBit(contexts, contextLabel);
  40958. coefficentsMagnitude[index] =
  40959. (coefficentsMagnitude[index] << 1) | bit;
  40960. bitsDecoded[index]++;
  40961. processingFlags[index] |= processedMask;
  40962. }
  40963. }
  40964. }
  40965. },
  40966. runCleanupPass: function BitModel_runCleanupPass() {
  40967. var decoder = this.decoder;
  40968. var width = this.width, height = this.height;
  40969. var neighborsSignificance = this.neighborsSignificance;
  40970. var coefficentsMagnitude = this.coefficentsMagnitude;
  40971. var coefficentsSign = this.coefficentsSign;
  40972. var contexts = this.contexts;
  40973. var labels = this.contextLabelTable;
  40974. var bitsDecoded = this.bitsDecoded;
  40975. var processingFlags = this.processingFlags;
  40976. var processedMask = 1;
  40977. var firstMagnitudeBitMask = 2;
  40978. var oneRowDown = width;
  40979. var twoRowsDown = width * 2;
  40980. var threeRowsDown = width * 3;
  40981. var iNext;
  40982. for (var i0 = 0; i0 < height; i0 = iNext) {
  40983. iNext = Math.min(i0 + 4, height);
  40984. var indexBase = i0 * width;
  40985. var checkAllEmpty = i0 + 3 < height;
  40986. for (var j = 0; j < width; j++) {
  40987. var index0 = indexBase + j;
  40988. // using the property: labels[neighborsSignificance[index]] === 0
  40989. // when neighborsSignificance[index] === 0
  40990. var allEmpty = (checkAllEmpty &&
  40991. processingFlags[index0] === 0 &&
  40992. processingFlags[index0 + oneRowDown] === 0 &&
  40993. processingFlags[index0 + twoRowsDown] === 0 &&
  40994. processingFlags[index0 + threeRowsDown] === 0 &&
  40995. neighborsSignificance[index0] === 0 &&
  40996. neighborsSignificance[index0 + oneRowDown] === 0 &&
  40997. neighborsSignificance[index0 + twoRowsDown] === 0 &&
  40998. neighborsSignificance[index0 + threeRowsDown] === 0);
  40999. var i1 = 0, index = index0;
  41000. var i = i0, sign;
  41001. if (allEmpty) {
  41002. var hasSignificantCoefficent =
  41003. decoder.readBit(contexts, RUNLENGTH_CONTEXT);
  41004. if (!hasSignificantCoefficent) {
  41005. bitsDecoded[index0]++;
  41006. bitsDecoded[index0 + oneRowDown]++;
  41007. bitsDecoded[index0 + twoRowsDown]++;
  41008. bitsDecoded[index0 + threeRowsDown]++;
  41009. continue; // next column
  41010. }
  41011. i1 = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
  41012. decoder.readBit(contexts, UNIFORM_CONTEXT);
  41013. if (i1 !== 0) {
  41014. i = i0 + i1;
  41015. index += i1 * width;
  41016. }
  41017. sign = this.decodeSignBit(i, j, index);
  41018. coefficentsSign[index] = sign;
  41019. coefficentsMagnitude[index] = 1;
  41020. this.setNeighborsSignificance(i, j, index);
  41021. processingFlags[index] |= firstMagnitudeBitMask;
  41022. index = index0;
  41023. for (var i2 = i0; i2 <= i; i2++, index += width) {
  41024. bitsDecoded[index]++;
  41025. }
  41026. i1++;
  41027. }
  41028. for (i = i0 + i1; i < iNext; i++, index += width) {
  41029. if (coefficentsMagnitude[index] ||
  41030. (processingFlags[index] & processedMask) !== 0) {
  41031. continue;
  41032. }
  41033. var contextLabel = labels[neighborsSignificance[index]];
  41034. var decision = decoder.readBit(contexts, contextLabel);
  41035. if (decision === 1) {
  41036. sign = this.decodeSignBit(i, j, index);
  41037. coefficentsSign[index] = sign;
  41038. coefficentsMagnitude[index] = 1;
  41039. this.setNeighborsSignificance(i, j, index);
  41040. processingFlags[index] |= firstMagnitudeBitMask;
  41041. }
  41042. bitsDecoded[index]++;
  41043. }
  41044. }
  41045. }
  41046. },
  41047. checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {
  41048. var decoder = this.decoder;
  41049. var contexts = this.contexts;
  41050. var symbol = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 3) |
  41051. (decoder.readBit(contexts, UNIFORM_CONTEXT) << 2) |
  41052. (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
  41053. decoder.readBit(contexts, UNIFORM_CONTEXT);
  41054. if (symbol !== 0xA) {
  41055. throw new Error('JPX Error: Invalid segmentation symbol');
  41056. }
  41057. }
  41058. };
  41059. return BitModel;
  41060. })();
  41061. // Section F, Discrete wavelet transformation
  41062. var Transform = (function TransformClosure() {
  41063. function Transform() {}
  41064. Transform.prototype.calculate =
  41065. function transformCalculate(subbands, u0, v0) {
  41066. var ll = subbands[0];
  41067. for (var i = 1, ii = subbands.length; i < ii; i++) {
  41068. ll = this.iterate(ll, subbands[i], u0, v0);
  41069. }
  41070. return ll;
  41071. };
  41072. Transform.prototype.extend = function extend(buffer, offset, size) {
  41073. // Section F.3.7 extending... using max extension of 4
  41074. var i1 = offset - 1, j1 = offset + 1;
  41075. var i2 = offset + size - 2, j2 = offset + size;
  41076. buffer[i1--] = buffer[j1++];
  41077. buffer[j2++] = buffer[i2--];
  41078. buffer[i1--] = buffer[j1++];
  41079. buffer[j2++] = buffer[i2--];
  41080. buffer[i1--] = buffer[j1++];
  41081. buffer[j2++] = buffer[i2--];
  41082. buffer[i1] = buffer[j1];
  41083. buffer[j2] = buffer[i2];
  41084. };
  41085. Transform.prototype.iterate = function Transform_iterate(ll, hl_lh_hh,
  41086. u0, v0) {
  41087. var llWidth = ll.width, llHeight = ll.height, llItems = ll.items;
  41088. var width = hl_lh_hh.width;
  41089. var height = hl_lh_hh.height;
  41090. var items = hl_lh_hh.items;
  41091. var i, j, k, l, u, v;
  41092. // Interleave LL according to Section F.3.3
  41093. for (k = 0, i = 0; i < llHeight; i++) {
  41094. l = i * 2 * width;
  41095. for (j = 0; j < llWidth; j++, k++, l += 2) {
  41096. items[l] = llItems[k];
  41097. }
  41098. }
  41099. // The LL band is not needed anymore.
  41100. llItems = ll.items = null;
  41101. var bufferPadding = 4;
  41102. var rowBuffer = new Float32Array(width + 2 * bufferPadding);
  41103. // Section F.3.4 HOR_SR
  41104. if (width === 1) {
  41105. // if width = 1, when u0 even keep items as is, when odd divide by 2
  41106. if ((u0 & 1) !== 0) {
  41107. for (v = 0, k = 0; v < height; v++, k += width) {
  41108. items[k] *= 0.5;
  41109. }
  41110. }
  41111. } else {
  41112. for (v = 0, k = 0; v < height; v++, k += width) {
  41113. rowBuffer.set(items.subarray(k, k + width), bufferPadding);
  41114. this.extend(rowBuffer, bufferPadding, width);
  41115. this.filter(rowBuffer, bufferPadding, width);
  41116. items.set(
  41117. rowBuffer.subarray(bufferPadding, bufferPadding + width),
  41118. k);
  41119. }
  41120. }
  41121. // Accesses to the items array can take long, because it may not fit into
  41122. // CPU cache and has to be fetched from main memory. Since subsequent
  41123. // accesses to the items array are not local when reading columns, we
  41124. // have a cache miss every time. To reduce cache misses, get up to
  41125. // 'numBuffers' items at a time and store them into the individual
  41126. // buffers. The colBuffers should be small enough to fit into CPU cache.
  41127. var numBuffers = 16;
  41128. var colBuffers = [];
  41129. for (i = 0; i < numBuffers; i++) {
  41130. colBuffers.push(new Float32Array(height + 2 * bufferPadding));
  41131. }
  41132. var b, currentBuffer = 0;
  41133. ll = bufferPadding + height;
  41134. // Section F.3.5 VER_SR
  41135. if (height === 1) {
  41136. // if height = 1, when v0 even keep items as is, when odd divide by 2
  41137. if ((v0 & 1) !== 0) {
  41138. for (u = 0; u < width; u++) {
  41139. items[u] *= 0.5;
  41140. }
  41141. }
  41142. } else {
  41143. for (u = 0; u < width; u++) {
  41144. // if we ran out of buffers, copy several image columns at once
  41145. if (currentBuffer === 0) {
  41146. numBuffers = Math.min(width - u, numBuffers);
  41147. for (k = u, l = bufferPadding; l < ll; k += width, l++) {
  41148. for (b = 0; b < numBuffers; b++) {
  41149. colBuffers[b][l] = items[k + b];
  41150. }
  41151. }
  41152. currentBuffer = numBuffers;
  41153. }
  41154. currentBuffer--;
  41155. var buffer = colBuffers[currentBuffer];
  41156. this.extend(buffer, bufferPadding, height);
  41157. this.filter(buffer, bufferPadding, height);
  41158. // If this is last buffer in this group of buffers, flush all buffers.
  41159. if (currentBuffer === 0) {
  41160. k = u - numBuffers + 1;
  41161. for (l = bufferPadding; l < ll; k += width, l++) {
  41162. for (b = 0; b < numBuffers; b++) {
  41163. items[k + b] = colBuffers[b][l];
  41164. }
  41165. }
  41166. }
  41167. }
  41168. }
  41169. return {
  41170. width: width,
  41171. height: height,
  41172. items: items
  41173. };
  41174. };
  41175. return Transform;
  41176. })();
  41177. // Section 3.8.2 Irreversible 9-7 filter
  41178. var IrreversibleTransform = (function IrreversibleTransformClosure() {
  41179. function IrreversibleTransform() {
  41180. Transform.call(this);
  41181. }
  41182. IrreversibleTransform.prototype = Object.create(Transform.prototype);
  41183. IrreversibleTransform.prototype.filter =
  41184. function irreversibleTransformFilter(x, offset, length) {
  41185. var len = length >> 1;
  41186. offset = offset | 0;
  41187. var j, n, current, next;
  41188. var alpha = -1.586134342059924;
  41189. var beta = -0.052980118572961;
  41190. var gamma = 0.882911075530934;
  41191. var delta = 0.443506852043971;
  41192. var K = 1.230174104914001;
  41193. var K_ = 1 / K;
  41194. // step 1 is combined with step 3
  41195. // step 2
  41196. j = offset - 3;
  41197. for (n = len + 4; n--; j += 2) {
  41198. x[j] *= K_;
  41199. }
  41200. // step 1 & 3
  41201. j = offset - 2;
  41202. current = delta * x[j -1];
  41203. for (n = len + 3; n--; j += 2) {
  41204. next = delta * x[j + 1];
  41205. x[j] = K * x[j] - current - next;
  41206. if (n--) {
  41207. j += 2;
  41208. current = delta * x[j + 1];
  41209. x[j] = K * x[j] - current - next;
  41210. } else {
  41211. break;
  41212. }
  41213. }
  41214. // step 4
  41215. j = offset - 1;
  41216. current = gamma * x[j - 1];
  41217. for (n = len + 2; n--; j += 2) {
  41218. next = gamma * x[j + 1];
  41219. x[j] -= current + next;
  41220. if (n--) {
  41221. j += 2;
  41222. current = gamma * x[j + 1];
  41223. x[j] -= current + next;
  41224. } else {
  41225. break;
  41226. }
  41227. }
  41228. // step 5
  41229. j = offset;
  41230. current = beta * x[j - 1];
  41231. for (n = len + 1; n--; j += 2) {
  41232. next = beta * x[j + 1];
  41233. x[j] -= current + next;
  41234. if (n--) {
  41235. j += 2;
  41236. current = beta * x[j + 1];
  41237. x[j] -= current + next;
  41238. } else {
  41239. break;
  41240. }
  41241. }
  41242. // step 6
  41243. if (len !== 0) {
  41244. j = offset + 1;
  41245. current = alpha * x[j - 1];
  41246. for (n = len; n--; j += 2) {
  41247. next = alpha * x[j + 1];
  41248. x[j] -= current + next;
  41249. if (n--) {
  41250. j += 2;
  41251. current = alpha * x[j + 1];
  41252. x[j] -= current + next;
  41253. } else {
  41254. break;
  41255. }
  41256. }
  41257. }
  41258. };
  41259. return IrreversibleTransform;
  41260. })();
  41261. // Section 3.8.1 Reversible 5-3 filter
  41262. var ReversibleTransform = (function ReversibleTransformClosure() {
  41263. function ReversibleTransform() {
  41264. Transform.call(this);
  41265. }
  41266. ReversibleTransform.prototype = Object.create(Transform.prototype);
  41267. ReversibleTransform.prototype.filter =
  41268. function reversibleTransformFilter(x, offset, length) {
  41269. var len = length >> 1;
  41270. offset = offset | 0;
  41271. var j, n;
  41272. for (j = offset, n = len + 1; n--; j += 2) {
  41273. x[j] -= (x[j - 1] + x[j + 1] + 2) >> 2;
  41274. }
  41275. for (j = offset + 1, n = len; n--; j += 2) {
  41276. x[j] += (x[j - 1] + x[j + 1]) >> 1;
  41277. }
  41278. };
  41279. return ReversibleTransform;
  41280. })();
  41281. return JpxImage;
  41282. })();
  41283. var Jbig2Image = (function Jbig2ImageClosure() {
  41284. // Utility data structures
  41285. function ContextCache() {}
  41286. ContextCache.prototype = {
  41287. getContexts: function(id) {
  41288. if (id in this) {
  41289. return this[id];
  41290. }
  41291. return (this[id] = new Int8Array(1 << 16));
  41292. }
  41293. };
  41294. function DecodingContext(data, start, end) {
  41295. this.data = data;
  41296. this.start = start;
  41297. this.end = end;
  41298. }
  41299. DecodingContext.prototype = {
  41300. get decoder() {
  41301. var decoder = new ArithmeticDecoder(this.data, this.start, this.end);
  41302. return shadow(this, 'decoder', decoder);
  41303. },
  41304. get contextCache() {
  41305. var cache = new ContextCache();
  41306. return shadow(this, 'contextCache', cache);
  41307. }
  41308. };
  41309. // Annex A. Arithmetic Integer Decoding Procedure
  41310. // A.2 Procedure for decoding values
  41311. function decodeInteger(contextCache, procedure, decoder) {
  41312. var contexts = contextCache.getContexts(procedure);
  41313. var prev = 1;
  41314. function readBits(length) {
  41315. var v = 0;
  41316. for (var i = 0; i < length; i++) {
  41317. var bit = decoder.readBit(contexts, prev);
  41318. prev = (prev < 256 ? (prev << 1) | bit :
  41319. (((prev << 1) | bit) & 511) | 256);
  41320. v = (v << 1) | bit;
  41321. }
  41322. return v >>> 0;
  41323. }
  41324. var sign = readBits(1);
  41325. var value = readBits(1) ?
  41326. (readBits(1) ?
  41327. (readBits(1) ?
  41328. (readBits(1) ?
  41329. (readBits(1) ?
  41330. (readBits(32) + 4436) :
  41331. readBits(12) + 340) :
  41332. readBits(8) + 84) :
  41333. readBits(6) + 20) :
  41334. readBits(4) + 4) :
  41335. readBits(2);
  41336. return (sign === 0 ? value : (value > 0 ? -value : null));
  41337. }
  41338. // A.3 The IAID decoding procedure
  41339. function decodeIAID(contextCache, decoder, codeLength) {
  41340. var contexts = contextCache.getContexts('IAID');
  41341. var prev = 1;
  41342. for (var i = 0; i < codeLength; i++) {
  41343. var bit = decoder.readBit(contexts, prev);
  41344. prev = (prev << 1) | bit;
  41345. }
  41346. if (codeLength < 31) {
  41347. return prev & ((1 << codeLength) - 1);
  41348. }
  41349. return prev & 0x7FFFFFFF;
  41350. }
  41351. // 7.3 Segment types
  41352. var SegmentTypes = [
  41353. 'SymbolDictionary', null, null, null, 'IntermediateTextRegion', null,
  41354. 'ImmediateTextRegion', 'ImmediateLosslessTextRegion', null, null, null,
  41355. null, null, null, null, null, 'patternDictionary', null, null, null,
  41356. 'IntermediateHalftoneRegion', null, 'ImmediateHalftoneRegion',
  41357. 'ImmediateLosslessHalftoneRegion', null, null, null, null, null, null, null,
  41358. null, null, null, null, null, 'IntermediateGenericRegion', null,
  41359. 'ImmediateGenericRegion', 'ImmediateLosslessGenericRegion',
  41360. 'IntermediateGenericRefinementRegion', null,
  41361. 'ImmediateGenericRefinementRegion',
  41362. 'ImmediateLosslessGenericRefinementRegion', null, null, null, null,
  41363. 'PageInformation', 'EndOfPage', 'EndOfStripe', 'EndOfFile', 'Profiles',
  41364. 'Tables', null, null, null, null, null, null, null, null,
  41365. 'Extension'
  41366. ];
  41367. var CodingTemplates = [
  41368. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: -2, y: -1},
  41369. {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: 2, y: -1},
  41370. {x: -4, y: 0}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}],
  41371. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: 2, y: -2},
  41372. {x: -2, y: -1}, {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1},
  41373. {x: 2, y: -1}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}],
  41374. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: -2, y: -1},
  41375. {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: -2, y: 0},
  41376. {x: -1, y: 0}],
  41377. [{x: -3, y: -1}, {x: -2, y: -1}, {x: -1, y: -1}, {x: 0, y: -1},
  41378. {x: 1, y: -1}, {x: -4, y: 0}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}]
  41379. ];
  41380. var RefinementTemplates = [
  41381. {
  41382. coding: [{x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}],
  41383. reference: [{x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}, {x: 0, y: 0},
  41384. {x: 1, y: 0}, {x: -1, y: 1}, {x: 0, y: 1}, {x: 1, y: 1}]
  41385. },
  41386. {
  41387. coding: [{x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}],
  41388. reference: [{x: 0, y: -1}, {x: -1, y: 0}, {x: 0, y: 0}, {x: 1, y: 0},
  41389. {x: 0, y: 1}, {x: 1, y: 1}]
  41390. }
  41391. ];
  41392. // See 6.2.5.7 Decoding the bitmap.
  41393. var ReusedContexts = [
  41394. 0x9B25, // 10011 0110010 0101
  41395. 0x0795, // 0011 110010 101
  41396. 0x00E5, // 001 11001 01
  41397. 0x0195 // 011001 0101
  41398. ];
  41399. var RefinementReusedContexts = [
  41400. 0x0020, // '000' + '0' (coding) + '00010000' + '0' (reference)
  41401. 0x0008 // '0000' + '001000'
  41402. ];
  41403. function decodeBitmapTemplate0(width, height, decodingContext) {
  41404. var decoder = decodingContext.decoder;
  41405. var contexts = decodingContext.contextCache.getContexts('GB');
  41406. var contextLabel, i, j, pixel, row, row1, row2, bitmap = [];
  41407. // ...ooooo....
  41408. // ..ooooooo... Context template for current pixel (X)
  41409. // .ooooX...... (concatenate values of 'o'-pixels to get contextLabel)
  41410. var OLD_PIXEL_MASK = 0x7BF7; // 01111 0111111 0111
  41411. for (i = 0; i < height; i++) {
  41412. row = bitmap[i] = new Uint8Array(width);
  41413. row1 = (i < 1) ? row : bitmap[i - 1];
  41414. row2 = (i < 2) ? row : bitmap[i - 2];
  41415. // At the beginning of each row:
  41416. // Fill contextLabel with pixels that are above/right of (X)
  41417. contextLabel = (row2[0] << 13) | (row2[1] << 12) | (row2[2] << 11) |
  41418. (row1[0] << 7) | (row1[1] << 6) | (row1[2] << 5) |
  41419. (row1[3] << 4);
  41420. for (j = 0; j < width; j++) {
  41421. row[j] = pixel = decoder.readBit(contexts, contextLabel);
  41422. // At each pixel: Clear contextLabel pixels that are shifted
  41423. // out of the context, then add new ones.
  41424. contextLabel = ((contextLabel & OLD_PIXEL_MASK) << 1) |
  41425. (j + 3 < width ? row2[j + 3] << 11 : 0) |
  41426. (j + 4 < width ? row1[j + 4] << 4 : 0) | pixel;
  41427. }
  41428. }
  41429. return bitmap;
  41430. }
  41431. // 6.2 Generic Region Decoding Procedure
  41432. function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at,
  41433. decodingContext) {
  41434. if (mmr) {
  41435. error('JBIG2 error: MMR encoding is not supported');
  41436. }
  41437. // Use optimized version for the most common case
  41438. if (templateIndex === 0 && !skip && !prediction && at.length === 4 &&
  41439. at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 &&
  41440. at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) {
  41441. return decodeBitmapTemplate0(width, height, decodingContext);
  41442. }
  41443. var useskip = !!skip;
  41444. var template = CodingTemplates[templateIndex].concat(at);
  41445. // Sorting is non-standard, and it is not required. But sorting increases
  41446. // the number of template bits that can be reused from the previous
  41447. // contextLabel in the main loop.
  41448. template.sort(function (a, b) {
  41449. return (a.y - b.y) || (a.x - b.x);
  41450. });
  41451. var templateLength = template.length;
  41452. var templateX = new Int8Array(templateLength);
  41453. var templateY = new Int8Array(templateLength);
  41454. var changingTemplateEntries = [];
  41455. var reuseMask = 0, minX = 0, maxX = 0, minY = 0;
  41456. var c, k;
  41457. for (k = 0; k < templateLength; k++) {
  41458. templateX[k] = template[k].x;
  41459. templateY[k] = template[k].y;
  41460. minX = Math.min(minX, template[k].x);
  41461. maxX = Math.max(maxX, template[k].x);
  41462. minY = Math.min(minY, template[k].y);
  41463. // Check if the template pixel appears in two consecutive context labels,
  41464. // so it can be reused. Otherwise, we add it to the list of changing
  41465. // template entries.
  41466. if (k < templateLength - 1 &&
  41467. template[k].y === template[k + 1].y &&
  41468. template[k].x === template[k + 1].x - 1) {
  41469. reuseMask |= 1 << (templateLength - 1 - k);
  41470. } else {
  41471. changingTemplateEntries.push(k);
  41472. }
  41473. }
  41474. var changingEntriesLength = changingTemplateEntries.length;
  41475. var changingTemplateX = new Int8Array(changingEntriesLength);
  41476. var changingTemplateY = new Int8Array(changingEntriesLength);
  41477. var changingTemplateBit = new Uint16Array(changingEntriesLength);
  41478. for (c = 0; c < changingEntriesLength; c++) {
  41479. k = changingTemplateEntries[c];
  41480. changingTemplateX[c] = template[k].x;
  41481. changingTemplateY[c] = template[k].y;
  41482. changingTemplateBit[c] = 1 << (templateLength - 1 - k);
  41483. }
  41484. // Get the safe bounding box edges from the width, height, minX, maxX, minY
  41485. var sbb_left = -minX;
  41486. var sbb_top = -minY;
  41487. var sbb_right = width - maxX;
  41488. var pseudoPixelContext = ReusedContexts[templateIndex];
  41489. var row = new Uint8Array(width);
  41490. var bitmap = [];
  41491. var decoder = decodingContext.decoder;
  41492. var contexts = decodingContext.contextCache.getContexts('GB');
  41493. var ltp = 0, j, i0, j0, contextLabel = 0, bit, shift;
  41494. for (var i = 0; i < height; i++) {
  41495. if (prediction) {
  41496. var sltp = decoder.readBit(contexts, pseudoPixelContext);
  41497. ltp ^= sltp;
  41498. if (ltp) {
  41499. bitmap.push(row); // duplicate previous row
  41500. continue;
  41501. }
  41502. }
  41503. row = new Uint8Array(row);
  41504. bitmap.push(row);
  41505. for (j = 0; j < width; j++) {
  41506. if (useskip && skip[i][j]) {
  41507. row[j] = 0;
  41508. continue;
  41509. }
  41510. // Are we in the middle of a scanline, so we can reuse contextLabel
  41511. // bits?
  41512. if (j >= sbb_left && j < sbb_right && i >= sbb_top) {
  41513. // If yes, we can just shift the bits that are reusable and only
  41514. // fetch the remaining ones.
  41515. contextLabel = (contextLabel << 1) & reuseMask;
  41516. for (k = 0; k < changingEntriesLength; k++) {
  41517. i0 = i + changingTemplateY[k];
  41518. j0 = j + changingTemplateX[k];
  41519. bit = bitmap[i0][j0];
  41520. if (bit) {
  41521. bit = changingTemplateBit[k];
  41522. contextLabel |= bit;
  41523. }
  41524. }
  41525. } else {
  41526. // compute the contextLabel from scratch
  41527. contextLabel = 0;
  41528. shift = templateLength - 1;
  41529. for (k = 0; k < templateLength; k++, shift--) {
  41530. j0 = j + templateX[k];
  41531. if (j0 >= 0 && j0 < width) {
  41532. i0 = i + templateY[k];
  41533. if (i0 >= 0) {
  41534. bit = bitmap[i0][j0];
  41535. if (bit) {
  41536. contextLabel |= bit << shift;
  41537. }
  41538. }
  41539. }
  41540. }
  41541. }
  41542. var pixel = decoder.readBit(contexts, contextLabel);
  41543. row[j] = pixel;
  41544. }
  41545. }
  41546. return bitmap;
  41547. }
  41548. // 6.3.2 Generic Refinement Region Decoding Procedure
  41549. function decodeRefinement(width, height, templateIndex, referenceBitmap,
  41550. offsetX, offsetY, prediction, at,
  41551. decodingContext) {
  41552. var codingTemplate = RefinementTemplates[templateIndex].coding;
  41553. if (templateIndex === 0) {
  41554. codingTemplate = codingTemplate.concat([at[0]]);
  41555. }
  41556. var codingTemplateLength = codingTemplate.length;
  41557. var codingTemplateX = new Int32Array(codingTemplateLength);
  41558. var codingTemplateY = new Int32Array(codingTemplateLength);
  41559. var k;
  41560. for (k = 0; k < codingTemplateLength; k++) {
  41561. codingTemplateX[k] = codingTemplate[k].x;
  41562. codingTemplateY[k] = codingTemplate[k].y;
  41563. }
  41564. var referenceTemplate = RefinementTemplates[templateIndex].reference;
  41565. if (templateIndex === 0) {
  41566. referenceTemplate = referenceTemplate.concat([at[1]]);
  41567. }
  41568. var referenceTemplateLength = referenceTemplate.length;
  41569. var referenceTemplateX = new Int32Array(referenceTemplateLength);
  41570. var referenceTemplateY = new Int32Array(referenceTemplateLength);
  41571. for (k = 0; k < referenceTemplateLength; k++) {
  41572. referenceTemplateX[k] = referenceTemplate[k].x;
  41573. referenceTemplateY[k] = referenceTemplate[k].y;
  41574. }
  41575. var referenceWidth = referenceBitmap[0].length;
  41576. var referenceHeight = referenceBitmap.length;
  41577. var pseudoPixelContext = RefinementReusedContexts[templateIndex];
  41578. var bitmap = [];
  41579. var decoder = decodingContext.decoder;
  41580. var contexts = decodingContext.contextCache.getContexts('GR');
  41581. var ltp = 0;
  41582. for (var i = 0; i < height; i++) {
  41583. if (prediction) {
  41584. var sltp = decoder.readBit(contexts, pseudoPixelContext);
  41585. ltp ^= sltp;
  41586. if (ltp) {
  41587. error('JBIG2 error: prediction is not supported');
  41588. }
  41589. }
  41590. var row = new Uint8Array(width);
  41591. bitmap.push(row);
  41592. for (var j = 0; j < width; j++) {
  41593. var i0, j0;
  41594. var contextLabel = 0;
  41595. for (k = 0; k < codingTemplateLength; k++) {
  41596. i0 = i + codingTemplateY[k];
  41597. j0 = j + codingTemplateX[k];
  41598. if (i0 < 0 || j0 < 0 || j0 >= width) {
  41599. contextLabel <<= 1; // out of bound pixel
  41600. } else {
  41601. contextLabel = (contextLabel << 1) | bitmap[i0][j0];
  41602. }
  41603. }
  41604. for (k = 0; k < referenceTemplateLength; k++) {
  41605. i0 = i + referenceTemplateY[k] + offsetY;
  41606. j0 = j + referenceTemplateX[k] + offsetX;
  41607. if (i0 < 0 || i0 >= referenceHeight || j0 < 0 ||
  41608. j0 >= referenceWidth) {
  41609. contextLabel <<= 1; // out of bound pixel
  41610. } else {
  41611. contextLabel = (contextLabel << 1) | referenceBitmap[i0][j0];
  41612. }
  41613. }
  41614. var pixel = decoder.readBit(contexts, contextLabel);
  41615. row[j] = pixel;
  41616. }
  41617. }
  41618. return bitmap;
  41619. }
  41620. // 6.5.5 Decoding the symbol dictionary
  41621. function decodeSymbolDictionary(huffman, refinement, symbols,
  41622. numberOfNewSymbols, numberOfExportedSymbols,
  41623. huffmanTables, templateIndex, at,
  41624. refinementTemplateIndex, refinementAt,
  41625. decodingContext) {
  41626. if (huffman) {
  41627. error('JBIG2 error: huffman is not supported');
  41628. }
  41629. var newSymbols = [];
  41630. var currentHeight = 0;
  41631. var symbolCodeLength = log2(symbols.length + numberOfNewSymbols);
  41632. var decoder = decodingContext.decoder;
  41633. var contextCache = decodingContext.contextCache;
  41634. while (newSymbols.length < numberOfNewSymbols) {
  41635. var deltaHeight = decodeInteger(contextCache, 'IADH', decoder); // 6.5.6
  41636. currentHeight += deltaHeight;
  41637. var currentWidth = 0;
  41638. var totalWidth = 0;
  41639. while (true) {
  41640. var deltaWidth = decodeInteger(contextCache, 'IADW', decoder); // 6.5.7
  41641. if (deltaWidth === null) {
  41642. break; // OOB
  41643. }
  41644. currentWidth += deltaWidth;
  41645. totalWidth += currentWidth;
  41646. var bitmap;
  41647. if (refinement) {
  41648. // 6.5.8.2 Refinement/aggregate-coded symbol bitmap
  41649. var numberOfInstances = decodeInteger(contextCache, 'IAAI', decoder);
  41650. if (numberOfInstances > 1) {
  41651. bitmap = decodeTextRegion(huffman, refinement,
  41652. currentWidth, currentHeight, 0,
  41653. numberOfInstances, 1, //strip size
  41654. symbols.concat(newSymbols),
  41655. symbolCodeLength,
  41656. 0, //transposed
  41657. 0, //ds offset
  41658. 1, //top left 7.4.3.1.1
  41659. 0, //OR operator
  41660. huffmanTables,
  41661. refinementTemplateIndex, refinementAt,
  41662. decodingContext);
  41663. } else {
  41664. var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  41665. var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3
  41666. var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4
  41667. var symbol = (symbolId < symbols.length ? symbols[symbolId] :
  41668. newSymbols[symbolId - symbols.length]);
  41669. bitmap = decodeRefinement(currentWidth, currentHeight,
  41670. refinementTemplateIndex, symbol, rdx, rdy, false, refinementAt,
  41671. decodingContext);
  41672. }
  41673. } else {
  41674. // 6.5.8.1 Direct-coded symbol bitmap
  41675. bitmap = decodeBitmap(false, currentWidth, currentHeight,
  41676. templateIndex, false, null, at, decodingContext);
  41677. }
  41678. newSymbols.push(bitmap);
  41679. }
  41680. }
  41681. // 6.5.10 Exported symbols
  41682. var exportedSymbols = [];
  41683. var flags = [], currentFlag = false;
  41684. var totalSymbolsLength = symbols.length + numberOfNewSymbols;
  41685. while (flags.length < totalSymbolsLength) {
  41686. var runLength = decodeInteger(contextCache, 'IAEX', decoder);
  41687. while (runLength--) {
  41688. flags.push(currentFlag);
  41689. }
  41690. currentFlag = !currentFlag;
  41691. }
  41692. for (var i = 0, ii = symbols.length; i < ii; i++) {
  41693. if (flags[i]) {
  41694. exportedSymbols.push(symbols[i]);
  41695. }
  41696. }
  41697. for (var j = 0; j < numberOfNewSymbols; i++, j++) {
  41698. if (flags[i]) {
  41699. exportedSymbols.push(newSymbols[j]);
  41700. }
  41701. }
  41702. return exportedSymbols;
  41703. }
  41704. function decodeTextRegion(huffman, refinement, width, height,
  41705. defaultPixelValue, numberOfSymbolInstances,
  41706. stripSize, inputSymbols, symbolCodeLength,
  41707. transposed, dsOffset, referenceCorner,
  41708. combinationOperator, huffmanTables,
  41709. refinementTemplateIndex, refinementAt,
  41710. decodingContext) {
  41711. if (huffman) {
  41712. error('JBIG2 error: huffman is not supported');
  41713. }
  41714. // Prepare bitmap
  41715. var bitmap = [];
  41716. var i, row;
  41717. for (i = 0; i < height; i++) {
  41718. row = new Uint8Array(width);
  41719. if (defaultPixelValue) {
  41720. for (var j = 0; j < width; j++) {
  41721. row[j] = defaultPixelValue;
  41722. }
  41723. }
  41724. bitmap.push(row);
  41725. }
  41726. var decoder = decodingContext.decoder;
  41727. var contextCache = decodingContext.contextCache;
  41728. var stripT = -decodeInteger(contextCache, 'IADT', decoder); // 6.4.6
  41729. var firstS = 0;
  41730. i = 0;
  41731. while (i < numberOfSymbolInstances) {
  41732. var deltaT = decodeInteger(contextCache, 'IADT', decoder); // 6.4.6
  41733. stripT += deltaT;
  41734. var deltaFirstS = decodeInteger(contextCache, 'IAFS', decoder); // 6.4.7
  41735. firstS += deltaFirstS;
  41736. var currentS = firstS;
  41737. do {
  41738. var currentT = (stripSize === 1 ? 0 :
  41739. decodeInteger(contextCache, 'IAIT', decoder)); // 6.4.9
  41740. var t = stripSize * stripT + currentT;
  41741. var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  41742. var applyRefinement = (refinement &&
  41743. decodeInteger(contextCache, 'IARI', decoder));
  41744. var symbolBitmap = inputSymbols[symbolId];
  41745. var symbolWidth = symbolBitmap[0].length;
  41746. var symbolHeight = symbolBitmap.length;
  41747. if (applyRefinement) {
  41748. var rdw = decodeInteger(contextCache, 'IARDW', decoder); // 6.4.11.1
  41749. var rdh = decodeInteger(contextCache, 'IARDH', decoder); // 6.4.11.2
  41750. var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3
  41751. var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4
  41752. symbolWidth += rdw;
  41753. symbolHeight += rdh;
  41754. symbolBitmap = decodeRefinement(symbolWidth, symbolHeight,
  41755. refinementTemplateIndex, symbolBitmap, (rdw >> 1) + rdx,
  41756. (rdh >> 1) + rdy, false, refinementAt,
  41757. decodingContext);
  41758. }
  41759. var offsetT = t - ((referenceCorner & 1) ? 0 : symbolHeight);
  41760. var offsetS = currentS - ((referenceCorner & 2) ? symbolWidth : 0);
  41761. var s2, t2, symbolRow;
  41762. if (transposed) {
  41763. // Place Symbol Bitmap from T1,S1
  41764. for (s2 = 0; s2 < symbolHeight; s2++) {
  41765. row = bitmap[offsetS + s2];
  41766. if (!row) {
  41767. continue;
  41768. }
  41769. symbolRow = symbolBitmap[s2];
  41770. // To ignore Parts of Symbol bitmap which goes
  41771. // outside bitmap region
  41772. var maxWidth = Math.min(width - offsetT, symbolWidth);
  41773. switch (combinationOperator) {
  41774. case 0: // OR
  41775. for (t2 = 0; t2 < maxWidth; t2++) {
  41776. row[offsetT + t2] |= symbolRow[t2];
  41777. }
  41778. break;
  41779. case 2: // XOR
  41780. for (t2 = 0; t2 < maxWidth; t2++) {
  41781. row[offsetT + t2] ^= symbolRow[t2];
  41782. }
  41783. break;
  41784. default:
  41785. error('JBIG2 error: operator ' + combinationOperator +
  41786. ' is not supported');
  41787. }
  41788. }
  41789. currentS += symbolHeight - 1;
  41790. } else {
  41791. for (t2 = 0; t2 < symbolHeight; t2++) {
  41792. row = bitmap[offsetT + t2];
  41793. if (!row) {
  41794. continue;
  41795. }
  41796. symbolRow = symbolBitmap[t2];
  41797. switch (combinationOperator) {
  41798. case 0: // OR
  41799. for (s2 = 0; s2 < symbolWidth; s2++) {
  41800. row[offsetS + s2] |= symbolRow[s2];
  41801. }
  41802. break;
  41803. case 2: // XOR
  41804. for (s2 = 0; s2 < symbolWidth; s2++) {
  41805. row[offsetS + s2] ^= symbolRow[s2];
  41806. }
  41807. break;
  41808. default:
  41809. error('JBIG2 error: operator ' + combinationOperator +
  41810. ' is not supported');
  41811. }
  41812. }
  41813. currentS += symbolWidth - 1;
  41814. }
  41815. i++;
  41816. var deltaS = decodeInteger(contextCache, 'IADS', decoder); // 6.4.8
  41817. if (deltaS === null) {
  41818. break; // OOB
  41819. }
  41820. currentS += deltaS + dsOffset;
  41821. } while (true);
  41822. }
  41823. return bitmap;
  41824. }
  41825. function readSegmentHeader(data, start) {
  41826. var segmentHeader = {};
  41827. segmentHeader.number = readUint32(data, start);
  41828. var flags = data[start + 4];
  41829. var segmentType = flags & 0x3F;
  41830. if (!SegmentTypes[segmentType]) {
  41831. error('JBIG2 error: invalid segment type: ' + segmentType);
  41832. }
  41833. segmentHeader.type = segmentType;
  41834. segmentHeader.typeName = SegmentTypes[segmentType];
  41835. segmentHeader.deferredNonRetain = !!(flags & 0x80);
  41836. var pageAssociationFieldSize = !!(flags & 0x40);
  41837. var referredFlags = data[start + 5];
  41838. var referredToCount = (referredFlags >> 5) & 7;
  41839. var retainBits = [referredFlags & 31];
  41840. var position = start + 6;
  41841. if (referredFlags === 7) {
  41842. referredToCount = readUint32(data, position - 1) & 0x1FFFFFFF;
  41843. position += 3;
  41844. var bytes = (referredToCount + 7) >> 3;
  41845. retainBits[0] = data[position++];
  41846. while (--bytes > 0) {
  41847. retainBits.push(data[position++]);
  41848. }
  41849. } else if (referredFlags === 5 || referredFlags === 6) {
  41850. error('JBIG2 error: invalid referred-to flags');
  41851. }
  41852. segmentHeader.retainBits = retainBits;
  41853. var referredToSegmentNumberSize = (segmentHeader.number <= 256 ? 1 :
  41854. (segmentHeader.number <= 65536 ? 2 : 4));
  41855. var referredTo = [];
  41856. var i, ii;
  41857. for (i = 0; i < referredToCount; i++) {
  41858. var number = (referredToSegmentNumberSize === 1 ? data[position] :
  41859. (referredToSegmentNumberSize === 2 ? readUint16(data, position) :
  41860. readUint32(data, position)));
  41861. referredTo.push(number);
  41862. position += referredToSegmentNumberSize;
  41863. }
  41864. segmentHeader.referredTo = referredTo;
  41865. if (!pageAssociationFieldSize) {
  41866. segmentHeader.pageAssociation = data[position++];
  41867. } else {
  41868. segmentHeader.pageAssociation = readUint32(data, position);
  41869. position += 4;
  41870. }
  41871. segmentHeader.length = readUint32(data, position);
  41872. position += 4;
  41873. if (segmentHeader.length === 0xFFFFFFFF) {
  41874. // 7.2.7 Segment data length, unknown segment length
  41875. if (segmentType === 38) { // ImmediateGenericRegion
  41876. var genericRegionInfo = readRegionSegmentInformation(data, position);
  41877. var genericRegionSegmentFlags = data[position +
  41878. RegionSegmentInformationFieldLength];
  41879. var genericRegionMmr = !!(genericRegionSegmentFlags & 1);
  41880. // searching for the segment end
  41881. var searchPatternLength = 6;
  41882. var searchPattern = new Uint8Array(searchPatternLength);
  41883. if (!genericRegionMmr) {
  41884. searchPattern[0] = 0xFF;
  41885. searchPattern[1] = 0xAC;
  41886. }
  41887. searchPattern[2] = (genericRegionInfo.height >>> 24) & 0xFF;
  41888. searchPattern[3] = (genericRegionInfo.height >> 16) & 0xFF;
  41889. searchPattern[4] = (genericRegionInfo.height >> 8) & 0xFF;
  41890. searchPattern[5] = genericRegionInfo.height & 0xFF;
  41891. for (i = position, ii = data.length; i < ii; i++) {
  41892. var j = 0;
  41893. while (j < searchPatternLength && searchPattern[j] === data[i + j]) {
  41894. j++;
  41895. }
  41896. if (j === searchPatternLength) {
  41897. segmentHeader.length = i + searchPatternLength;
  41898. break;
  41899. }
  41900. }
  41901. if (segmentHeader.length === 0xFFFFFFFF) {
  41902. error('JBIG2 error: segment end was not found');
  41903. }
  41904. } else {
  41905. error('JBIG2 error: invalid unknown segment length');
  41906. }
  41907. }
  41908. segmentHeader.headerEnd = position;
  41909. return segmentHeader;
  41910. }
  41911. function readSegments(header, data, start, end) {
  41912. var segments = [];
  41913. var position = start;
  41914. while (position < end) {
  41915. var segmentHeader = readSegmentHeader(data, position);
  41916. position = segmentHeader.headerEnd;
  41917. var segment = {
  41918. header: segmentHeader,
  41919. data: data
  41920. };
  41921. if (!header.randomAccess) {
  41922. segment.start = position;
  41923. position += segmentHeader.length;
  41924. segment.end = position;
  41925. }
  41926. segments.push(segment);
  41927. if (segmentHeader.type === 51) {
  41928. break; // end of file is found
  41929. }
  41930. }
  41931. if (header.randomAccess) {
  41932. for (var i = 0, ii = segments.length; i < ii; i++) {
  41933. segments[i].start = position;
  41934. position += segments[i].header.length;
  41935. segments[i].end = position;
  41936. }
  41937. }
  41938. return segments;
  41939. }
  41940. // 7.4.1 Region segment information field
  41941. function readRegionSegmentInformation(data, start) {
  41942. return {
  41943. width: readUint32(data, start),
  41944. height: readUint32(data, start + 4),
  41945. x: readUint32(data, start + 8),
  41946. y: readUint32(data, start + 12),
  41947. combinationOperator: data[start + 16] & 7
  41948. };
  41949. }
  41950. var RegionSegmentInformationFieldLength = 17;
  41951. function processSegment(segment, visitor) {
  41952. var header = segment.header;
  41953. var data = segment.data, position = segment.start, end = segment.end;
  41954. var args, at, i, atLength;
  41955. switch (header.type) {
  41956. case 0: // SymbolDictionary
  41957. // 7.4.2 Symbol dictionary segment syntax
  41958. var dictionary = {};
  41959. var dictionaryFlags = readUint16(data, position); // 7.4.2.1.1
  41960. dictionary.huffman = !!(dictionaryFlags & 1);
  41961. dictionary.refinement = !!(dictionaryFlags & 2);
  41962. dictionary.huffmanDHSelector = (dictionaryFlags >> 2) & 3;
  41963. dictionary.huffmanDWSelector = (dictionaryFlags >> 4) & 3;
  41964. dictionary.bitmapSizeSelector = (dictionaryFlags >> 6) & 1;
  41965. dictionary.aggregationInstancesSelector = (dictionaryFlags >> 7) & 1;
  41966. dictionary.bitmapCodingContextUsed = !!(dictionaryFlags & 256);
  41967. dictionary.bitmapCodingContextRetained = !!(dictionaryFlags & 512);
  41968. dictionary.template = (dictionaryFlags >> 10) & 3;
  41969. dictionary.refinementTemplate = (dictionaryFlags >> 12) & 1;
  41970. position += 2;
  41971. if (!dictionary.huffman) {
  41972. atLength = dictionary.template === 0 ? 4 : 1;
  41973. at = [];
  41974. for (i = 0; i < atLength; i++) {
  41975. at.push({
  41976. x: readInt8(data, position),
  41977. y: readInt8(data, position + 1)
  41978. });
  41979. position += 2;
  41980. }
  41981. dictionary.at = at;
  41982. }
  41983. if (dictionary.refinement && !dictionary.refinementTemplate) {
  41984. at = [];
  41985. for (i = 0; i < 2; i++) {
  41986. at.push({
  41987. x: readInt8(data, position),
  41988. y: readInt8(data, position + 1)
  41989. });
  41990. position += 2;
  41991. }
  41992. dictionary.refinementAt = at;
  41993. }
  41994. dictionary.numberOfExportedSymbols = readUint32(data, position);
  41995. position += 4;
  41996. dictionary.numberOfNewSymbols = readUint32(data, position);
  41997. position += 4;
  41998. args = [dictionary, header.number, header.referredTo,
  41999. data, position, end];
  42000. break;
  42001. case 6: // ImmediateTextRegion
  42002. case 7: // ImmediateLosslessTextRegion
  42003. var textRegion = {};
  42004. textRegion.info = readRegionSegmentInformation(data, position);
  42005. position += RegionSegmentInformationFieldLength;
  42006. var textRegionSegmentFlags = readUint16(data, position);
  42007. position += 2;
  42008. textRegion.huffman = !!(textRegionSegmentFlags & 1);
  42009. textRegion.refinement = !!(textRegionSegmentFlags & 2);
  42010. textRegion.stripSize = 1 << ((textRegionSegmentFlags >> 2) & 3);
  42011. textRegion.referenceCorner = (textRegionSegmentFlags >> 4) & 3;
  42012. textRegion.transposed = !!(textRegionSegmentFlags & 64);
  42013. textRegion.combinationOperator = (textRegionSegmentFlags >> 7) & 3;
  42014. textRegion.defaultPixelValue = (textRegionSegmentFlags >> 9) & 1;
  42015. textRegion.dsOffset = (textRegionSegmentFlags << 17) >> 27;
  42016. textRegion.refinementTemplate = (textRegionSegmentFlags >> 15) & 1;
  42017. if (textRegion.huffman) {
  42018. var textRegionHuffmanFlags = readUint16(data, position);
  42019. position += 2;
  42020. textRegion.huffmanFS = (textRegionHuffmanFlags) & 3;
  42021. textRegion.huffmanDS = (textRegionHuffmanFlags >> 2) & 3;
  42022. textRegion.huffmanDT = (textRegionHuffmanFlags >> 4) & 3;
  42023. textRegion.huffmanRefinementDW = (textRegionHuffmanFlags >> 6) & 3;
  42024. textRegion.huffmanRefinementDH = (textRegionHuffmanFlags >> 8) & 3;
  42025. textRegion.huffmanRefinementDX = (textRegionHuffmanFlags >> 10) & 3;
  42026. textRegion.huffmanRefinementDY = (textRegionHuffmanFlags >> 12) & 3;
  42027. textRegion.huffmanRefinementSizeSelector =
  42028. !!(textRegionHuffmanFlags & 14);
  42029. }
  42030. if (textRegion.refinement && !textRegion.refinementTemplate) {
  42031. at = [];
  42032. for (i = 0; i < 2; i++) {
  42033. at.push({
  42034. x: readInt8(data, position),
  42035. y: readInt8(data, position + 1)
  42036. });
  42037. position += 2;
  42038. }
  42039. textRegion.refinementAt = at;
  42040. }
  42041. textRegion.numberOfSymbolInstances = readUint32(data, position);
  42042. position += 4;
  42043. // TODO 7.4.3.1.7 Symbol ID Huffman table decoding
  42044. if (textRegion.huffman) {
  42045. error('JBIG2 error: huffman is not supported');
  42046. }
  42047. args = [textRegion, header.referredTo, data, position, end];
  42048. break;
  42049. case 38: // ImmediateGenericRegion
  42050. case 39: // ImmediateLosslessGenericRegion
  42051. var genericRegion = {};
  42052. genericRegion.info = readRegionSegmentInformation(data, position);
  42053. position += RegionSegmentInformationFieldLength;
  42054. var genericRegionSegmentFlags = data[position++];
  42055. genericRegion.mmr = !!(genericRegionSegmentFlags & 1);
  42056. genericRegion.template = (genericRegionSegmentFlags >> 1) & 3;
  42057. genericRegion.prediction = !!(genericRegionSegmentFlags & 8);
  42058. if (!genericRegion.mmr) {
  42059. atLength = genericRegion.template === 0 ? 4 : 1;
  42060. at = [];
  42061. for (i = 0; i < atLength; i++) {
  42062. at.push({
  42063. x: readInt8(data, position),
  42064. y: readInt8(data, position + 1)
  42065. });
  42066. position += 2;
  42067. }
  42068. genericRegion.at = at;
  42069. }
  42070. args = [genericRegion, data, position, end];
  42071. break;
  42072. case 48: // PageInformation
  42073. var pageInfo = {
  42074. width: readUint32(data, position),
  42075. height: readUint32(data, position + 4),
  42076. resolutionX: readUint32(data, position + 8),
  42077. resolutionY: readUint32(data, position + 12)
  42078. };
  42079. if (pageInfo.height === 0xFFFFFFFF) {
  42080. delete pageInfo.height;
  42081. }
  42082. var pageSegmentFlags = data[position + 16];
  42083. var pageStripingInformatiom = readUint16(data, position + 17);
  42084. pageInfo.lossless = !!(pageSegmentFlags & 1);
  42085. pageInfo.refinement = !!(pageSegmentFlags & 2);
  42086. pageInfo.defaultPixelValue = (pageSegmentFlags >> 2) & 1;
  42087. pageInfo.combinationOperator = (pageSegmentFlags >> 3) & 3;
  42088. pageInfo.requiresBuffer = !!(pageSegmentFlags & 32);
  42089. pageInfo.combinationOperatorOverride = !!(pageSegmentFlags & 64);
  42090. args = [pageInfo];
  42091. break;
  42092. case 49: // EndOfPage
  42093. break;
  42094. case 50: // EndOfStripe
  42095. break;
  42096. case 51: // EndOfFile
  42097. break;
  42098. case 62: // 7.4.15 defines 2 extension types which
  42099. // are comments and can be ignored.
  42100. break;
  42101. default:
  42102. error('JBIG2 error: segment type ' + header.typeName + '(' +
  42103. header.type + ') is not implemented');
  42104. }
  42105. var callbackName = 'on' + header.typeName;
  42106. if (callbackName in visitor) {
  42107. visitor[callbackName].apply(visitor, args);
  42108. }
  42109. }
  42110. function processSegments(segments, visitor) {
  42111. for (var i = 0, ii = segments.length; i < ii; i++) {
  42112. processSegment(segments[i], visitor);
  42113. }
  42114. }
  42115. function parseJbig2(data, start, end) {
  42116. var position = start;
  42117. if (data[position] !== 0x97 || data[position + 1] !== 0x4A ||
  42118. data[position + 2] !== 0x42 || data[position + 3] !== 0x32 ||
  42119. data[position + 4] !== 0x0D || data[position + 5] !== 0x0A ||
  42120. data[position + 6] !== 0x1A || data[position + 7] !== 0x0A) {
  42121. error('JBIG2 error: invalid header');
  42122. }
  42123. var header = {};
  42124. position += 8;
  42125. var flags = data[position++];
  42126. header.randomAccess = !(flags & 1);
  42127. if (!(flags & 2)) {
  42128. header.numberOfPages = readUint32(data, position);
  42129. position += 4;
  42130. }
  42131. var segments = readSegments(header, data, position, end);
  42132. error('Not implemented');
  42133. // processSegments(segments, new SimpleSegmentVisitor());
  42134. }
  42135. function parseJbig2Chunks(chunks) {
  42136. var visitor = new SimpleSegmentVisitor();
  42137. for (var i = 0, ii = chunks.length; i < ii; i++) {
  42138. var chunk = chunks[i];
  42139. var segments = readSegments({}, chunk.data, chunk.start, chunk.end);
  42140. processSegments(segments, visitor);
  42141. }
  42142. return visitor.buffer;
  42143. }
  42144. function SimpleSegmentVisitor() {}
  42145. SimpleSegmentVisitor.prototype = {
  42146. onPageInformation: function SimpleSegmentVisitor_onPageInformation(info) {
  42147. this.currentPageInfo = info;
  42148. var rowSize = (info.width + 7) >> 3;
  42149. var buffer = new Uint8Array(rowSize * info.height);
  42150. // The contents of ArrayBuffers are initialized to 0.
  42151. // Fill the buffer with 0xFF only if info.defaultPixelValue is set
  42152. if (info.defaultPixelValue) {
  42153. for (var i = 0, ii = buffer.length; i < ii; i++) {
  42154. buffer[i] = 0xFF;
  42155. }
  42156. }
  42157. this.buffer = buffer;
  42158. },
  42159. drawBitmap: function SimpleSegmentVisitor_drawBitmap(regionInfo, bitmap) {
  42160. var pageInfo = this.currentPageInfo;
  42161. var width = regionInfo.width, height = regionInfo.height;
  42162. var rowSize = (pageInfo.width + 7) >> 3;
  42163. var combinationOperator = pageInfo.combinationOperatorOverride ?
  42164. regionInfo.combinationOperator : pageInfo.combinationOperator;
  42165. var buffer = this.buffer;
  42166. var mask0 = 128 >> (regionInfo.x & 7);
  42167. var offset0 = regionInfo.y * rowSize + (regionInfo.x >> 3);
  42168. var i, j, mask, offset;
  42169. switch (combinationOperator) {
  42170. case 0: // OR
  42171. for (i = 0; i < height; i++) {
  42172. mask = mask0;
  42173. offset = offset0;
  42174. for (j = 0; j < width; j++) {
  42175. if (bitmap[i][j]) {
  42176. buffer[offset] |= mask;
  42177. }
  42178. mask >>= 1;
  42179. if (!mask) {
  42180. mask = 128;
  42181. offset++;
  42182. }
  42183. }
  42184. offset0 += rowSize;
  42185. }
  42186. break;
  42187. case 2: // XOR
  42188. for (i = 0; i < height; i++) {
  42189. mask = mask0;
  42190. offset = offset0;
  42191. for (j = 0; j < width; j++) {
  42192. if (bitmap[i][j]) {
  42193. buffer[offset] ^= mask;
  42194. }
  42195. mask >>= 1;
  42196. if (!mask) {
  42197. mask = 128;
  42198. offset++;
  42199. }
  42200. }
  42201. offset0 += rowSize;
  42202. }
  42203. break;
  42204. default:
  42205. error('JBIG2 error: operator ' + combinationOperator +
  42206. ' is not supported');
  42207. }
  42208. },
  42209. onImmediateGenericRegion:
  42210. function SimpleSegmentVisitor_onImmediateGenericRegion(region, data,
  42211. start, end) {
  42212. var regionInfo = region.info;
  42213. var decodingContext = new DecodingContext(data, start, end);
  42214. var bitmap = decodeBitmap(region.mmr, regionInfo.width, regionInfo.height,
  42215. region.template, region.prediction, null,
  42216. region.at, decodingContext);
  42217. this.drawBitmap(regionInfo, bitmap);
  42218. },
  42219. onImmediateLosslessGenericRegion:
  42220. function SimpleSegmentVisitor_onImmediateLosslessGenericRegion() {
  42221. this.onImmediateGenericRegion.apply(this, arguments);
  42222. },
  42223. onSymbolDictionary:
  42224. function SimpleSegmentVisitor_onSymbolDictionary(dictionary,
  42225. currentSegment,
  42226. referredSegments,
  42227. data, start, end) {
  42228. var huffmanTables;
  42229. if (dictionary.huffman) {
  42230. error('JBIG2 error: huffman is not supported');
  42231. }
  42232. // Combines exported symbols from all referred segments
  42233. var symbols = this.symbols;
  42234. if (!symbols) {
  42235. this.symbols = symbols = {};
  42236. }
  42237. var inputSymbols = [];
  42238. for (var i = 0, ii = referredSegments.length; i < ii; i++) {
  42239. inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
  42240. }
  42241. var decodingContext = new DecodingContext(data, start, end);
  42242. symbols[currentSegment] = decodeSymbolDictionary(dictionary.huffman,
  42243. dictionary.refinement, inputSymbols, dictionary.numberOfNewSymbols,
  42244. dictionary.numberOfExportedSymbols, huffmanTables,
  42245. dictionary.template, dictionary.at,
  42246. dictionary.refinementTemplate, dictionary.refinementAt,
  42247. decodingContext);
  42248. },
  42249. onImmediateTextRegion:
  42250. function SimpleSegmentVisitor_onImmediateTextRegion(region,
  42251. referredSegments,
  42252. data, start, end) {
  42253. var regionInfo = region.info;
  42254. var huffmanTables;
  42255. // Combines exported symbols from all referred segments
  42256. var symbols = this.symbols;
  42257. var inputSymbols = [];
  42258. for (var i = 0, ii = referredSegments.length; i < ii; i++) {
  42259. inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
  42260. }
  42261. var symbolCodeLength = log2(inputSymbols.length);
  42262. var decodingContext = new DecodingContext(data, start, end);
  42263. var bitmap = decodeTextRegion(region.huffman, region.refinement,
  42264. regionInfo.width, regionInfo.height, region.defaultPixelValue,
  42265. region.numberOfSymbolInstances, region.stripSize, inputSymbols,
  42266. symbolCodeLength, region.transposed, region.dsOffset,
  42267. region.referenceCorner, region.combinationOperator, huffmanTables,
  42268. region.refinementTemplate, region.refinementAt, decodingContext);
  42269. this.drawBitmap(regionInfo, bitmap);
  42270. },
  42271. onImmediateLosslessTextRegion:
  42272. function SimpleSegmentVisitor_onImmediateLosslessTextRegion() {
  42273. this.onImmediateTextRegion.apply(this, arguments);
  42274. }
  42275. };
  42276. function Jbig2Image() {}
  42277. Jbig2Image.prototype = {
  42278. parseChunks: function Jbig2Image_parseChunks(chunks) {
  42279. return parseJbig2Chunks(chunks);
  42280. }
  42281. };
  42282. return Jbig2Image;
  42283. })();
  42284. var bidi = PDFJS.bidi = (function bidiClosure() {
  42285. // Character types for symbols from 0000 to 00FF.
  42286. var baseTypes = [
  42287. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS',
  42288. 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  42289. 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON',
  42290. 'ON', 'ON', 'ON', 'ON', 'ON', 'CS', 'ON', 'CS', 'ON', 'EN', 'EN', 'EN',
  42291. 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'ON', 'ON', 'ON', 'ON', 'ON',
  42292. 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42293. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON',
  42294. 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42295. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42296. 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN',
  42297. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  42298. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  42299. 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON',
  42300. 'ON', 'ON', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON',
  42301. 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42302. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42303. 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42304. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  42305. 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'
  42306. ];
  42307. // Character types for symbols from 0600 to 06FF
  42308. var arabicTypes = [
  42309. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42310. 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL',
  42311. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42312. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42313. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42314. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42315. 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
  42316. 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL',
  42317. 'AL', 'AL', 'AL', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN',
  42318. 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL',
  42319. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42320. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42321. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42322. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42323. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42324. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42325. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42326. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42327. 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
  42328. 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'ON', 'NSM',
  42329. 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  42330. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL'
  42331. ];
  42332. function isOdd(i) {
  42333. return (i & 1) !== 0;
  42334. }
  42335. function isEven(i) {
  42336. return (i & 1) === 0;
  42337. }
  42338. function findUnequal(arr, start, value) {
  42339. for (var j = start, jj = arr.length; j < jj; ++j) {
  42340. if (arr[j] !== value) {
  42341. return j;
  42342. }
  42343. }
  42344. return j;
  42345. }
  42346. function setValues(arr, start, end, value) {
  42347. for (var j = start; j < end; ++j) {
  42348. arr[j] = value;
  42349. }
  42350. }
  42351. function reverseValues(arr, start, end) {
  42352. for (var i = start, j = end - 1; i < j; ++i, --j) {
  42353. var temp = arr[i];
  42354. arr[i] = arr[j];
  42355. arr[j] = temp;
  42356. }
  42357. }
  42358. function createBidiText(str, isLTR, vertical) {
  42359. return {
  42360. str: str,
  42361. dir: (vertical ? 'ttb' : (isLTR ? 'ltr' : 'rtl'))
  42362. };
  42363. }
  42364. // These are used in bidi(), which is called frequently. We re-use them on
  42365. // each call to avoid unnecessary allocations.
  42366. var chars = [];
  42367. var types = [];
  42368. function bidi(str, startLevel, vertical) {
  42369. var isLTR = true;
  42370. var strLength = str.length;
  42371. if (strLength === 0 || vertical) {
  42372. return createBidiText(str, isLTR, vertical);
  42373. }
  42374. // Get types and fill arrays
  42375. chars.length = strLength;
  42376. types.length = strLength;
  42377. var numBidi = 0;
  42378. var i, ii;
  42379. for (i = 0; i < strLength; ++i) {
  42380. chars[i] = str.charAt(i);
  42381. var charCode = str.charCodeAt(i);
  42382. var charType = 'L';
  42383. if (charCode <= 0x00ff) {
  42384. charType = baseTypes[charCode];
  42385. } else if (0x0590 <= charCode && charCode <= 0x05f4) {
  42386. charType = 'R';
  42387. } else if (0x0600 <= charCode && charCode <= 0x06ff) {
  42388. charType = arabicTypes[charCode & 0xff];
  42389. } else if (0x0700 <= charCode && charCode <= 0x08AC) {
  42390. charType = 'AL';
  42391. }
  42392. if (charType === 'R' || charType === 'AL' || charType === 'AN') {
  42393. numBidi++;
  42394. }
  42395. types[i] = charType;
  42396. }
  42397. // Detect the bidi method
  42398. // - If there are no rtl characters then no bidi needed
  42399. // - If less than 30% chars are rtl then string is primarily ltr
  42400. // - If more than 30% chars are rtl then string is primarily rtl
  42401. if (numBidi === 0) {
  42402. isLTR = true;
  42403. return createBidiText(str, isLTR);
  42404. }
  42405. if (startLevel === -1) {
  42406. if ((strLength / numBidi) < 0.3) {
  42407. isLTR = true;
  42408. startLevel = 0;
  42409. } else {
  42410. isLTR = false;
  42411. startLevel = 1;
  42412. }
  42413. }
  42414. var levels = [];
  42415. for (i = 0; i < strLength; ++i) {
  42416. levels[i] = startLevel;
  42417. }
  42418. /*
  42419. X1-X10: skip most of this, since we are NOT doing the embeddings.
  42420. */
  42421. var e = (isOdd(startLevel) ? 'R' : 'L');
  42422. var sor = e;
  42423. var eor = sor;
  42424. /*
  42425. W1. Examine each non-spacing mark (NSM) in the level run, and change the
  42426. type of the NSM to the type of the previous character. If the NSM is at the
  42427. start of the level run, it will get the type of sor.
  42428. */
  42429. var lastType = sor;
  42430. for (i = 0; i < strLength; ++i) {
  42431. if (types[i] === 'NSM') {
  42432. types[i] = lastType;
  42433. } else {
  42434. lastType = types[i];
  42435. }
  42436. }
  42437. /*
  42438. W2. Search backwards from each instance of a European number until the
  42439. first strong type (R, L, AL, or sor) is found. If an AL is found, change
  42440. the type of the European number to Arabic number.
  42441. */
  42442. lastType = sor;
  42443. var t;
  42444. for (i = 0; i < strLength; ++i) {
  42445. t = types[i];
  42446. if (t === 'EN') {
  42447. types[i] = (lastType === 'AL') ? 'AN' : 'EN';
  42448. } else if (t === 'R' || t === 'L' || t === 'AL') {
  42449. lastType = t;
  42450. }
  42451. }
  42452. /*
  42453. W3. Change all ALs to R.
  42454. */
  42455. for (i = 0; i < strLength; ++i) {
  42456. t = types[i];
  42457. if (t === 'AL') {
  42458. types[i] = 'R';
  42459. }
  42460. }
  42461. /*
  42462. W4. A single European separator between two European numbers changes to a
  42463. European number. A single common separator between two numbers of the same
  42464. type changes to that type:
  42465. */
  42466. for (i = 1; i < strLength - 1; ++i) {
  42467. if (types[i] === 'ES' && types[i - 1] === 'EN' && types[i + 1] === 'EN') {
  42468. types[i] = 'EN';
  42469. }
  42470. if (types[i] === 'CS' &&
  42471. (types[i - 1] === 'EN' || types[i - 1] === 'AN') &&
  42472. types[i + 1] === types[i - 1]) {
  42473. types[i] = types[i - 1];
  42474. }
  42475. }
  42476. /*
  42477. W5. A sequence of European terminators adjacent to European numbers changes
  42478. to all European numbers:
  42479. */
  42480. for (i = 0; i < strLength; ++i) {
  42481. if (types[i] === 'EN') {
  42482. // do before
  42483. var j;
  42484. for (j = i - 1; j >= 0; --j) {
  42485. if (types[j] !== 'ET') {
  42486. break;
  42487. }
  42488. types[j] = 'EN';
  42489. }
  42490. // do after
  42491. for (j = i + 1; j < strLength; --j) {
  42492. if (types[j] !== 'ET') {
  42493. break;
  42494. }
  42495. types[j] = 'EN';
  42496. }
  42497. }
  42498. }
  42499. /*
  42500. W6. Otherwise, separators and terminators change to Other Neutral:
  42501. */
  42502. for (i = 0; i < strLength; ++i) {
  42503. t = types[i];
  42504. if (t === 'WS' || t === 'ES' || t === 'ET' || t === 'CS') {
  42505. types[i] = 'ON';
  42506. }
  42507. }
  42508. /*
  42509. W7. Search backwards from each instance of a European number until the
  42510. first strong type (R, L, or sor) is found. If an L is found, then change
  42511. the type of the European number to L.
  42512. */
  42513. lastType = sor;
  42514. for (i = 0; i < strLength; ++i) {
  42515. t = types[i];
  42516. if (t === 'EN') {
  42517. types[i] = ((lastType === 'L') ? 'L' : 'EN');
  42518. } else if (t === 'R' || t === 'L') {
  42519. lastType = t;
  42520. }
  42521. }
  42522. /*
  42523. N1. A sequence of neutrals takes the direction of the surrounding strong
  42524. text if the text on both sides has the same direction. European and Arabic
  42525. numbers are treated as though they were R. Start-of-level-run (sor) and
  42526. end-of-level-run (eor) are used at level run boundaries.
  42527. */
  42528. for (i = 0; i < strLength; ++i) {
  42529. if (types[i] === 'ON') {
  42530. var end = findUnequal(types, i + 1, 'ON');
  42531. var before = sor;
  42532. if (i > 0) {
  42533. before = types[i - 1];
  42534. }
  42535. var after = eor;
  42536. if (end + 1 < strLength) {
  42537. after = types[end + 1];
  42538. }
  42539. if (before !== 'L') {
  42540. before = 'R';
  42541. }
  42542. if (after !== 'L') {
  42543. after = 'R';
  42544. }
  42545. if (before === after) {
  42546. setValues(types, i, end, before);
  42547. }
  42548. i = end - 1; // reset to end (-1 so next iteration is ok)
  42549. }
  42550. }
  42551. /*
  42552. N2. Any remaining neutrals take the embedding direction.
  42553. */
  42554. for (i = 0; i < strLength; ++i) {
  42555. if (types[i] === 'ON') {
  42556. types[i] = e;
  42557. }
  42558. }
  42559. /*
  42560. I1. For all characters with an even (left-to-right) embedding direction,
  42561. those of type R go up one level and those of type AN or EN go up two
  42562. levels.
  42563. I2. For all characters with an odd (right-to-left) embedding direction,
  42564. those of type L, EN or AN go up one level.
  42565. */
  42566. for (i = 0; i < strLength; ++i) {
  42567. t = types[i];
  42568. if (isEven(levels[i])) {
  42569. if (t === 'R') {
  42570. levels[i] += 1;
  42571. } else if (t === 'AN' || t === 'EN') {
  42572. levels[i] += 2;
  42573. }
  42574. } else { // isOdd
  42575. if (t === 'L' || t === 'AN' || t === 'EN') {
  42576. levels[i] += 1;
  42577. }
  42578. }
  42579. }
  42580. /*
  42581. L1. On each line, reset the embedding level of the following characters to
  42582. the paragraph embedding level:
  42583. segment separators,
  42584. paragraph separators,
  42585. any sequence of whitespace characters preceding a segment separator or
  42586. paragraph separator, and any sequence of white space characters at the end
  42587. of the line.
  42588. */
  42589. // don't bother as text is only single line
  42590. /*
  42591. L2. From the highest level found in the text to the lowest odd level on
  42592. each line, reverse any contiguous sequence of characters that are at that
  42593. level or higher.
  42594. */
  42595. // find highest level & lowest odd level
  42596. var highestLevel = -1;
  42597. var lowestOddLevel = 99;
  42598. var level;
  42599. for (i = 0, ii = levels.length; i < ii; ++i) {
  42600. level = levels[i];
  42601. if (highestLevel < level) {
  42602. highestLevel = level;
  42603. }
  42604. if (lowestOddLevel > level && isOdd(level)) {
  42605. lowestOddLevel = level;
  42606. }
  42607. }
  42608. // now reverse between those limits
  42609. for (level = highestLevel; level >= lowestOddLevel; --level) {
  42610. // find segments to reverse
  42611. var start = -1;
  42612. for (i = 0, ii = levels.length; i < ii; ++i) {
  42613. if (levels[i] < level) {
  42614. if (start >= 0) {
  42615. reverseValues(chars, start, i);
  42616. start = -1;
  42617. }
  42618. } else if (start < 0) {
  42619. start = i;
  42620. }
  42621. }
  42622. if (start >= 0) {
  42623. reverseValues(chars, start, levels.length);
  42624. }
  42625. }
  42626. /*
  42627. L3. Combining marks applied to a right-to-left base character will at this
  42628. point precede their base character. If the rendering engine expects them to
  42629. follow the base characters in the final display process, then the ordering
  42630. of the marks and the base character must be reversed.
  42631. */
  42632. // don't bother for now
  42633. /*
  42634. L4. A character that possesses the mirrored property as specified by
  42635. Section 4.7, Mirrored, must be depicted by a mirrored glyph if the resolved
  42636. directionality of that character is R.
  42637. */
  42638. // don't mirror as characters are already mirrored in the pdf
  42639. // Finally, return string
  42640. var result = '';
  42641. for (i = 0, ii = chars.length; i < ii; ++i) {
  42642. var ch = chars[i];
  42643. if (ch !== '<' && ch !== '>') {
  42644. result += ch;
  42645. }
  42646. }
  42647. return createBidiText(result, isLTR);
  42648. }
  42649. return bidi;
  42650. })();
  42651. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  42652. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  42653. /* Copyright 2014 Opera Software ASA
  42654. *
  42655. * Licensed under the Apache License, Version 2.0 (the "License");
  42656. * you may not use this file except in compliance with the License.
  42657. * You may obtain a copy of the License at
  42658. *
  42659. * http://www.apache.org/licenses/LICENSE-2.0
  42660. *
  42661. * Unless required by applicable law or agreed to in writing, software
  42662. * distributed under the License is distributed on an "AS IS" BASIS,
  42663. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42664. * See the License for the specific language governing permissions and
  42665. * limitations under the License.
  42666. *
  42667. *
  42668. * Based on https://code.google.com/p/smhasher/wiki/MurmurHash3.
  42669. * Hashes roughly 100 KB per millisecond on i7 3.4 GHz.
  42670. */
  42671. /* globals Uint32ArrayView */
  42672. 'use strict';
  42673. var MurmurHash3_64 = (function MurmurHash3_64Closure (seed) {
  42674. // Workaround for missing math precison in JS.
  42675. var MASK_HIGH = 0xffff0000;
  42676. var MASK_LOW = 0xffff;
  42677. function MurmurHash3_64 (seed) {
  42678. var SEED = 0xc3d2e1f0;
  42679. this.h1 = seed ? seed & 0xffffffff : SEED;
  42680. this.h2 = seed ? seed & 0xffffffff : SEED;
  42681. }
  42682. var alwaysUseUint32ArrayView = false;
  42683. // old webkits have issues with non-aligned arrays
  42684. try {
  42685. new Uint32Array(new Uint8Array(5).buffer, 0, 1);
  42686. } catch (e) {
  42687. alwaysUseUint32ArrayView = true;
  42688. }
  42689. MurmurHash3_64.prototype = {
  42690. update: function MurmurHash3_64_update(input) {
  42691. var useUint32ArrayView = alwaysUseUint32ArrayView;
  42692. var i;
  42693. if (typeof input === 'string') {
  42694. var data = new Uint8Array(input.length * 2);
  42695. var length = 0;
  42696. for (i = 0; i < input.length; i++) {
  42697. var code = input.charCodeAt(i);
  42698. if (code <= 0xff) {
  42699. data[length++] = code;
  42700. }
  42701. else {
  42702. data[length++] = code >>> 8;
  42703. data[length++] = code & 0xff;
  42704. }
  42705. }
  42706. } else if (input instanceof Uint8Array) {
  42707. data = input;
  42708. length = data.length;
  42709. } else if (typeof input === 'object' && ('length' in input)) {
  42710. // processing regular arrays as well, e.g. for IE9
  42711. data = input;
  42712. length = data.length;
  42713. useUint32ArrayView = true;
  42714. } else {
  42715. throw new Error('Wrong data format in MurmurHash3_64_update. ' +
  42716. 'Input must be a string or array.');
  42717. }
  42718. var blockCounts = length >> 2;
  42719. var tailLength = length - blockCounts * 4;
  42720. // we don't care about endianness here
  42721. var dataUint32 = useUint32ArrayView ?
  42722. new Uint32ArrayView(data, blockCounts) :
  42723. new Uint32Array(data.buffer, 0, blockCounts);
  42724. var k1 = 0;
  42725. var k2 = 0;
  42726. var h1 = this.h1;
  42727. var h2 = this.h2;
  42728. var C1 = 0xcc9e2d51;
  42729. var C2 = 0x1b873593;
  42730. var C1_LOW = C1 & MASK_LOW;
  42731. var C2_LOW = C2 & MASK_LOW;
  42732. for (i = 0; i < blockCounts; i++) {
  42733. if (i & 1) {
  42734. k1 = dataUint32[i];
  42735. k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);
  42736. k1 = k1 << 15 | k1 >>> 17;
  42737. k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);
  42738. h1 ^= k1;
  42739. h1 = h1 << 13 | h1 >>> 19;
  42740. h1 = h1 * 5 + 0xe6546b64;
  42741. } else {
  42742. k2 = dataUint32[i];
  42743. k2 = (k2 * C1 & MASK_HIGH) | (k2 * C1_LOW & MASK_LOW);
  42744. k2 = k2 << 15 | k2 >>> 17;
  42745. k2 = (k2 * C2 & MASK_HIGH) | (k2 * C2_LOW & MASK_LOW);
  42746. h2 ^= k2;
  42747. h2 = h2 << 13 | h2 >>> 19;
  42748. h2 = h2 * 5 + 0xe6546b64;
  42749. }
  42750. }
  42751. k1 = 0;
  42752. switch (tailLength) {
  42753. case 3:
  42754. k1 ^= data[blockCounts * 4 + 2] << 16;
  42755. /* falls through */
  42756. case 2:
  42757. k1 ^= data[blockCounts * 4 + 1] << 8;
  42758. /* falls through */
  42759. case 1:
  42760. k1 ^= data[blockCounts * 4];
  42761. /* falls through */
  42762. k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);
  42763. k1 = k1 << 15 | k1 >>> 17;
  42764. k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);
  42765. if (blockCounts & 1) {
  42766. h1 ^= k1;
  42767. } else {
  42768. h2 ^= k1;
  42769. }
  42770. }
  42771. this.h1 = h1;
  42772. this.h2 = h2;
  42773. return this;
  42774. },
  42775. hexdigest: function MurmurHash3_64_hexdigest () {
  42776. var h1 = this.h1;
  42777. var h2 = this.h2;
  42778. h1 ^= h2 >>> 1;
  42779. h1 = (h1 * 0xed558ccd & MASK_HIGH) | (h1 * 0x8ccd & MASK_LOW);
  42780. h2 = (h2 * 0xff51afd7 & MASK_HIGH) |
  42781. (((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16);
  42782. h1 ^= h2 >>> 1;
  42783. h1 = (h1 * 0x1a85ec53 & MASK_HIGH) | (h1 * 0xec53 & MASK_LOW);
  42784. h2 = (h2 * 0xc4ceb9fe & MASK_HIGH) |
  42785. (((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16);
  42786. h1 ^= h2 >>> 1;
  42787. for (var i = 0, arr = [h1, h2], str = ''; i < arr.length; i++) {
  42788. var hex = (arr[i] >>> 0).toString(16);
  42789. while (hex.length < 8) {
  42790. hex = '0' + hex;
  42791. }
  42792. str += hex;
  42793. }
  42794. return str;
  42795. }
  42796. };
  42797. return MurmurHash3_64;
  42798. })();
  42799. }).call((typeof window === 'undefined') ? this : window);
  42800. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  42801. // workerSrc is not set -- using last script url to define default location
  42802. PDFJS.workerSrc = (function () {
  42803. 'use strict';
  42804. var scriptTagContainer = document.body ||
  42805. document.getElementsByTagName('head')[0];
  42806. var pdfjsSrc = scriptTagContainer.lastChild.src;
  42807. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  42808. })();
  42809. }