pdf.combined.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214
  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.0.1029';
  24. PDFJS.build = '50fe7c8';
  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 StreamType = {
  73. UNKNOWN: 0,
  74. FLATE: 1,
  75. LZW: 2,
  76. DCT: 3,
  77. JPX: 4,
  78. JBIG: 5,
  79. A85: 6,
  80. AHX: 7,
  81. CCF: 8,
  82. RL: 9
  83. };
  84. var FontType = {
  85. UNKNOWN: 0,
  86. TYPE1: 1,
  87. TYPE1C: 2,
  88. CIDFONTTYPE0: 3,
  89. CIDFONTTYPE0C: 4,
  90. TRUETYPE: 5,
  91. CIDFONTTYPE2: 6,
  92. TYPE3: 7,
  93. OPENTYPE: 8,
  94. TYPE0: 9,
  95. MMTYPE1: 10
  96. };
  97. // The global PDFJS object exposes the API
  98. // In production, it will be declared outside a global wrapper
  99. // In development, it will be declared here
  100. if (!globalScope.PDFJS) {
  101. globalScope.PDFJS = {};
  102. }
  103. globalScope.PDFJS.pdfBug = false;
  104. PDFJS.VERBOSITY_LEVELS = {
  105. errors: 0,
  106. warnings: 1,
  107. infos: 5
  108. };
  109. // All the possible operations for an operator list.
  110. var OPS = PDFJS.OPS = {
  111. // Intentionally start from 1 so it is easy to spot bad operators that will be
  112. // 0's.
  113. dependency: 1,
  114. setLineWidth: 2,
  115. setLineCap: 3,
  116. setLineJoin: 4,
  117. setMiterLimit: 5,
  118. setDash: 6,
  119. setRenderingIntent: 7,
  120. setFlatness: 8,
  121. setGState: 9,
  122. save: 10,
  123. restore: 11,
  124. transform: 12,
  125. moveTo: 13,
  126. lineTo: 14,
  127. curveTo: 15,
  128. curveTo2: 16,
  129. curveTo3: 17,
  130. closePath: 18,
  131. rectangle: 19,
  132. stroke: 20,
  133. closeStroke: 21,
  134. fill: 22,
  135. eoFill: 23,
  136. fillStroke: 24,
  137. eoFillStroke: 25,
  138. closeFillStroke: 26,
  139. closeEOFillStroke: 27,
  140. endPath: 28,
  141. clip: 29,
  142. eoClip: 30,
  143. beginText: 31,
  144. endText: 32,
  145. setCharSpacing: 33,
  146. setWordSpacing: 34,
  147. setHScale: 35,
  148. setLeading: 36,
  149. setFont: 37,
  150. setTextRenderingMode: 38,
  151. setTextRise: 39,
  152. moveText: 40,
  153. setLeadingMoveText: 41,
  154. setTextMatrix: 42,
  155. nextLine: 43,
  156. showText: 44,
  157. showSpacedText: 45,
  158. nextLineShowText: 46,
  159. nextLineSetSpacingShowText: 47,
  160. setCharWidth: 48,
  161. setCharWidthAndBounds: 49,
  162. setStrokeColorSpace: 50,
  163. setFillColorSpace: 51,
  164. setStrokeColor: 52,
  165. setStrokeColorN: 53,
  166. setFillColor: 54,
  167. setFillColorN: 55,
  168. setStrokeGray: 56,
  169. setFillGray: 57,
  170. setStrokeRGBColor: 58,
  171. setFillRGBColor: 59,
  172. setStrokeCMYKColor: 60,
  173. setFillCMYKColor: 61,
  174. shadingFill: 62,
  175. beginInlineImage: 63,
  176. beginImageData: 64,
  177. endInlineImage: 65,
  178. paintXObject: 66,
  179. markPoint: 67,
  180. markPointProps: 68,
  181. beginMarkedContent: 69,
  182. beginMarkedContentProps: 70,
  183. endMarkedContent: 71,
  184. beginCompat: 72,
  185. endCompat: 73,
  186. paintFormXObjectBegin: 74,
  187. paintFormXObjectEnd: 75,
  188. beginGroup: 76,
  189. endGroup: 77,
  190. beginAnnotations: 78,
  191. endAnnotations: 79,
  192. beginAnnotation: 80,
  193. endAnnotation: 81,
  194. paintJpegXObject: 82,
  195. paintImageMaskXObject: 83,
  196. paintImageMaskXObjectGroup: 84,
  197. paintImageXObject: 85,
  198. paintInlineImageXObject: 86,
  199. paintInlineImageXObjectGroup: 87,
  200. paintImageXObjectRepeat: 88,
  201. paintImageMaskXObjectRepeat: 89,
  202. paintSolidColorImageMask: 90,
  203. constructPath: 91
  204. };
  205. // A notice for devs. These are good for things that are helpful to devs, such
  206. // as warning that Workers were disabled, which is important to devs but not
  207. // end users.
  208. function info(msg) {
  209. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
  210. console.log('Info: ' + msg);
  211. }
  212. }
  213. // Non-fatal warnings.
  214. function warn(msg) {
  215. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
  216. console.log('Warning: ' + msg);
  217. }
  218. }
  219. // Fatal errors that should trigger the fallback UI and halt execution by
  220. // throwing an exception.
  221. function error(msg) {
  222. // If multiple arguments were passed, pass them all to the log function.
  223. if (arguments.length > 1) {
  224. var logArguments = ['Error:'];
  225. logArguments.push.apply(logArguments, arguments);
  226. console.log.apply(console, logArguments);
  227. // Join the arguments into a single string for the lines below.
  228. msg = [].join.call(arguments, ' ');
  229. } else {
  230. console.log('Error: ' + msg);
  231. }
  232. console.log(backtrace());
  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. return true;
  319. default:
  320. return false;
  321. }
  322. }
  323. PDFJS.isValidUrl = isValidUrl;
  324. function shadow(obj, prop, value) {
  325. Object.defineProperty(obj, prop, { value: value,
  326. enumerable: true,
  327. configurable: true,
  328. writable: false });
  329. return value;
  330. }
  331. var PasswordResponses = PDFJS.PasswordResponses = {
  332. NEED_PASSWORD: 1,
  333. INCORRECT_PASSWORD: 2
  334. };
  335. var PasswordException = (function PasswordExceptionClosure() {
  336. function PasswordException(msg, code) {
  337. this.name = 'PasswordException';
  338. this.message = msg;
  339. this.code = code;
  340. }
  341. PasswordException.prototype = new Error();
  342. PasswordException.constructor = PasswordException;
  343. return PasswordException;
  344. })();
  345. PDFJS.PasswordException = PasswordException;
  346. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  347. function UnknownErrorException(msg, details) {
  348. this.name = 'UnknownErrorException';
  349. this.message = msg;
  350. this.details = details;
  351. }
  352. UnknownErrorException.prototype = new Error();
  353. UnknownErrorException.constructor = UnknownErrorException;
  354. return UnknownErrorException;
  355. })();
  356. PDFJS.UnknownErrorException = UnknownErrorException;
  357. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  358. function InvalidPDFException(msg) {
  359. this.name = 'InvalidPDFException';
  360. this.message = msg;
  361. }
  362. InvalidPDFException.prototype = new Error();
  363. InvalidPDFException.constructor = InvalidPDFException;
  364. return InvalidPDFException;
  365. })();
  366. PDFJS.InvalidPDFException = InvalidPDFException;
  367. var MissingPDFException = (function MissingPDFExceptionClosure() {
  368. function MissingPDFException(msg) {
  369. this.name = 'MissingPDFException';
  370. this.message = msg;
  371. }
  372. MissingPDFException.prototype = new Error();
  373. MissingPDFException.constructor = MissingPDFException;
  374. return MissingPDFException;
  375. })();
  376. PDFJS.MissingPDFException = MissingPDFException;
  377. var UnexpectedResponseException =
  378. (function UnexpectedResponseExceptionClosure() {
  379. function UnexpectedResponseException(msg, status) {
  380. this.name = 'UnexpectedResponseException';
  381. this.message = msg;
  382. this.status = status;
  383. }
  384. UnexpectedResponseException.prototype = new Error();
  385. UnexpectedResponseException.constructor = UnexpectedResponseException;
  386. return UnexpectedResponseException;
  387. })();
  388. PDFJS.UnexpectedResponseException = UnexpectedResponseException;
  389. var NotImplementedException = (function NotImplementedExceptionClosure() {
  390. function NotImplementedException(msg) {
  391. this.message = msg;
  392. }
  393. NotImplementedException.prototype = new Error();
  394. NotImplementedException.prototype.name = 'NotImplementedException';
  395. NotImplementedException.constructor = NotImplementedException;
  396. return NotImplementedException;
  397. })();
  398. var MissingDataException = (function MissingDataExceptionClosure() {
  399. function MissingDataException(begin, end) {
  400. this.begin = begin;
  401. this.end = end;
  402. this.message = 'Missing data [' + begin + ', ' + end + ')';
  403. }
  404. MissingDataException.prototype = new Error();
  405. MissingDataException.prototype.name = 'MissingDataException';
  406. MissingDataException.constructor = MissingDataException;
  407. return MissingDataException;
  408. })();
  409. var XRefParseException = (function XRefParseExceptionClosure() {
  410. function XRefParseException(msg) {
  411. this.message = msg;
  412. }
  413. XRefParseException.prototype = new Error();
  414. XRefParseException.prototype.name = 'XRefParseException';
  415. XRefParseException.constructor = XRefParseException;
  416. return XRefParseException;
  417. })();
  418. function bytesToString(bytes) {
  419. var length = bytes.length;
  420. var MAX_ARGUMENT_COUNT = 8192;
  421. if (length < MAX_ARGUMENT_COUNT) {
  422. return String.fromCharCode.apply(null, bytes);
  423. }
  424. var strBuf = [];
  425. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  426. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  427. var chunk = bytes.subarray(i, chunkEnd);
  428. strBuf.push(String.fromCharCode.apply(null, chunk));
  429. }
  430. return strBuf.join('');
  431. }
  432. function stringToBytes(str) {
  433. var length = str.length;
  434. var bytes = new Uint8Array(length);
  435. for (var i = 0; i < length; ++i) {
  436. bytes[i] = str.charCodeAt(i) & 0xFF;
  437. }
  438. return bytes;
  439. }
  440. function string32(value) {
  441. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  442. (value >> 8) & 0xff, value & 0xff);
  443. }
  444. function log2(x) {
  445. var n = 1, i = 0;
  446. while (x > n) {
  447. n <<= 1;
  448. i++;
  449. }
  450. return i;
  451. }
  452. function readInt8(data, start) {
  453. return (data[start] << 24) >> 24;
  454. }
  455. function readUint16(data, offset) {
  456. return (data[offset] << 8) | data[offset + 1];
  457. }
  458. function readUint32(data, offset) {
  459. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  460. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  461. }
  462. // Lazy test the endianness of the platform
  463. // NOTE: This will be 'true' for simulated TypedArrays
  464. function isLittleEndian() {
  465. var buffer8 = new Uint8Array(2);
  466. buffer8[0] = 1;
  467. var buffer16 = new Uint16Array(buffer8.buffer);
  468. return (buffer16[0] === 1);
  469. }
  470. Object.defineProperty(PDFJS, 'isLittleEndian', {
  471. configurable: true,
  472. get: function PDFJS_isLittleEndian() {
  473. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  474. }
  475. });
  476. // Lazy test if the userAgant support CanvasTypedArrays
  477. function hasCanvasTypedArrays() {
  478. var canvas = document.createElement('canvas');
  479. canvas.width = canvas.height = 1;
  480. var ctx = canvas.getContext('2d');
  481. var imageData = ctx.createImageData(1, 1);
  482. return (typeof imageData.data.buffer !== 'undefined');
  483. }
  484. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  485. configurable: true,
  486. get: function PDFJS_hasCanvasTypedArrays() {
  487. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  488. }
  489. });
  490. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  491. function Uint32ArrayView(buffer, length) {
  492. this.buffer = buffer;
  493. this.byteLength = buffer.length;
  494. this.length = length === undefined ? (this.byteLength >> 2) : length;
  495. ensureUint32ArrayViewProps(this.length);
  496. }
  497. Uint32ArrayView.prototype = Object.create(null);
  498. var uint32ArrayViewSetters = 0;
  499. function createUint32ArrayProp(index) {
  500. return {
  501. get: function () {
  502. var buffer = this.buffer, offset = index << 2;
  503. return (buffer[offset] | (buffer[offset + 1] << 8) |
  504. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  505. },
  506. set: function (value) {
  507. var buffer = this.buffer, offset = index << 2;
  508. buffer[offset] = value & 255;
  509. buffer[offset + 1] = (value >> 8) & 255;
  510. buffer[offset + 2] = (value >> 16) & 255;
  511. buffer[offset + 3] = (value >>> 24) & 255;
  512. }
  513. };
  514. }
  515. function ensureUint32ArrayViewProps(length) {
  516. while (uint32ArrayViewSetters < length) {
  517. Object.defineProperty(Uint32ArrayView.prototype,
  518. uint32ArrayViewSetters,
  519. createUint32ArrayProp(uint32ArrayViewSetters));
  520. uint32ArrayViewSetters++;
  521. }
  522. }
  523. return Uint32ArrayView;
  524. })();
  525. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  526. var Util = PDFJS.Util = (function UtilClosure() {
  527. function Util() {}
  528. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  529. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  530. // creating many intermediate strings.
  531. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  532. rgbBuf[1] = r;
  533. rgbBuf[3] = g;
  534. rgbBuf[5] = b;
  535. return rgbBuf.join('');
  536. };
  537. // Concatenates two transformation matrices together and returns the result.
  538. Util.transform = function Util_transform(m1, m2) {
  539. return [
  540. m1[0] * m2[0] + m1[2] * m2[1],
  541. m1[1] * m2[0] + m1[3] * m2[1],
  542. m1[0] * m2[2] + m1[2] * m2[3],
  543. m1[1] * m2[2] + m1[3] * m2[3],
  544. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  545. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  546. ];
  547. };
  548. // For 2d affine transforms
  549. Util.applyTransform = function Util_applyTransform(p, m) {
  550. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  551. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  552. return [xt, yt];
  553. };
  554. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  555. var d = m[0] * m[3] - m[1] * m[2];
  556. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  557. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  558. return [xt, yt];
  559. };
  560. // Applies the transform to the rectangle and finds the minimum axially
  561. // aligned bounding box.
  562. Util.getAxialAlignedBoundingBox =
  563. function Util_getAxialAlignedBoundingBox(r, m) {
  564. var p1 = Util.applyTransform(r, m);
  565. var p2 = Util.applyTransform(r.slice(2, 4), m);
  566. var p3 = Util.applyTransform([r[0], r[3]], m);
  567. var p4 = Util.applyTransform([r[2], r[1]], m);
  568. return [
  569. Math.min(p1[0], p2[0], p3[0], p4[0]),
  570. Math.min(p1[1], p2[1], p3[1], p4[1]),
  571. Math.max(p1[0], p2[0], p3[0], p4[0]),
  572. Math.max(p1[1], p2[1], p3[1], p4[1])
  573. ];
  574. };
  575. Util.inverseTransform = function Util_inverseTransform(m) {
  576. var d = m[0] * m[3] - m[1] * m[2];
  577. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  578. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  579. };
  580. // Apply a generic 3d matrix M on a 3-vector v:
  581. // | a b c | | X |
  582. // | d e f | x | Y |
  583. // | g h i | | Z |
  584. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  585. // with v as [X,Y,Z]
  586. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  587. return [
  588. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  589. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  590. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  591. ];
  592. };
  593. // This calculation uses Singular Value Decomposition.
  594. // The SVD can be represented with formula A = USV. We are interested in the
  595. // matrix S here because it represents the scale values.
  596. Util.singularValueDecompose2dScale =
  597. function Util_singularValueDecompose2dScale(m) {
  598. var transpose = [m[0], m[2], m[1], m[3]];
  599. // Multiply matrix m with its transpose.
  600. var a = m[0] * transpose[0] + m[1] * transpose[2];
  601. var b = m[0] * transpose[1] + m[1] * transpose[3];
  602. var c = m[2] * transpose[0] + m[3] * transpose[2];
  603. var d = m[2] * transpose[1] + m[3] * transpose[3];
  604. // Solve the second degree polynomial to get roots.
  605. var first = (a + d) / 2;
  606. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  607. var sx = first + second || 1;
  608. var sy = first - second || 1;
  609. // Scale values are the square roots of the eigenvalues.
  610. return [Math.sqrt(sx), Math.sqrt(sy)];
  611. };
  612. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  613. // For coordinate systems whose origin lies in the bottom-left, this
  614. // means normalization to (BL,TR) ordering. For systems with origin in the
  615. // top-left, this means (TL,BR) ordering.
  616. Util.normalizeRect = function Util_normalizeRect(rect) {
  617. var r = rect.slice(0); // clone rect
  618. if (rect[0] > rect[2]) {
  619. r[0] = rect[2];
  620. r[2] = rect[0];
  621. }
  622. if (rect[1] > rect[3]) {
  623. r[1] = rect[3];
  624. r[3] = rect[1];
  625. }
  626. return r;
  627. };
  628. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  629. // intersection of rect1 and rect2. If no intersection, returns 'false'
  630. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  631. Util.intersect = function Util_intersect(rect1, rect2) {
  632. function compare(a, b) {
  633. return a - b;
  634. }
  635. // Order points along the axes
  636. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  637. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  638. result = [];
  639. rect1 = Util.normalizeRect(rect1);
  640. rect2 = Util.normalizeRect(rect2);
  641. // X: first and second points belong to different rectangles?
  642. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  643. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  644. // Intersection must be between second and third points
  645. result[0] = orderedX[1];
  646. result[2] = orderedX[2];
  647. } else {
  648. return false;
  649. }
  650. // Y: first and second points belong to different rectangles?
  651. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  652. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  653. // Intersection must be between second and third points
  654. result[1] = orderedY[1];
  655. result[3] = orderedY[2];
  656. } else {
  657. return false;
  658. }
  659. return result;
  660. };
  661. Util.sign = function Util_sign(num) {
  662. return num < 0 ? -1 : 1;
  663. };
  664. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  665. Array.prototype.push.apply(arr1, arr2);
  666. };
  667. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  668. Array.prototype.unshift.apply(arr1, arr2);
  669. };
  670. Util.extendObj = function extendObj(obj1, obj2) {
  671. for (var key in obj2) {
  672. obj1[key] = obj2[key];
  673. }
  674. };
  675. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  676. name) {
  677. while (dict && !dict.has(name)) {
  678. dict = dict.get('Parent');
  679. }
  680. if (!dict) {
  681. return null;
  682. }
  683. return dict.get(name);
  684. };
  685. Util.inherit = function Util_inherit(sub, base, prototype) {
  686. sub.prototype = Object.create(base.prototype);
  687. sub.prototype.constructor = sub;
  688. for (var prop in prototype) {
  689. sub.prototype[prop] = prototype[prop];
  690. }
  691. };
  692. Util.loadScript = function Util_loadScript(src, callback) {
  693. var script = document.createElement('script');
  694. var loaded = false;
  695. script.setAttribute('src', src);
  696. if (callback) {
  697. script.onload = function() {
  698. if (!loaded) {
  699. callback();
  700. }
  701. loaded = true;
  702. };
  703. }
  704. document.getElementsByTagName('head')[0].appendChild(script);
  705. };
  706. return Util;
  707. })();
  708. /**
  709. * PDF page viewport created based on scale, rotation and offset.
  710. * @class
  711. * @alias PDFJS.PageViewport
  712. */
  713. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  714. /**
  715. * @constructor
  716. * @private
  717. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  718. * @param scale {number} scale of the viewport.
  719. * @param rotation {number} rotations of the viewport in degrees.
  720. * @param offsetX {number} offset X
  721. * @param offsetY {number} offset Y
  722. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  723. */
  724. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  725. this.viewBox = viewBox;
  726. this.scale = scale;
  727. this.rotation = rotation;
  728. this.offsetX = offsetX;
  729. this.offsetY = offsetY;
  730. // creating transform to convert pdf coordinate system to the normal
  731. // canvas like coordinates taking in account scale and rotation
  732. var centerX = (viewBox[2] + viewBox[0]) / 2;
  733. var centerY = (viewBox[3] + viewBox[1]) / 2;
  734. var rotateA, rotateB, rotateC, rotateD;
  735. rotation = rotation % 360;
  736. rotation = rotation < 0 ? rotation + 360 : rotation;
  737. switch (rotation) {
  738. case 180:
  739. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  740. break;
  741. case 90:
  742. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  743. break;
  744. case 270:
  745. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  746. break;
  747. //case 0:
  748. default:
  749. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  750. break;
  751. }
  752. if (dontFlip) {
  753. rotateC = -rotateC; rotateD = -rotateD;
  754. }
  755. var offsetCanvasX, offsetCanvasY;
  756. var width, height;
  757. if (rotateA === 0) {
  758. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  759. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  760. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  761. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  762. } else {
  763. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  764. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  765. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  766. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  767. }
  768. // creating transform for the following operations:
  769. // translate(-centerX, -centerY), rotate and flip vertically,
  770. // scale, and translate(offsetCanvasX, offsetCanvasY)
  771. this.transform = [
  772. rotateA * scale,
  773. rotateB * scale,
  774. rotateC * scale,
  775. rotateD * scale,
  776. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  777. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  778. ];
  779. this.width = width;
  780. this.height = height;
  781. this.fontScale = scale;
  782. }
  783. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  784. /**
  785. * Clones viewport with additional properties.
  786. * @param args {Object} (optional) If specified, may contain the 'scale' or
  787. * 'rotation' properties to override the corresponding properties in
  788. * the cloned viewport.
  789. * @returns {PDFJS.PageViewport} Cloned viewport.
  790. */
  791. clone: function PageViewPort_clone(args) {
  792. args = args || {};
  793. var scale = 'scale' in args ? args.scale : this.scale;
  794. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  795. return new PageViewport(this.viewBox.slice(), scale, rotation,
  796. this.offsetX, this.offsetY, args.dontFlip);
  797. },
  798. /**
  799. * Converts PDF point to the viewport coordinates. For examples, useful for
  800. * converting PDF location into canvas pixel coordinates.
  801. * @param x {number} X coordinate.
  802. * @param y {number} Y coordinate.
  803. * @returns {Object} Object that contains 'x' and 'y' properties of the
  804. * point in the viewport coordinate space.
  805. * @see {@link convertToPdfPoint}
  806. * @see {@link convertToViewportRectangle}
  807. */
  808. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  809. return Util.applyTransform([x, y], this.transform);
  810. },
  811. /**
  812. * Converts PDF rectangle to the viewport coordinates.
  813. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  814. * @returns {Array} Contains corresponding coordinates of the rectangle
  815. * in the viewport coordinate space.
  816. * @see {@link convertToViewportPoint}
  817. */
  818. convertToViewportRectangle:
  819. function PageViewport_convertToViewportRectangle(rect) {
  820. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  821. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  822. return [tl[0], tl[1], br[0], br[1]];
  823. },
  824. /**
  825. * Converts viewport coordinates to the PDF location. For examples, useful
  826. * for converting canvas pixel location into PDF one.
  827. * @param x {number} X coordinate.
  828. * @param y {number} Y coordinate.
  829. * @returns {Object} Object that contains 'x' and 'y' properties of the
  830. * point in the PDF coordinate space.
  831. * @see {@link convertToViewportPoint}
  832. */
  833. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  834. return Util.applyInverseTransform([x, y], this.transform);
  835. }
  836. };
  837. return PageViewport;
  838. })();
  839. var PDFStringTranslateTable = [
  840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  841. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  842. 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,
  843. 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,
  844. 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,
  845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  846. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  847. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  848. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  849. ];
  850. function stringToPDFString(str) {
  851. var i, n = str.length, strBuf = [];
  852. if (str[0] === '\xFE' && str[1] === '\xFF') {
  853. // UTF16BE BOM
  854. for (i = 2; i < n; i += 2) {
  855. strBuf.push(String.fromCharCode(
  856. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  857. }
  858. } else {
  859. for (i = 0; i < n; ++i) {
  860. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  861. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  862. }
  863. }
  864. return strBuf.join('');
  865. }
  866. function stringToUTF8String(str) {
  867. return decodeURIComponent(escape(str));
  868. }
  869. function isEmptyObj(obj) {
  870. for (var key in obj) {
  871. return false;
  872. }
  873. return true;
  874. }
  875. function isBool(v) {
  876. return typeof v === 'boolean';
  877. }
  878. function isInt(v) {
  879. return typeof v === 'number' && ((v | 0) === v);
  880. }
  881. function isNum(v) {
  882. return typeof v === 'number';
  883. }
  884. function isString(v) {
  885. return typeof v === 'string';
  886. }
  887. function isNull(v) {
  888. return v === null;
  889. }
  890. function isName(v) {
  891. return v instanceof Name;
  892. }
  893. function isCmd(v, cmd) {
  894. return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
  895. }
  896. function isDict(v, type) {
  897. if (!(v instanceof Dict)) {
  898. return false;
  899. }
  900. if (!type) {
  901. return true;
  902. }
  903. var dictType = v.get('Type');
  904. return isName(dictType) && dictType.name === type;
  905. }
  906. function isArray(v) {
  907. return v instanceof Array;
  908. }
  909. function isStream(v) {
  910. return typeof v === 'object' && v !== null && v.getBytes !== undefined;
  911. }
  912. function isArrayBuffer(v) {
  913. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  914. }
  915. function isRef(v) {
  916. return v instanceof Ref;
  917. }
  918. /**
  919. * Promise Capability object.
  920. *
  921. * @typedef {Object} PromiseCapability
  922. * @property {Promise} promise - A promise object.
  923. * @property {function} resolve - Fullfills the promise.
  924. * @property {function} reject - Rejects the promise.
  925. */
  926. /**
  927. * Creates a promise capability object.
  928. * @alias PDFJS.createPromiseCapability
  929. *
  930. * @return {PromiseCapability} A capability object contains:
  931. * - a Promise, resolve and reject methods.
  932. */
  933. function createPromiseCapability() {
  934. var capability = {};
  935. capability.promise = new Promise(function (resolve, reject) {
  936. capability.resolve = resolve;
  937. capability.reject = reject;
  938. });
  939. return capability;
  940. }
  941. PDFJS.createPromiseCapability = createPromiseCapability;
  942. /**
  943. * Polyfill for Promises:
  944. * The following promise implementation tries to generally implement the
  945. * Promise/A+ spec. Some notable differences from other promise libaries are:
  946. * - There currently isn't a seperate deferred and promise object.
  947. * - Unhandled rejections eventually show an error if they aren't handled.
  948. *
  949. * Based off of the work in:
  950. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  951. */
  952. (function PromiseClosure() {
  953. if (globalScope.Promise) {
  954. // Promises existing in the DOM/Worker, checking presence of all/resolve
  955. if (typeof globalScope.Promise.all !== 'function') {
  956. globalScope.Promise.all = function (iterable) {
  957. var count = 0, results = [], resolve, reject;
  958. var promise = new globalScope.Promise(function (resolve_, reject_) {
  959. resolve = resolve_;
  960. reject = reject_;
  961. });
  962. iterable.forEach(function (p, i) {
  963. count++;
  964. p.then(function (result) {
  965. results[i] = result;
  966. count--;
  967. if (count === 0) {
  968. resolve(results);
  969. }
  970. }, reject);
  971. });
  972. if (count === 0) {
  973. resolve(results);
  974. }
  975. return promise;
  976. };
  977. }
  978. if (typeof globalScope.Promise.resolve !== 'function') {
  979. globalScope.Promise.resolve = function (value) {
  980. return new globalScope.Promise(function (resolve) { resolve(value); });
  981. };
  982. }
  983. if (typeof globalScope.Promise.reject !== 'function') {
  984. globalScope.Promise.reject = function (reason) {
  985. return new globalScope.Promise(function (resolve, reject) {
  986. reject(reason);
  987. });
  988. };
  989. }
  990. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  991. globalScope.Promise.prototype.catch = function (onReject) {
  992. return globalScope.Promise.prototype.then(undefined, onReject);
  993. };
  994. }
  995. return;
  996. }
  997. var STATUS_PENDING = 0;
  998. var STATUS_RESOLVED = 1;
  999. var STATUS_REJECTED = 2;
  1000. // In an attempt to avoid silent exceptions, unhandled rejections are
  1001. // tracked and if they aren't handled in a certain amount of time an
  1002. // error is logged.
  1003. var REJECTION_TIMEOUT = 500;
  1004. var HandlerManager = {
  1005. handlers: [],
  1006. running: false,
  1007. unhandledRejections: [],
  1008. pendingRejectionCheck: false,
  1009. scheduleHandlers: function scheduleHandlers(promise) {
  1010. if (promise._status === STATUS_PENDING) {
  1011. return;
  1012. }
  1013. this.handlers = this.handlers.concat(promise._handlers);
  1014. promise._handlers = [];
  1015. if (this.running) {
  1016. return;
  1017. }
  1018. this.running = true;
  1019. setTimeout(this.runHandlers.bind(this), 0);
  1020. },
  1021. runHandlers: function runHandlers() {
  1022. var RUN_TIMEOUT = 1; // ms
  1023. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1024. while (this.handlers.length > 0) {
  1025. var handler = this.handlers.shift();
  1026. var nextStatus = handler.thisPromise._status;
  1027. var nextValue = handler.thisPromise._value;
  1028. try {
  1029. if (nextStatus === STATUS_RESOLVED) {
  1030. if (typeof handler.onResolve === 'function') {
  1031. nextValue = handler.onResolve(nextValue);
  1032. }
  1033. } else if (typeof handler.onReject === 'function') {
  1034. nextValue = handler.onReject(nextValue);
  1035. nextStatus = STATUS_RESOLVED;
  1036. if (handler.thisPromise._unhandledRejection) {
  1037. this.removeUnhandeledRejection(handler.thisPromise);
  1038. }
  1039. }
  1040. } catch (ex) {
  1041. nextStatus = STATUS_REJECTED;
  1042. nextValue = ex;
  1043. }
  1044. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1045. if (Date.now() >= timeoutAt) {
  1046. break;
  1047. }
  1048. }
  1049. if (this.handlers.length > 0) {
  1050. setTimeout(this.runHandlers.bind(this), 0);
  1051. return;
  1052. }
  1053. this.running = false;
  1054. },
  1055. addUnhandledRejection: function addUnhandledRejection(promise) {
  1056. this.unhandledRejections.push({
  1057. promise: promise,
  1058. time: Date.now()
  1059. });
  1060. this.scheduleRejectionCheck();
  1061. },
  1062. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1063. promise._unhandledRejection = false;
  1064. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1065. if (this.unhandledRejections[i].promise === promise) {
  1066. this.unhandledRejections.splice(i);
  1067. i--;
  1068. }
  1069. }
  1070. },
  1071. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1072. if (this.pendingRejectionCheck) {
  1073. return;
  1074. }
  1075. this.pendingRejectionCheck = true;
  1076. setTimeout(function rejectionCheck() {
  1077. this.pendingRejectionCheck = false;
  1078. var now = Date.now();
  1079. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1080. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1081. var unhandled = this.unhandledRejections[i].promise._value;
  1082. var msg = 'Unhandled rejection: ' + unhandled;
  1083. if (unhandled.stack) {
  1084. msg += '\n' + unhandled.stack;
  1085. }
  1086. warn(msg);
  1087. this.unhandledRejections.splice(i);
  1088. i--;
  1089. }
  1090. }
  1091. if (this.unhandledRejections.length) {
  1092. this.scheduleRejectionCheck();
  1093. }
  1094. }.bind(this), REJECTION_TIMEOUT);
  1095. }
  1096. };
  1097. function Promise(resolver) {
  1098. this._status = STATUS_PENDING;
  1099. this._handlers = [];
  1100. try {
  1101. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1102. } catch (e) {
  1103. this._reject(e);
  1104. }
  1105. }
  1106. /**
  1107. * Builds a promise that is resolved when all the passed in promises are
  1108. * resolved.
  1109. * @param {array} array of data and/or promises to wait for.
  1110. * @return {Promise} New dependant promise.
  1111. */
  1112. Promise.all = function Promise_all(promises) {
  1113. var resolveAll, rejectAll;
  1114. var deferred = new Promise(function (resolve, reject) {
  1115. resolveAll = resolve;
  1116. rejectAll = reject;
  1117. });
  1118. var unresolved = promises.length;
  1119. var results = [];
  1120. if (unresolved === 0) {
  1121. resolveAll(results);
  1122. return deferred;
  1123. }
  1124. function reject(reason) {
  1125. if (deferred._status === STATUS_REJECTED) {
  1126. return;
  1127. }
  1128. results = [];
  1129. rejectAll(reason);
  1130. }
  1131. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1132. var promise = promises[i];
  1133. var resolve = (function(i) {
  1134. return function(value) {
  1135. if (deferred._status === STATUS_REJECTED) {
  1136. return;
  1137. }
  1138. results[i] = value;
  1139. unresolved--;
  1140. if (unresolved === 0) {
  1141. resolveAll(results);
  1142. }
  1143. };
  1144. })(i);
  1145. if (Promise.isPromise(promise)) {
  1146. promise.then(resolve, reject);
  1147. } else {
  1148. resolve(promise);
  1149. }
  1150. }
  1151. return deferred;
  1152. };
  1153. /**
  1154. * Checks if the value is likely a promise (has a 'then' function).
  1155. * @return {boolean} true if value is thenable
  1156. */
  1157. Promise.isPromise = function Promise_isPromise(value) {
  1158. return value && typeof value.then === 'function';
  1159. };
  1160. /**
  1161. * Creates resolved promise
  1162. * @param value resolve value
  1163. * @returns {Promise}
  1164. */
  1165. Promise.resolve = function Promise_resolve(value) {
  1166. return new Promise(function (resolve) { resolve(value); });
  1167. };
  1168. /**
  1169. * Creates rejected promise
  1170. * @param reason rejection value
  1171. * @returns {Promise}
  1172. */
  1173. Promise.reject = function Promise_reject(reason) {
  1174. return new Promise(function (resolve, reject) { reject(reason); });
  1175. };
  1176. Promise.prototype = {
  1177. _status: null,
  1178. _value: null,
  1179. _handlers: null,
  1180. _unhandledRejection: null,
  1181. _updateStatus: function Promise__updateStatus(status, value) {
  1182. if (this._status === STATUS_RESOLVED ||
  1183. this._status === STATUS_REJECTED) {
  1184. return;
  1185. }
  1186. if (status === STATUS_RESOLVED &&
  1187. Promise.isPromise(value)) {
  1188. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1189. this._updateStatus.bind(this, STATUS_REJECTED));
  1190. return;
  1191. }
  1192. this._status = status;
  1193. this._value = value;
  1194. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1195. this._unhandledRejection = true;
  1196. HandlerManager.addUnhandledRejection(this);
  1197. }
  1198. HandlerManager.scheduleHandlers(this);
  1199. },
  1200. _resolve: function Promise_resolve(value) {
  1201. this._updateStatus(STATUS_RESOLVED, value);
  1202. },
  1203. _reject: function Promise_reject(reason) {
  1204. this._updateStatus(STATUS_REJECTED, reason);
  1205. },
  1206. then: function Promise_then(onResolve, onReject) {
  1207. var nextPromise = new Promise(function (resolve, reject) {
  1208. this.resolve = resolve;
  1209. this.reject = reject;
  1210. });
  1211. this._handlers.push({
  1212. thisPromise: this,
  1213. onResolve: onResolve,
  1214. onReject: onReject,
  1215. nextPromise: nextPromise
  1216. });
  1217. HandlerManager.scheduleHandlers(this);
  1218. return nextPromise;
  1219. },
  1220. catch: function Promise_catch(onReject) {
  1221. return this.then(undefined, onReject);
  1222. }
  1223. };
  1224. globalScope.Promise = Promise;
  1225. })();
  1226. var StatTimer = (function StatTimerClosure() {
  1227. function rpad(str, pad, length) {
  1228. while (str.length < length) {
  1229. str += pad;
  1230. }
  1231. return str;
  1232. }
  1233. function StatTimer() {
  1234. this.started = {};
  1235. this.times = [];
  1236. this.enabled = true;
  1237. }
  1238. StatTimer.prototype = {
  1239. time: function StatTimer_time(name) {
  1240. if (!this.enabled) {
  1241. return;
  1242. }
  1243. if (name in this.started) {
  1244. warn('Timer is already running for ' + name);
  1245. }
  1246. this.started[name] = Date.now();
  1247. },
  1248. timeEnd: function StatTimer_timeEnd(name) {
  1249. if (!this.enabled) {
  1250. return;
  1251. }
  1252. if (!(name in this.started)) {
  1253. warn('Timer has not been started for ' + name);
  1254. }
  1255. this.times.push({
  1256. 'name': name,
  1257. 'start': this.started[name],
  1258. 'end': Date.now()
  1259. });
  1260. // Remove timer from started so it can be called again.
  1261. delete this.started[name];
  1262. },
  1263. toString: function StatTimer_toString() {
  1264. var i, ii;
  1265. var times = this.times;
  1266. var out = '';
  1267. // Find the longest name for padding purposes.
  1268. var longest = 0;
  1269. for (i = 0, ii = times.length; i < ii; ++i) {
  1270. var name = times[i]['name'];
  1271. if (name.length > longest) {
  1272. longest = name.length;
  1273. }
  1274. }
  1275. for (i = 0, ii = times.length; i < ii; ++i) {
  1276. var span = times[i];
  1277. var duration = span.end - span.start;
  1278. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1279. }
  1280. return out;
  1281. }
  1282. };
  1283. return StatTimer;
  1284. })();
  1285. PDFJS.createBlob = function createBlob(data, contentType) {
  1286. if (typeof Blob !== 'undefined') {
  1287. return new Blob([data], { type: contentType });
  1288. }
  1289. // Blob builder is deprecated in FF14 and removed in FF18.
  1290. var bb = new MozBlobBuilder();
  1291. bb.append(data);
  1292. return bb.getBlob(contentType);
  1293. };
  1294. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1295. // Blob/createObjectURL is not available, falling back to data schema.
  1296. var digits =
  1297. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1298. return function createObjectURL(data, contentType) {
  1299. if (!PDFJS.disableCreateObjectURL &&
  1300. typeof URL !== 'undefined' && URL.createObjectURL) {
  1301. var blob = PDFJS.createBlob(data, contentType);
  1302. return URL.createObjectURL(blob);
  1303. }
  1304. var buffer = 'data:' + contentType + ';base64,';
  1305. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1306. var b1 = data[i] & 0xFF;
  1307. var b2 = data[i + 1] & 0xFF;
  1308. var b3 = data[i + 2] & 0xFF;
  1309. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1310. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1311. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1312. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1313. }
  1314. return buffer;
  1315. };
  1316. })();
  1317. function MessageHandler(name, comObj) {
  1318. this.name = name;
  1319. this.comObj = comObj;
  1320. this.callbackIndex = 1;
  1321. this.postMessageTransfers = true;
  1322. var callbacksCapabilities = this.callbacksCapabilities = {};
  1323. var ah = this.actionHandler = {};
  1324. ah['console_log'] = [function ahConsoleLog(data) {
  1325. console.log.apply(console, data);
  1326. }];
  1327. ah['console_error'] = [function ahConsoleError(data) {
  1328. console.error.apply(console, data);
  1329. }];
  1330. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1331. UnsupportedManager.notify(data);
  1332. }];
  1333. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1334. var data = event.data;
  1335. if (data.isReply) {
  1336. var callbackId = data.callbackId;
  1337. if (data.callbackId in callbacksCapabilities) {
  1338. var callback = callbacksCapabilities[callbackId];
  1339. delete callbacksCapabilities[callbackId];
  1340. if ('error' in data) {
  1341. callback.reject(data.error);
  1342. } else {
  1343. callback.resolve(data.data);
  1344. }
  1345. } else {
  1346. error('Cannot resolve callback ' + callbackId);
  1347. }
  1348. } else if (data.action in ah) {
  1349. var action = ah[data.action];
  1350. if (data.callbackId) {
  1351. Promise.resolve().then(function () {
  1352. return action[0].call(action[1], data.data);
  1353. }).then(function (result) {
  1354. comObj.postMessage({
  1355. isReply: true,
  1356. callbackId: data.callbackId,
  1357. data: result
  1358. });
  1359. }, function (reason) {
  1360. comObj.postMessage({
  1361. isReply: true,
  1362. callbackId: data.callbackId,
  1363. error: reason
  1364. });
  1365. });
  1366. } else {
  1367. action[0].call(action[1], data.data);
  1368. }
  1369. } else {
  1370. error('Unknown action from worker: ' + data.action);
  1371. }
  1372. };
  1373. }
  1374. MessageHandler.prototype = {
  1375. on: function messageHandlerOn(actionName, handler, scope) {
  1376. var ah = this.actionHandler;
  1377. if (ah[actionName]) {
  1378. error('There is already an actionName called "' + actionName + '"');
  1379. }
  1380. ah[actionName] = [handler, scope];
  1381. },
  1382. /**
  1383. * Sends a message to the comObj to invoke the action with the supplied data.
  1384. * @param {String} actionName Action to call.
  1385. * @param {JSON} data JSON data to send.
  1386. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1387. */
  1388. send: function messageHandlerSend(actionName, data, transfers) {
  1389. var message = {
  1390. action: actionName,
  1391. data: data
  1392. };
  1393. this.postMessage(message, transfers);
  1394. },
  1395. /**
  1396. * Sends a message to the comObj to invoke the action with the supplied data.
  1397. * Expects that other side will callback with the response.
  1398. * @param {String} actionName Action to call.
  1399. * @param {JSON} data JSON data to send.
  1400. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1401. * @returns {Promise} Promise to be resolved with response data.
  1402. */
  1403. sendWithPromise:
  1404. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1405. var callbackId = this.callbackIndex++;
  1406. var message = {
  1407. action: actionName,
  1408. data: data,
  1409. callbackId: callbackId
  1410. };
  1411. var capability = createPromiseCapability();
  1412. this.callbacksCapabilities[callbackId] = capability;
  1413. try {
  1414. this.postMessage(message, transfers);
  1415. } catch (e) {
  1416. capability.reject(e);
  1417. }
  1418. return capability.promise;
  1419. },
  1420. /**
  1421. * Sends raw message to the comObj.
  1422. * @private
  1423. * @param message {Object} Raw message.
  1424. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1425. */
  1426. postMessage: function (message, transfers) {
  1427. if (transfers && this.postMessageTransfers) {
  1428. this.comObj.postMessage(message, transfers);
  1429. } else {
  1430. this.comObj.postMessage(message);
  1431. }
  1432. }
  1433. };
  1434. function loadJpegStream(id, imageUrl, objs) {
  1435. var img = new Image();
  1436. img.onload = (function loadJpegStream_onloadClosure() {
  1437. objs.resolve(id, img);
  1438. });
  1439. img.onerror = (function loadJpegStream_onerrorClosure() {
  1440. objs.resolve(id, null);
  1441. warn('Error during JPEG image loading');
  1442. });
  1443. img.src = imageUrl;
  1444. }
  1445. /**
  1446. * The maximum allowed image size in total pixels e.g. width * height. Images
  1447. * above this value will not be drawn. Use -1 for no limit.
  1448. * @var {number}
  1449. */
  1450. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  1451. -1 : PDFJS.maxImageSize);
  1452. /**
  1453. * The url of where the predefined Adobe CMaps are located. Include trailing
  1454. * slash.
  1455. * @var {string}
  1456. */
  1457. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  1458. /**
  1459. * Specifies if CMaps are binary packed.
  1460. * @var {boolean}
  1461. */
  1462. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  1463. /*
  1464. * By default fonts are converted to OpenType fonts and loaded via font face
  1465. * rules. If disabled, the font will be rendered using a built in font renderer
  1466. * that constructs the glyphs with primitive path commands.
  1467. * @var {boolean}
  1468. */
  1469. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  1470. false : PDFJS.disableFontFace);
  1471. /**
  1472. * Path for image resources, mainly for annotation icons. Include trailing
  1473. * slash.
  1474. * @var {string}
  1475. */
  1476. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  1477. '' : PDFJS.imageResourcesPath);
  1478. /**
  1479. * Disable the web worker and run all code on the main thread. This will happen
  1480. * automatically if the browser doesn't support workers or sending typed arrays
  1481. * to workers.
  1482. * @var {boolean}
  1483. */
  1484. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  1485. false : PDFJS.disableWorker);
  1486. /**
  1487. * Path and filename of the worker file. Required when the worker is enabled in
  1488. * development mode. If unspecified in the production build, the worker will be
  1489. * loaded based on the location of the pdf.js file.
  1490. * @var {string}
  1491. */
  1492. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  1493. /**
  1494. * Disable range request loading of PDF files. When enabled and if the server
  1495. * supports partial content requests then the PDF will be fetched in chunks.
  1496. * Enabled (false) by default.
  1497. * @var {boolean}
  1498. */
  1499. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  1500. false : PDFJS.disableRange);
  1501. /**
  1502. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  1503. * in chunks. This default behavior can be disabled.
  1504. * @var {boolean}
  1505. */
  1506. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  1507. false : PDFJS.disableStream);
  1508. /**
  1509. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  1510. * will automatically keep fetching more data even if it isn't needed to display
  1511. * the current page. This default behavior can be disabled.
  1512. * @var {boolean}
  1513. */
  1514. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  1515. false : PDFJS.disableAutoFetch);
  1516. /**
  1517. * Enables special hooks for debugging PDF.js.
  1518. * @var {boolean}
  1519. */
  1520. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  1521. /**
  1522. * Enables transfer usage in postMessage for ArrayBuffers.
  1523. * @var {boolean}
  1524. */
  1525. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  1526. true : PDFJS.postMessageTransfers);
  1527. /**
  1528. * Disables URL.createObjectURL usage.
  1529. * @var {boolean}
  1530. */
  1531. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  1532. false : PDFJS.disableCreateObjectURL);
  1533. /**
  1534. * Disables WebGL usage.
  1535. * @var {boolean}
  1536. */
  1537. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  1538. true : PDFJS.disableWebGL);
  1539. /**
  1540. * Enables CSS only zooming.
  1541. * @var {boolean}
  1542. */
  1543. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  1544. false : PDFJS.useOnlyCssZoom);
  1545. /**
  1546. * Controls the logging level.
  1547. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  1548. * - errors
  1549. * - warnings [default]
  1550. * - infos
  1551. * @var {number}
  1552. */
  1553. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  1554. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  1555. /**
  1556. * The maximum supported canvas size in total pixels e.g. width * height.
  1557. * The default value is 4096 * 4096. Use -1 for no limit.
  1558. * @var {number}
  1559. */
  1560. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  1561. 16777216 : PDFJS.maxCanvasPixels);
  1562. /**
  1563. * Document initialization / loading parameters object.
  1564. *
  1565. * @typedef {Object} DocumentInitParameters
  1566. * @property {string} url - The URL of the PDF.
  1567. * @property {TypedArray} data - A typed array with PDF data.
  1568. * @property {Object} httpHeaders - Basic authentication headers.
  1569. * @property {boolean} withCredentials - Indicates whether or not cross-site
  1570. * Access-Control requests should be made using credentials such as cookies
  1571. * or authorization headers. The default is false.
  1572. * @property {string} password - For decrypting password-protected PDFs.
  1573. * @property {TypedArray} initialData - A typed array with the first portion or
  1574. * all of the pdf data. Used by the extension since some data is already
  1575. * loaded before the switch to range requests.
  1576. */
  1577. /**
  1578. * @typedef {Object} PDFDocumentStats
  1579. * @property {Array} streamTypes - Used stream types in the document (an item
  1580. * is set to true if specific stream ID was used in the document).
  1581. * @property {Array} fontTypes - Used font type in the document (an item is set
  1582. * to true if specific font ID was used in the document).
  1583. */
  1584. /**
  1585. * This is the main entry point for loading a PDF and interacting with it.
  1586. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  1587. * is used, which means it must follow the same origin rules that any XHR does
  1588. * e.g. No cross domain requests without CORS.
  1589. *
  1590. * @param {string|TypedArray|DocumentInitParameters} source Can be a url to
  1591. * where a PDF is located, a typed array (Uint8Array) already populated with
  1592. * data or parameter object.
  1593. *
  1594. * @param {Object} pdfDataRangeTransport is optional. It is used if you want
  1595. * to manually serve range requests for data in the PDF. See viewer.js for
  1596. * an example of pdfDataRangeTransport's interface.
  1597. *
  1598. * @param {function} passwordCallback is optional. It is used to request a
  1599. * password if wrong or no password was provided. The callback receives two
  1600. * parameters: function that needs to be called with new password and reason
  1601. * (see {PasswordResponses}).
  1602. *
  1603. * @param {function} progressCallback is optional. It is used to be able to
  1604. * monitor the loading progress of the PDF file (necessary to implement e.g.
  1605. * a loading bar). The callback receives an {Object} with the properties:
  1606. * {number} loaded and {number} total.
  1607. *
  1608. * @return {Promise} A promise that is resolved with {@link PDFDocumentProxy}
  1609. * object.
  1610. */
  1611. PDFJS.getDocument = function getDocument(source,
  1612. pdfDataRangeTransport,
  1613. passwordCallback,
  1614. progressCallback) {
  1615. var workerInitializedCapability, workerReadyCapability, transport;
  1616. if (typeof source === 'string') {
  1617. source = { url: source };
  1618. } else if (isArrayBuffer(source)) {
  1619. source = { data: source };
  1620. } else if (typeof source !== 'object') {
  1621. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  1622. 'string or a parameter object');
  1623. }
  1624. if (!source.url && !source.data) {
  1625. error('Invalid parameter array, need either .data or .url');
  1626. }
  1627. // copy/use all keys as is except 'url' -- full path is required
  1628. var params = {};
  1629. for (var key in source) {
  1630. if (key === 'url' && typeof window !== 'undefined') {
  1631. params[key] = combineUrl(window.location.href, source[key]);
  1632. continue;
  1633. }
  1634. params[key] = source[key];
  1635. }
  1636. workerInitializedCapability = createPromiseCapability();
  1637. workerReadyCapability = createPromiseCapability();
  1638. transport = new WorkerTransport(workerInitializedCapability,
  1639. workerReadyCapability, pdfDataRangeTransport,
  1640. progressCallback);
  1641. workerInitializedCapability.promise.then(function transportInitialized() {
  1642. transport.passwordCallback = passwordCallback;
  1643. transport.fetchDocument(params);
  1644. });
  1645. return workerReadyCapability.promise;
  1646. };
  1647. /**
  1648. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  1649. * properties that can be read synchronously.
  1650. * @class
  1651. */
  1652. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  1653. function PDFDocumentProxy(pdfInfo, transport) {
  1654. this.pdfInfo = pdfInfo;
  1655. this.transport = transport;
  1656. }
  1657. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  1658. /**
  1659. * @return {number} Total number of pages the PDF contains.
  1660. */
  1661. get numPages() {
  1662. return this.pdfInfo.numPages;
  1663. },
  1664. /**
  1665. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  1666. * unique.
  1667. */
  1668. get fingerprint() {
  1669. return this.pdfInfo.fingerprint;
  1670. },
  1671. /**
  1672. * @param {number} pageNumber The page number to get. The first page is 1.
  1673. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  1674. * object.
  1675. */
  1676. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  1677. return this.transport.getPage(pageNumber);
  1678. },
  1679. /**
  1680. * @param {{num: number, gen: number}} ref The page reference. Must have
  1681. * the 'num' and 'gen' properties.
  1682. * @return {Promise} A promise that is resolved with the page index that is
  1683. * associated with the reference.
  1684. */
  1685. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  1686. return this.transport.getPageIndex(ref);
  1687. },
  1688. /**
  1689. * @return {Promise} A promise that is resolved with a lookup table for
  1690. * mapping named destinations to reference numbers.
  1691. *
  1692. * This can be slow for large documents: use getDestination instead
  1693. */
  1694. getDestinations: function PDFDocumentProxy_getDestinations() {
  1695. return this.transport.getDestinations();
  1696. },
  1697. /**
  1698. * @param {string} id The named destination to get.
  1699. * @return {Promise} A promise that is resolved with all information
  1700. * of the given named destination.
  1701. */
  1702. getDestination: function PDFDocumentProxy_getDestination(id) {
  1703. return this.transport.getDestination(id);
  1704. },
  1705. /**
  1706. * @return {Promise} A promise that is resolved with a lookup table for
  1707. * mapping named attachments to their content.
  1708. */
  1709. getAttachments: function PDFDocumentProxy_getAttachments() {
  1710. return this.transport.getAttachments();
  1711. },
  1712. /**
  1713. * @return {Promise} A promise that is resolved with an array of all the
  1714. * JavaScript strings in the name tree.
  1715. */
  1716. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  1717. return this.transport.getJavaScript();
  1718. },
  1719. /**
  1720. * @return {Promise} A promise that is resolved with an {Array} that is a
  1721. * tree outline (if it has one) of the PDF. The tree is in the format of:
  1722. * [
  1723. * {
  1724. * title: string,
  1725. * bold: boolean,
  1726. * italic: boolean,
  1727. * color: rgb array,
  1728. * dest: dest obj,
  1729. * items: array of more items like this
  1730. * },
  1731. * ...
  1732. * ].
  1733. */
  1734. getOutline: function PDFDocumentProxy_getOutline() {
  1735. return this.transport.getOutline();
  1736. },
  1737. /**
  1738. * @return {Promise} A promise that is resolved with an {Object} that has
  1739. * info and metadata properties. Info is an {Object} filled with anything
  1740. * available in the information dictionary and similarly metadata is a
  1741. * {Metadata} object with information from the metadata section of the PDF.
  1742. */
  1743. getMetadata: function PDFDocumentProxy_getMetadata() {
  1744. return this.transport.getMetadata();
  1745. },
  1746. /**
  1747. * @return {Promise} A promise that is resolved with a TypedArray that has
  1748. * the raw data from the PDF.
  1749. */
  1750. getData: function PDFDocumentProxy_getData() {
  1751. return this.transport.getData();
  1752. },
  1753. /**
  1754. * @return {Promise} A promise that is resolved when the document's data
  1755. * is loaded. It is resolved with an {Object} that contains the length
  1756. * property that indicates size of the PDF data in bytes.
  1757. */
  1758. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  1759. return this.transport.downloadInfoCapability.promise;
  1760. },
  1761. /**
  1762. * @returns {Promise} A promise this is resolved with current stats about
  1763. * document structures (see {@link PDFDocumentStats}).
  1764. */
  1765. getStats: function PDFDocumentProxy_getStats() {
  1766. return this.transport.getStats();
  1767. },
  1768. /**
  1769. * Cleans up resources allocated by the document, e.g. created @font-face.
  1770. */
  1771. cleanup: function PDFDocumentProxy_cleanup() {
  1772. this.transport.startCleanup();
  1773. },
  1774. /**
  1775. * Destroys current document instance and terminates worker.
  1776. */
  1777. destroy: function PDFDocumentProxy_destroy() {
  1778. this.transport.destroy();
  1779. }
  1780. };
  1781. return PDFDocumentProxy;
  1782. })();
  1783. /**
  1784. * Page text content.
  1785. *
  1786. * @typedef {Object} TextContent
  1787. * @property {array} items - array of {@link TextItem}
  1788. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  1789. * name.
  1790. */
  1791. /**
  1792. * Page text content part.
  1793. *
  1794. * @typedef {Object} TextItem
  1795. * @property {string} str - text content.
  1796. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  1797. * @property {array} transform - transformation matrix.
  1798. * @property {number} width - width in device space.
  1799. * @property {number} height - height in device space.
  1800. * @property {string} fontName - font name used by pdf.js for converted font.
  1801. */
  1802. /**
  1803. * Text style.
  1804. *
  1805. * @typedef {Object} TextStyle
  1806. * @property {number} ascent - font ascent.
  1807. * @property {number} descent - font descent.
  1808. * @property {boolean} vertical - text is in vertical mode.
  1809. * @property {string} fontFamily - possible font family
  1810. */
  1811. /**
  1812. * Page render parameters.
  1813. *
  1814. * @typedef {Object} RenderParameters
  1815. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  1816. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  1817. * calling of PDFPage.getViewport method.
  1818. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  1819. * (default value is 'display').
  1820. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  1821. * endLayout and appendImage functions.
  1822. * @property {function} continueCallback - (optional) A function that will be
  1823. * called each time the rendering is paused. To continue
  1824. * rendering call the function that is the first argument
  1825. * to the callback.
  1826. */
  1827. /**
  1828. * PDF page operator list.
  1829. *
  1830. * @typedef {Object} PDFOperatorList
  1831. * @property {Array} fnArray - Array containing the operator functions.
  1832. * @property {Array} argsArray - Array containing the arguments of the
  1833. * functions.
  1834. */
  1835. /**
  1836. * Proxy to a PDFPage in the worker thread.
  1837. * @class
  1838. */
  1839. var PDFPageProxy = (function PDFPageProxyClosure() {
  1840. function PDFPageProxy(pageIndex, pageInfo, transport) {
  1841. this.pageIndex = pageIndex;
  1842. this.pageInfo = pageInfo;
  1843. this.transport = transport;
  1844. this.stats = new StatTimer();
  1845. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  1846. this.commonObjs = transport.commonObjs;
  1847. this.objs = new PDFObjects();
  1848. this.cleanupAfterRender = false;
  1849. this.pendingDestroy = false;
  1850. this.intentStates = {};
  1851. }
  1852. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  1853. /**
  1854. * @return {number} Page number of the page. First page is 1.
  1855. */
  1856. get pageNumber() {
  1857. return this.pageIndex + 1;
  1858. },
  1859. /**
  1860. * @return {number} The number of degrees the page is rotated clockwise.
  1861. */
  1862. get rotate() {
  1863. return this.pageInfo.rotate;
  1864. },
  1865. /**
  1866. * @return {Object} The reference that points to this page. It has 'num' and
  1867. * 'gen' properties.
  1868. */
  1869. get ref() {
  1870. return this.pageInfo.ref;
  1871. },
  1872. /**
  1873. * @return {Array} An array of the visible portion of the PDF page in the
  1874. * user space units - [x1, y1, x2, y2].
  1875. */
  1876. get view() {
  1877. return this.pageInfo.view;
  1878. },
  1879. /**
  1880. * @param {number} scale The desired scale of the viewport.
  1881. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  1882. * defaults to the page rotation.
  1883. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  1884. * along with transforms required for rendering.
  1885. */
  1886. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  1887. if (arguments.length < 2) {
  1888. rotate = this.rotate;
  1889. }
  1890. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  1891. },
  1892. /**
  1893. * @return {Promise} A promise that is resolved with an {Array} of the
  1894. * annotation objects.
  1895. */
  1896. getAnnotations: function PDFPageProxy_getAnnotations() {
  1897. if (this.annotationsPromise) {
  1898. return this.annotationsPromise;
  1899. }
  1900. var promise = this.transport.getAnnotations(this.pageIndex);
  1901. this.annotationsPromise = promise;
  1902. return promise;
  1903. },
  1904. /**
  1905. * Begins the process of rendering a page to the desired context.
  1906. * @param {RenderParameters} params Page render parameters.
  1907. * @return {RenderTask} An object that contains the promise, which
  1908. * is resolved when the page finishes rendering.
  1909. */
  1910. render: function PDFPageProxy_render(params) {
  1911. var stats = this.stats;
  1912. stats.time('Overall');
  1913. // If there was a pending destroy cancel it so no cleanup happens during
  1914. // this call to render.
  1915. this.pendingDestroy = false;
  1916. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  1917. if (!this.intentStates[renderingIntent]) {
  1918. this.intentStates[renderingIntent] = {};
  1919. }
  1920. var intentState = this.intentStates[renderingIntent];
  1921. // If there's no displayReadyCapability yet, then the operatorList
  1922. // was never requested before. Make the request and create the promise.
  1923. if (!intentState.displayReadyCapability) {
  1924. intentState.receivingOperatorList = true;
  1925. intentState.displayReadyCapability = createPromiseCapability();
  1926. intentState.operatorList = {
  1927. fnArray: [],
  1928. argsArray: [],
  1929. lastChunk: false
  1930. };
  1931. this.stats.time('Page Request');
  1932. this.transport.messageHandler.send('RenderPageRequest', {
  1933. pageIndex: this.pageNumber - 1,
  1934. intent: renderingIntent
  1935. });
  1936. }
  1937. var internalRenderTask = new InternalRenderTask(complete, params,
  1938. this.objs,
  1939. this.commonObjs,
  1940. intentState.operatorList,
  1941. this.pageNumber);
  1942. if (!intentState.renderTasks) {
  1943. intentState.renderTasks = [];
  1944. }
  1945. intentState.renderTasks.push(internalRenderTask);
  1946. var renderTask = new RenderTask(internalRenderTask);
  1947. var self = this;
  1948. intentState.displayReadyCapability.promise.then(
  1949. function pageDisplayReadyPromise(transparency) {
  1950. if (self.pendingDestroy) {
  1951. complete();
  1952. return;
  1953. }
  1954. stats.time('Rendering');
  1955. internalRenderTask.initalizeGraphics(transparency);
  1956. internalRenderTask.operatorListChanged();
  1957. },
  1958. function pageDisplayReadPromiseError(reason) {
  1959. complete(reason);
  1960. }
  1961. );
  1962. function complete(error) {
  1963. var i = intentState.renderTasks.indexOf(internalRenderTask);
  1964. if (i >= 0) {
  1965. intentState.renderTasks.splice(i, 1);
  1966. }
  1967. if (self.cleanupAfterRender) {
  1968. self.pendingDestroy = true;
  1969. }
  1970. self._tryDestroy();
  1971. if (error) {
  1972. internalRenderTask.capability.reject(error);
  1973. } else {
  1974. internalRenderTask.capability.resolve();
  1975. }
  1976. stats.timeEnd('Rendering');
  1977. stats.timeEnd('Overall');
  1978. }
  1979. return renderTask;
  1980. },
  1981. /**
  1982. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  1983. * object that represents page's operator list.
  1984. */
  1985. getOperatorList: function PDFPageProxy_getOperatorList() {
  1986. function operatorListChanged() {
  1987. if (intentState.operatorList.lastChunk) {
  1988. intentState.opListReadCapability.resolve(intentState.operatorList);
  1989. }
  1990. }
  1991. var renderingIntent = 'oplist';
  1992. if (!this.intentStates[renderingIntent]) {
  1993. this.intentStates[renderingIntent] = {};
  1994. }
  1995. var intentState = this.intentStates[renderingIntent];
  1996. if (!intentState.opListReadCapability) {
  1997. var opListTask = {};
  1998. opListTask.operatorListChanged = operatorListChanged;
  1999. intentState.receivingOperatorList = true;
  2000. intentState.opListReadCapability = createPromiseCapability();
  2001. intentState.renderTasks = [];
  2002. intentState.renderTasks.push(opListTask);
  2003. intentState.operatorList = {
  2004. fnArray: [],
  2005. argsArray: [],
  2006. lastChunk: false
  2007. };
  2008. this.transport.messageHandler.send('RenderPageRequest', {
  2009. pageIndex: this.pageIndex,
  2010. intent: renderingIntent
  2011. });
  2012. }
  2013. return intentState.opListReadCapability.promise;
  2014. },
  2015. /**
  2016. * @return {Promise} That is resolved a {@link TextContent}
  2017. * object that represent the page text content.
  2018. */
  2019. getTextContent: function PDFPageProxy_getTextContent() {
  2020. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  2021. pageIndex: this.pageNumber - 1
  2022. });
  2023. },
  2024. /**
  2025. * Destroys resources allocated by the page.
  2026. */
  2027. destroy: function PDFPageProxy_destroy() {
  2028. this.pendingDestroy = true;
  2029. this._tryDestroy();
  2030. },
  2031. /**
  2032. * For internal use only. Attempts to clean up if rendering is in a state
  2033. * where that's possible.
  2034. * @ignore
  2035. */
  2036. _tryDestroy: function PDFPageProxy__destroy() {
  2037. if (!this.pendingDestroy ||
  2038. Object.keys(this.intentStates).some(function(intent) {
  2039. var intentState = this.intentStates[intent];
  2040. return (intentState.renderTasks.length !== 0 ||
  2041. intentState.receivingOperatorList);
  2042. }, this)) {
  2043. return;
  2044. }
  2045. Object.keys(this.intentStates).forEach(function(intent) {
  2046. delete this.intentStates[intent];
  2047. }, this);
  2048. this.objs.clear();
  2049. this.annotationsPromise = null;
  2050. this.pendingDestroy = false;
  2051. },
  2052. /**
  2053. * For internal use only.
  2054. * @ignore
  2055. */
  2056. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  2057. intent) {
  2058. var intentState = this.intentStates[intent];
  2059. // TODO Refactor RenderPageRequest to separate rendering
  2060. // and operator list logic
  2061. if (intentState.displayReadyCapability) {
  2062. intentState.displayReadyCapability.resolve(transparency);
  2063. }
  2064. },
  2065. /**
  2066. * For internal use only.
  2067. * @ignore
  2068. */
  2069. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  2070. intent) {
  2071. var intentState = this.intentStates[intent];
  2072. var i, ii;
  2073. // Add the new chunk to the current operator list.
  2074. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2075. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2076. intentState.operatorList.argsArray.push(
  2077. operatorListChunk.argsArray[i]);
  2078. }
  2079. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2080. // Notify all the rendering tasks there are more operators to be consumed.
  2081. for (i = 0; i < intentState.renderTasks.length; i++) {
  2082. intentState.renderTasks[i].operatorListChanged();
  2083. }
  2084. if (operatorListChunk.lastChunk) {
  2085. intentState.receivingOperatorList = false;
  2086. this._tryDestroy();
  2087. }
  2088. }
  2089. };
  2090. return PDFPageProxy;
  2091. })();
  2092. /**
  2093. * For internal use only.
  2094. * @ignore
  2095. */
  2096. var WorkerTransport = (function WorkerTransportClosure() {
  2097. function WorkerTransport(workerInitializedCapability, workerReadyCapability,
  2098. pdfDataRangeTransport, progressCallback) {
  2099. this.pdfDataRangeTransport = pdfDataRangeTransport;
  2100. this.workerInitializedCapability = workerInitializedCapability;
  2101. this.workerReadyCapability = workerReadyCapability;
  2102. this.progressCallback = progressCallback;
  2103. this.commonObjs = new PDFObjects();
  2104. this.pageCache = [];
  2105. this.pagePromises = [];
  2106. this.downloadInfoCapability = createPromiseCapability();
  2107. this.passwordCallback = null;
  2108. // If worker support isn't disabled explicit and the browser has worker
  2109. // support, create a new web worker and test if it/the browser fullfills
  2110. // all requirements to run parts of pdf.js in a web worker.
  2111. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  2112. // as it arrives on the worker. Chrome added this with version 15.
  2113. // Either workers are disabled, not supported or have thrown an exception.
  2114. // Thus, we fallback to a faked worker.
  2115. this.setupFakeWorker();
  2116. }
  2117. WorkerTransport.prototype = {
  2118. destroy: function WorkerTransport_destroy() {
  2119. this.pageCache = [];
  2120. this.pagePromises = [];
  2121. var self = this;
  2122. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  2123. FontLoader.clear();
  2124. if (self.worker) {
  2125. self.worker.terminate();
  2126. }
  2127. });
  2128. },
  2129. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  2130. globalScope.PDFJS.disableWorker = true;
  2131. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  2132. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  2133. // In the developer build load worker_loader which in turn loads all the
  2134. // other files and resolves the promise. In production only the
  2135. // pdf.worker.js file is needed.
  2136. PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  2137. }
  2138. PDFJS.fakeWorkerFilesLoadedCapability.promise.then(function () {
  2139. warn('Setting up fake worker.');
  2140. // If we don't use a worker, just post/sendMessage to the main thread.
  2141. var fakeWorker = {
  2142. postMessage: function WorkerTransport_postMessage(obj) {
  2143. fakeWorker.onmessage({data: obj});
  2144. },
  2145. terminate: function WorkerTransport_terminate() {}
  2146. };
  2147. var messageHandler = new MessageHandler('main', fakeWorker);
  2148. this.setupMessageHandler(messageHandler);
  2149. // If the main thread is our worker, setup the handling for the messages
  2150. // the main thread sends to it self.
  2151. PDFJS.WorkerMessageHandler.setup(messageHandler);
  2152. this.workerInitializedCapability.resolve();
  2153. }.bind(this));
  2154. },
  2155. setupMessageHandler:
  2156. function WorkerTransport_setupMessageHandler(messageHandler) {
  2157. this.messageHandler = messageHandler;
  2158. function updatePassword(password) {
  2159. messageHandler.send('UpdatePassword', password);
  2160. }
  2161. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  2162. if (pdfDataRangeTransport) {
  2163. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  2164. messageHandler.send('OnDataRange', {
  2165. begin: begin,
  2166. chunk: chunk
  2167. });
  2168. });
  2169. pdfDataRangeTransport.addProgressListener(function(loaded) {
  2170. messageHandler.send('OnDataProgress', {
  2171. loaded: loaded
  2172. });
  2173. });
  2174. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  2175. messageHandler.send('OnDataRange', {
  2176. chunk: chunk
  2177. });
  2178. });
  2179. messageHandler.on('RequestDataRange',
  2180. function transportDataRange(data) {
  2181. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  2182. }, this);
  2183. }
  2184. messageHandler.on('GetDoc', function transportDoc(data) {
  2185. var pdfInfo = data.pdfInfo;
  2186. this.numPages = data.pdfInfo.numPages;
  2187. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  2188. this.pdfDocument = pdfDocument;
  2189. this.workerReadyCapability.resolve(pdfDocument);
  2190. }, this);
  2191. messageHandler.on('NeedPassword',
  2192. function transportNeedPassword(exception) {
  2193. if (this.passwordCallback) {
  2194. return this.passwordCallback(updatePassword,
  2195. PasswordResponses.NEED_PASSWORD);
  2196. }
  2197. this.workerReadyCapability.reject(
  2198. new PasswordException(exception.message, exception.code));
  2199. }, this);
  2200. messageHandler.on('IncorrectPassword',
  2201. function transportIncorrectPassword(exception) {
  2202. if (this.passwordCallback) {
  2203. return this.passwordCallback(updatePassword,
  2204. PasswordResponses.INCORRECT_PASSWORD);
  2205. }
  2206. this.workerReadyCapability.reject(
  2207. new PasswordException(exception.message, exception.code));
  2208. }, this);
  2209. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  2210. this.workerReadyCapability.reject(
  2211. new InvalidPDFException(exception.message));
  2212. }, this);
  2213. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  2214. this.workerReadyCapability.reject(
  2215. new MissingPDFException(exception.message));
  2216. }, this);
  2217. messageHandler.on('UnexpectedResponse',
  2218. function transportUnexpectedResponse(exception) {
  2219. this.workerReadyCapability.reject(
  2220. new UnexpectedResponseException(exception.message, exception.status));
  2221. }, this);
  2222. messageHandler.on('UnknownError',
  2223. function transportUnknownError(exception) {
  2224. this.workerReadyCapability.reject(
  2225. new UnknownErrorException(exception.message, exception.details));
  2226. }, this);
  2227. messageHandler.on('DataLoaded', function transportPage(data) {
  2228. this.downloadInfoCapability.resolve(data);
  2229. }, this);
  2230. messageHandler.on('PDFManagerReady', function transportPage(data) {
  2231. if (this.pdfDataRangeTransport) {
  2232. this.pdfDataRangeTransport.transportReady();
  2233. }
  2234. }, this);
  2235. messageHandler.on('StartRenderPage', function transportRender(data) {
  2236. var page = this.pageCache[data.pageIndex];
  2237. page.stats.timeEnd('Page Request');
  2238. page._startRenderPage(data.transparency, data.intent);
  2239. }, this);
  2240. messageHandler.on('RenderPageChunk', function transportRender(data) {
  2241. var page = this.pageCache[data.pageIndex];
  2242. page._renderPageChunk(data.operatorList, data.intent);
  2243. }, this);
  2244. messageHandler.on('commonobj', function transportObj(data) {
  2245. var id = data[0];
  2246. var type = data[1];
  2247. if (this.commonObjs.hasData(id)) {
  2248. return;
  2249. }
  2250. switch (type) {
  2251. case 'Font':
  2252. var exportedData = data[2];
  2253. var font;
  2254. if ('error' in exportedData) {
  2255. var error = exportedData.error;
  2256. warn('Error during font loading: ' + error);
  2257. this.commonObjs.resolve(id, error);
  2258. break;
  2259. } else {
  2260. font = new FontFaceObject(exportedData);
  2261. }
  2262. FontLoader.bind(
  2263. [font],
  2264. function fontReady(fontObjs) {
  2265. this.commonObjs.resolve(id, font);
  2266. }.bind(this)
  2267. );
  2268. break;
  2269. case 'FontPath':
  2270. this.commonObjs.resolve(id, data[2]);
  2271. break;
  2272. default:
  2273. error('Got unknown common object type ' + type);
  2274. }
  2275. }, this);
  2276. messageHandler.on('obj', function transportObj(data) {
  2277. var id = data[0];
  2278. var pageIndex = data[1];
  2279. var type = data[2];
  2280. var pageProxy = this.pageCache[pageIndex];
  2281. var imageData;
  2282. if (pageProxy.objs.hasData(id)) {
  2283. return;
  2284. }
  2285. switch (type) {
  2286. case 'JpegStream':
  2287. imageData = data[3];
  2288. loadJpegStream(id, imageData, pageProxy.objs);
  2289. break;
  2290. case 'Image':
  2291. imageData = data[3];
  2292. pageProxy.objs.resolve(id, imageData);
  2293. // heuristics that will allow not to store large data
  2294. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2295. if (imageData && 'data' in imageData &&
  2296. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  2297. pageProxy.cleanupAfterRender = true;
  2298. }
  2299. break;
  2300. default:
  2301. error('Got unknown object type ' + type);
  2302. }
  2303. }, this);
  2304. messageHandler.on('DocProgress', function transportDocProgress(data) {
  2305. if (this.progressCallback) {
  2306. this.progressCallback({
  2307. loaded: data.loaded,
  2308. total: data.total
  2309. });
  2310. }
  2311. }, this);
  2312. messageHandler.on('PageError', function transportError(data) {
  2313. var page = this.pageCache[data.pageNum - 1];
  2314. var intentState = page.intentStates[data.intent];
  2315. if (intentState.displayReadyCapability) {
  2316. intentState.displayReadyCapability.reject(data.error);
  2317. } else {
  2318. error(data.error);
  2319. }
  2320. }, this);
  2321. messageHandler.on('JpegDecode', function(data) {
  2322. var imageUrl = data[0];
  2323. var components = data[1];
  2324. if (components !== 3 && components !== 1) {
  2325. return Promise.reject(
  2326. new Error('Only 3 components or 1 component can be returned'));
  2327. }
  2328. return new Promise(function (resolve, reject) {
  2329. var img = new Image();
  2330. img.onload = function () {
  2331. var width = img.width;
  2332. var height = img.height;
  2333. var size = width * height;
  2334. var rgbaLength = size * 4;
  2335. var buf = new Uint8Array(size * components);
  2336. var tmpCanvas = createScratchCanvas(width, height);
  2337. var tmpCtx = tmpCanvas.getContext('2d');
  2338. tmpCtx.drawImage(img, 0, 0);
  2339. var data = tmpCtx.getImageData(0, 0, width, height).data;
  2340. var i, j;
  2341. if (components === 3) {
  2342. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  2343. buf[j] = data[i];
  2344. buf[j + 1] = data[i + 1];
  2345. buf[j + 2] = data[i + 2];
  2346. }
  2347. } else if (components === 1) {
  2348. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  2349. buf[j] = data[i];
  2350. }
  2351. }
  2352. resolve({ data: buf, width: width, height: height});
  2353. };
  2354. img.onerror = function () {
  2355. reject(new Error('JpegDecode failed to load image'));
  2356. };
  2357. img.src = imageUrl;
  2358. });
  2359. });
  2360. },
  2361. fetchDocument: function WorkerTransport_fetchDocument(source) {
  2362. source.disableAutoFetch = PDFJS.disableAutoFetch;
  2363. source.disableStream = PDFJS.disableStream;
  2364. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  2365. this.messageHandler.send('GetDocRequest', {
  2366. source: source,
  2367. disableRange: PDFJS.disableRange,
  2368. maxImageSize: PDFJS.maxImageSize,
  2369. cMapUrl: PDFJS.cMapUrl,
  2370. cMapPacked: PDFJS.cMapPacked,
  2371. disableFontFace: PDFJS.disableFontFace,
  2372. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  2373. verbosity: PDFJS.verbosity
  2374. });
  2375. },
  2376. getData: function WorkerTransport_getData() {
  2377. return this.messageHandler.sendWithPromise('GetData', null);
  2378. },
  2379. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  2380. if (pageNumber <= 0 || pageNumber > this.numPages ||
  2381. (pageNumber|0) !== pageNumber) {
  2382. return Promise.reject(new Error('Invalid page request'));
  2383. }
  2384. var pageIndex = pageNumber - 1;
  2385. if (pageIndex in this.pagePromises) {
  2386. return this.pagePromises[pageIndex];
  2387. }
  2388. var promise = this.messageHandler.sendWithPromise('GetPage', {
  2389. pageIndex: pageIndex
  2390. }).then(function (pageInfo) {
  2391. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  2392. this.pageCache[pageIndex] = page;
  2393. return page;
  2394. }.bind(this));
  2395. this.pagePromises[pageIndex] = promise;
  2396. return promise;
  2397. },
  2398. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  2399. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  2400. },
  2401. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  2402. return this.messageHandler.sendWithPromise('GetAnnotations',
  2403. { pageIndex: pageIndex });
  2404. },
  2405. getDestinations: function WorkerTransport_getDestinations() {
  2406. return this.messageHandler.sendWithPromise('GetDestinations', null);
  2407. },
  2408. getDestination: function WorkerTransport_getDestination(id) {
  2409. return this.messageHandler.sendWithPromise('GetDestination', { id: id } );
  2410. },
  2411. getAttachments: function WorkerTransport_getAttachments() {
  2412. return this.messageHandler.sendWithPromise('GetAttachments', null);
  2413. },
  2414. getJavaScript: function WorkerTransport_getJavaScript() {
  2415. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  2416. },
  2417. getOutline: function WorkerTransport_getOutline() {
  2418. return this.messageHandler.sendWithPromise('GetOutline', null);
  2419. },
  2420. getMetadata: function WorkerTransport_getMetadata() {
  2421. return this.messageHandler.sendWithPromise('GetMetadata', null).
  2422. then(function transportMetadata(results) {
  2423. return {
  2424. info: results[0],
  2425. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  2426. };
  2427. });
  2428. },
  2429. getStats: function WorkerTransport_getStats() {
  2430. return this.messageHandler.sendWithPromise('GetStats', null);
  2431. },
  2432. startCleanup: function WorkerTransport_startCleanup() {
  2433. this.messageHandler.sendWithPromise('Cleanup', null).
  2434. then(function endCleanup() {
  2435. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  2436. var page = this.pageCache[i];
  2437. if (page) {
  2438. page.destroy();
  2439. }
  2440. }
  2441. this.commonObjs.clear();
  2442. FontLoader.clear();
  2443. }.bind(this));
  2444. }
  2445. };
  2446. return WorkerTransport;
  2447. })();
  2448. /**
  2449. * A PDF document and page is built of many objects. E.g. there are objects
  2450. * for fonts, images, rendering code and such. These objects might get processed
  2451. * inside of a worker. The `PDFObjects` implements some basic functions to
  2452. * manage these objects.
  2453. * @ignore
  2454. */
  2455. var PDFObjects = (function PDFObjectsClosure() {
  2456. function PDFObjects() {
  2457. this.objs = {};
  2458. }
  2459. PDFObjects.prototype = {
  2460. /**
  2461. * Internal function.
  2462. * Ensures there is an object defined for `objId`.
  2463. */
  2464. ensureObj: function PDFObjects_ensureObj(objId) {
  2465. if (this.objs[objId]) {
  2466. return this.objs[objId];
  2467. }
  2468. var obj = {
  2469. capability: createPromiseCapability(),
  2470. data: null,
  2471. resolved: false
  2472. };
  2473. this.objs[objId] = obj;
  2474. return obj;
  2475. },
  2476. /**
  2477. * If called *without* callback, this returns the data of `objId` but the
  2478. * object needs to be resolved. If it isn't, this function throws.
  2479. *
  2480. * If called *with* a callback, the callback is called with the data of the
  2481. * object once the object is resolved. That means, if you call this
  2482. * function and the object is already resolved, the callback gets called
  2483. * right away.
  2484. */
  2485. get: function PDFObjects_get(objId, callback) {
  2486. // If there is a callback, then the get can be async and the object is
  2487. // not required to be resolved right now
  2488. if (callback) {
  2489. this.ensureObj(objId).capability.promise.then(callback);
  2490. return null;
  2491. }
  2492. // If there isn't a callback, the user expects to get the resolved data
  2493. // directly.
  2494. var obj = this.objs[objId];
  2495. // If there isn't an object yet or the object isn't resolved, then the
  2496. // data isn't ready yet!
  2497. if (!obj || !obj.resolved) {
  2498. error('Requesting object that isn\'t resolved yet ' + objId);
  2499. }
  2500. return obj.data;
  2501. },
  2502. /**
  2503. * Resolves the object `objId` with optional `data`.
  2504. */
  2505. resolve: function PDFObjects_resolve(objId, data) {
  2506. var obj = this.ensureObj(objId);
  2507. obj.resolved = true;
  2508. obj.data = data;
  2509. obj.capability.resolve(data);
  2510. },
  2511. isResolved: function PDFObjects_isResolved(objId) {
  2512. var objs = this.objs;
  2513. if (!objs[objId]) {
  2514. return false;
  2515. } else {
  2516. return objs[objId].resolved;
  2517. }
  2518. },
  2519. hasData: function PDFObjects_hasData(objId) {
  2520. return this.isResolved(objId);
  2521. },
  2522. /**
  2523. * Returns the data of `objId` if object exists, null otherwise.
  2524. */
  2525. getData: function PDFObjects_getData(objId) {
  2526. var objs = this.objs;
  2527. if (!objs[objId] || !objs[objId].resolved) {
  2528. return null;
  2529. } else {
  2530. return objs[objId].data;
  2531. }
  2532. },
  2533. clear: function PDFObjects_clear() {
  2534. this.objs = {};
  2535. }
  2536. };
  2537. return PDFObjects;
  2538. })();
  2539. /**
  2540. * Allows controlling of the rendering tasks.
  2541. * @class
  2542. */
  2543. var RenderTask = (function RenderTaskClosure() {
  2544. function RenderTask(internalRenderTask) {
  2545. this.internalRenderTask = internalRenderTask;
  2546. /**
  2547. * Promise for rendering task completion.
  2548. * @type {Promise}
  2549. */
  2550. this.promise = this.internalRenderTask.capability.promise;
  2551. }
  2552. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  2553. /**
  2554. * Cancels the rendering task. If the task is currently rendering it will
  2555. * not be cancelled until graphics pauses with a timeout. The promise that
  2556. * this object extends will resolved when cancelled.
  2557. */
  2558. cancel: function RenderTask_cancel() {
  2559. this.internalRenderTask.cancel();
  2560. },
  2561. /**
  2562. * Registers callback to indicate the rendering task completion.
  2563. *
  2564. * @param {function} onFulfilled The callback for the rendering completion.
  2565. * @param {function} onRejected The callback for the rendering failure.
  2566. * @return {Promise} A promise that is resolved after the onFulfilled or
  2567. * onRejected callback.
  2568. */
  2569. then: function RenderTask_then(onFulfilled, onRejected) {
  2570. return this.promise.then(onFulfilled, onRejected);
  2571. }
  2572. };
  2573. return RenderTask;
  2574. })();
  2575. /**
  2576. * For internal use only.
  2577. * @ignore
  2578. */
  2579. var InternalRenderTask = (function InternalRenderTaskClosure() {
  2580. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  2581. pageNumber) {
  2582. this.callback = callback;
  2583. this.params = params;
  2584. this.objs = objs;
  2585. this.commonObjs = commonObjs;
  2586. this.operatorListIdx = null;
  2587. this.operatorList = operatorList;
  2588. this.pageNumber = pageNumber;
  2589. this.running = false;
  2590. this.graphicsReadyCallback = null;
  2591. this.graphicsReady = false;
  2592. this.cancelled = false;
  2593. this.capability = createPromiseCapability();
  2594. // caching this-bound methods
  2595. this._continueBound = this._continue.bind(this);
  2596. this._scheduleNextBound = this._scheduleNext.bind(this);
  2597. this._nextBound = this._next.bind(this);
  2598. }
  2599. InternalRenderTask.prototype = {
  2600. initalizeGraphics:
  2601. function InternalRenderTask_initalizeGraphics(transparency) {
  2602. if (this.cancelled) {
  2603. return;
  2604. }
  2605. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  2606. globalScope.StepperManager.enabled) {
  2607. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  2608. this.stepper.init(this.operatorList);
  2609. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2610. }
  2611. var params = this.params;
  2612. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  2613. this.objs, params.imageLayer);
  2614. this.gfx.beginDrawing(params.viewport, transparency);
  2615. this.operatorListIdx = 0;
  2616. this.graphicsReady = true;
  2617. if (this.graphicsReadyCallback) {
  2618. this.graphicsReadyCallback();
  2619. }
  2620. },
  2621. cancel: function InternalRenderTask_cancel() {
  2622. this.running = false;
  2623. this.cancelled = true;
  2624. this.callback('cancelled');
  2625. },
  2626. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  2627. if (!this.graphicsReady) {
  2628. if (!this.graphicsReadyCallback) {
  2629. this.graphicsReadyCallback = this._continueBound;
  2630. }
  2631. return;
  2632. }
  2633. if (this.stepper) {
  2634. this.stepper.updateOperatorList(this.operatorList);
  2635. }
  2636. if (this.running) {
  2637. return;
  2638. }
  2639. this._continue();
  2640. },
  2641. _continue: function InternalRenderTask__continue() {
  2642. this.running = true;
  2643. if (this.cancelled) {
  2644. return;
  2645. }
  2646. if (this.params.continueCallback) {
  2647. this.params.continueCallback(this._scheduleNextBound);
  2648. } else {
  2649. this._scheduleNext();
  2650. }
  2651. },
  2652. _scheduleNext: function InternalRenderTask__scheduleNext() {
  2653. window.requestAnimationFrame(this._nextBound);
  2654. },
  2655. _next: function InternalRenderTask__next() {
  2656. if (this.cancelled) {
  2657. return;
  2658. }
  2659. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  2660. this.operatorListIdx,
  2661. this._continueBound,
  2662. this.stepper);
  2663. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2664. this.running = false;
  2665. if (this.operatorList.lastChunk) {
  2666. this.gfx.endDrawing();
  2667. this.callback();
  2668. }
  2669. }
  2670. }
  2671. };
  2672. return InternalRenderTask;
  2673. })();
  2674. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  2675. function fixMetadata(meta) {
  2676. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2677. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2678. function(code, d1, d2, d3) {
  2679. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2680. });
  2681. var chars = '';
  2682. for (var i = 0; i < bytes.length; i += 2) {
  2683. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2684. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2685. code !== 38 && false ? String.fromCharCode(code) :
  2686. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2687. }
  2688. return '>' + chars;
  2689. });
  2690. }
  2691. function Metadata(meta) {
  2692. if (typeof meta === 'string') {
  2693. // Ghostscript produces invalid metadata
  2694. meta = fixMetadata(meta);
  2695. var parser = new DOMParser();
  2696. meta = parser.parseFromString(meta, 'application/xml');
  2697. } else if (!(meta instanceof Document)) {
  2698. error('Metadata: Invalid metadata object');
  2699. }
  2700. this.metaDocument = meta;
  2701. this.metadata = {};
  2702. this.parse();
  2703. }
  2704. Metadata.prototype = {
  2705. parse: function Metadata_parse() {
  2706. var doc = this.metaDocument;
  2707. var rdf = doc.documentElement;
  2708. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2709. rdf = rdf.firstChild;
  2710. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2711. rdf = rdf.nextSibling;
  2712. }
  2713. }
  2714. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2715. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2716. return;
  2717. }
  2718. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2719. for (i = 0, length = children.length; i < length; i++) {
  2720. desc = children[i];
  2721. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2722. continue;
  2723. }
  2724. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2725. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2726. entry = desc.childNodes[ii];
  2727. name = entry.nodeName.toLowerCase();
  2728. this.metadata[name] = entry.textContent.trim();
  2729. }
  2730. }
  2731. }
  2732. },
  2733. get: function Metadata_get(name) {
  2734. return this.metadata[name] || null;
  2735. },
  2736. has: function Metadata_has(name) {
  2737. return typeof this.metadata[name] !== 'undefined';
  2738. }
  2739. };
  2740. return Metadata;
  2741. })();
  2742. // <canvas> contexts store most of the state we need natively.
  2743. // However, PDF needs a bit more state, which we store here.
  2744. // Minimal font size that would be used during canvas fillText operations.
  2745. var MIN_FONT_SIZE = 16;
  2746. // Maximum font size that would be used during canvas fillText operations.
  2747. var MAX_FONT_SIZE = 100;
  2748. var MAX_GROUP_SIZE = 4096;
  2749. // Heuristic value used when enforcing minimum line widths.
  2750. var MIN_WIDTH_FACTOR = 0.65;
  2751. var COMPILE_TYPE3_GLYPHS = true;
  2752. var MAX_SIZE_TO_COMPILE = 1000;
  2753. var FULL_CHUNK_HEIGHT = 16;
  2754. function createScratchCanvas(width, height) {
  2755. var canvas = document.createElement('canvas');
  2756. canvas.width = width;
  2757. canvas.height = height;
  2758. return canvas;
  2759. }
  2760. function addContextCurrentTransform(ctx) {
  2761. // If the context doesn't expose a `mozCurrentTransform`, add a JS based on.
  2762. if (!ctx.mozCurrentTransform) {
  2763. // Store the original context
  2764. ctx._scaleX = ctx._scaleX || 1.0;
  2765. ctx._scaleY = ctx._scaleY || 1.0;
  2766. ctx._originalSave = ctx.save;
  2767. ctx._originalRestore = ctx.restore;
  2768. ctx._originalRotate = ctx.rotate;
  2769. ctx._originalScale = ctx.scale;
  2770. ctx._originalTranslate = ctx.translate;
  2771. ctx._originalTransform = ctx.transform;
  2772. ctx._originalSetTransform = ctx.setTransform;
  2773. ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];
  2774. ctx._transformStack = [];
  2775. Object.defineProperty(ctx, 'mozCurrentTransform', {
  2776. get: function getCurrentTransform() {
  2777. return this._transformMatrix;
  2778. }
  2779. });
  2780. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  2781. get: function getCurrentTransformInverse() {
  2782. // Calculation done using WolframAlpha:
  2783. // http://www.wolframalpha.com/input/?
  2784. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  2785. var m = this._transformMatrix;
  2786. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  2787. var ad_bc = a * d - b * c;
  2788. var bc_ad = b * c - a * d;
  2789. return [
  2790. d / ad_bc,
  2791. b / bc_ad,
  2792. c / bc_ad,
  2793. a / ad_bc,
  2794. (d * e - c * f) / bc_ad,
  2795. (b * e - a * f) / ad_bc
  2796. ];
  2797. }
  2798. });
  2799. ctx.save = function ctxSave() {
  2800. var old = this._transformMatrix;
  2801. this._transformStack.push(old);
  2802. this._transformMatrix = old.slice(0, 6);
  2803. this._originalSave();
  2804. };
  2805. ctx.restore = function ctxRestore() {
  2806. var prev = this._transformStack.pop();
  2807. if (prev) {
  2808. this._transformMatrix = prev;
  2809. this._originalRestore();
  2810. }
  2811. };
  2812. ctx.translate = function ctxTranslate(x, y) {
  2813. var m = this._transformMatrix;
  2814. m[4] = m[0] * x + m[2] * y + m[4];
  2815. m[5] = m[1] * x + m[3] * y + m[5];
  2816. this._originalTranslate(x, y);
  2817. };
  2818. ctx.scale = function ctxScale(x, y) {
  2819. var m = this._transformMatrix;
  2820. m[0] = m[0] * x;
  2821. m[1] = m[1] * x;
  2822. m[2] = m[2] * y;
  2823. m[3] = m[3] * y;
  2824. this._originalScale(x, y);
  2825. };
  2826. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  2827. var m = this._transformMatrix;
  2828. this._transformMatrix = [
  2829. m[0] * a + m[2] * b,
  2830. m[1] * a + m[3] * b,
  2831. m[0] * c + m[2] * d,
  2832. m[1] * c + m[3] * d,
  2833. m[0] * e + m[2] * f + m[4],
  2834. m[1] * e + m[3] * f + m[5]
  2835. ];
  2836. ctx._originalTransform(a, b, c, d, e, f);
  2837. };
  2838. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  2839. this._transformMatrix = [a, b, c, d, e, f];
  2840. ctx._originalSetTransform(a, b, c, d, e, f);
  2841. };
  2842. ctx.rotate = function ctxRotate(angle) {
  2843. var cosValue = Math.cos(angle);
  2844. var sinValue = Math.sin(angle);
  2845. var m = this._transformMatrix;
  2846. this._transformMatrix = [
  2847. m[0] * cosValue + m[2] * sinValue,
  2848. m[1] * cosValue + m[3] * sinValue,
  2849. m[0] * (-sinValue) + m[2] * cosValue,
  2850. m[1] * (-sinValue) + m[3] * cosValue,
  2851. m[4],
  2852. m[5]
  2853. ];
  2854. this._originalRotate(angle);
  2855. };
  2856. }
  2857. }
  2858. var CachedCanvases = (function CachedCanvasesClosure() {
  2859. var cache = {};
  2860. return {
  2861. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  2862. trackTransform) {
  2863. var canvasEntry;
  2864. if (cache[id] !== undefined) {
  2865. canvasEntry = cache[id];
  2866. canvasEntry.canvas.width = width;
  2867. canvasEntry.canvas.height = height;
  2868. // reset canvas transform for emulated mozCurrentTransform, if needed
  2869. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  2870. } else {
  2871. var canvas = createScratchCanvas(width, height);
  2872. var ctx = canvas.getContext('2d');
  2873. if (trackTransform) {
  2874. addContextCurrentTransform(ctx);
  2875. }
  2876. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  2877. }
  2878. return canvasEntry;
  2879. },
  2880. clear: function () {
  2881. for (var id in cache) {
  2882. var canvasEntry = cache[id];
  2883. // Zeroing the width and height causes Firefox to release graphics
  2884. // resources immediately, which can greatly reduce memory consumption.
  2885. canvasEntry.canvas.width = 0;
  2886. canvasEntry.canvas.height = 0;
  2887. delete cache[id];
  2888. }
  2889. }
  2890. };
  2891. })();
  2892. function compileType3Glyph(imgData) {
  2893. var POINT_TO_PROCESS_LIMIT = 1000;
  2894. var width = imgData.width, height = imgData.height;
  2895. var i, j, j0, width1 = width + 1;
  2896. var points = new Uint8Array(width1 * (height + 1));
  2897. var POINT_TYPES =
  2898. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  2899. // decodes bit-packed mask data
  2900. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  2901. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  2902. for (i = 0, ii = data0.length; i < ii; i++) {
  2903. var mask = 128, elem = data0[i];
  2904. while (mask > 0) {
  2905. data[pos++] = (elem & mask) ? 0 : 255;
  2906. mask >>= 1;
  2907. }
  2908. }
  2909. // finding iteresting points: every point is located between mask pixels,
  2910. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  2911. // will have flags assigned based on neighboring mask pixels:
  2912. // 4 | 8
  2913. // --P--
  2914. // 2 | 1
  2915. // We are interested only in points with the flags:
  2916. // - outside corners: 1, 2, 4, 8;
  2917. // - inside corners: 7, 11, 13, 14;
  2918. // - and, intersections: 5, 10.
  2919. var count = 0;
  2920. pos = 0;
  2921. if (data[pos] !== 0) {
  2922. points[0] = 1;
  2923. ++count;
  2924. }
  2925. for (j = 1; j < width; j++) {
  2926. if (data[pos] !== data[pos + 1]) {
  2927. points[j] = data[pos] ? 2 : 1;
  2928. ++count;
  2929. }
  2930. pos++;
  2931. }
  2932. if (data[pos] !== 0) {
  2933. points[j] = 2;
  2934. ++count;
  2935. }
  2936. for (i = 1; i < height; i++) {
  2937. pos = i * lineSize;
  2938. j0 = i * width1;
  2939. if (data[pos - lineSize] !== data[pos]) {
  2940. points[j0] = data[pos] ? 1 : 8;
  2941. ++count;
  2942. }
  2943. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  2944. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  2945. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  2946. for (j = 1; j < width; j++) {
  2947. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  2948. (data[pos - lineSize + 1] ? 8 : 0);
  2949. if (POINT_TYPES[sum]) {
  2950. points[j0 + j] = POINT_TYPES[sum];
  2951. ++count;
  2952. }
  2953. pos++;
  2954. }
  2955. if (data[pos - lineSize] !== data[pos]) {
  2956. points[j0 + j] = data[pos] ? 2 : 4;
  2957. ++count;
  2958. }
  2959. if (count > POINT_TO_PROCESS_LIMIT) {
  2960. return null;
  2961. }
  2962. }
  2963. pos = lineSize * (height - 1);
  2964. j0 = i * width1;
  2965. if (data[pos] !== 0) {
  2966. points[j0] = 8;
  2967. ++count;
  2968. }
  2969. for (j = 1; j < width; j++) {
  2970. if (data[pos] !== data[pos + 1]) {
  2971. points[j0 + j] = data[pos] ? 4 : 8;
  2972. ++count;
  2973. }
  2974. pos++;
  2975. }
  2976. if (data[pos] !== 0) {
  2977. points[j0 + j] = 4;
  2978. ++count;
  2979. }
  2980. if (count > POINT_TO_PROCESS_LIMIT) {
  2981. return null;
  2982. }
  2983. // building outlines
  2984. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  2985. var outlines = [];
  2986. for (i = 0; count && i <= height; i++) {
  2987. var p = i * width1;
  2988. var end = p + width;
  2989. while (p < end && !points[p]) {
  2990. p++;
  2991. }
  2992. if (p === end) {
  2993. continue;
  2994. }
  2995. var coords = [p % width1, i];
  2996. var type = points[p], p0 = p, pp;
  2997. do {
  2998. var step = steps[type];
  2999. do {
  3000. p += step;
  3001. } while (!points[p]);
  3002. pp = points[p];
  3003. if (pp !== 5 && pp !== 10) {
  3004. // set new direction
  3005. type = pp;
  3006. // delete mark
  3007. points[p] = 0;
  3008. } else { // type is 5 or 10, ie, a crossing
  3009. // set new direction
  3010. type = pp & ((0x33 * type) >> 4);
  3011. // set new type for "future hit"
  3012. points[p] &= (type >> 2 | type << 2);
  3013. }
  3014. coords.push(p % width1);
  3015. coords.push((p / width1) | 0);
  3016. --count;
  3017. } while (p0 !== p);
  3018. outlines.push(coords);
  3019. --i;
  3020. }
  3021. var drawOutline = function(c) {
  3022. c.save();
  3023. // the path shall be painted in [0..1]x[0..1] space
  3024. c.scale(1 / width, -1 / height);
  3025. c.translate(0, -height);
  3026. c.beginPath();
  3027. for (var i = 0, ii = outlines.length; i < ii; i++) {
  3028. var o = outlines[i];
  3029. c.moveTo(o[0], o[1]);
  3030. for (var j = 2, jj = o.length; j < jj; j += 2) {
  3031. c.lineTo(o[j], o[j+1]);
  3032. }
  3033. }
  3034. c.fill();
  3035. c.beginPath();
  3036. c.restore();
  3037. };
  3038. return drawOutline;
  3039. }
  3040. var CanvasExtraState = (function CanvasExtraStateClosure() {
  3041. function CanvasExtraState(old) {
  3042. // Are soft masks and alpha values shapes or opacities?
  3043. this.alphaIsShape = false;
  3044. this.fontSize = 0;
  3045. this.fontSizeScale = 1;
  3046. this.textMatrix = IDENTITY_MATRIX;
  3047. this.textMatrixScale = 1;
  3048. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3049. this.leading = 0;
  3050. // Current point (in user coordinates)
  3051. this.x = 0;
  3052. this.y = 0;
  3053. // Start of text line (in text coordinates)
  3054. this.lineX = 0;
  3055. this.lineY = 0;
  3056. // Character and word spacing
  3057. this.charSpacing = 0;
  3058. this.wordSpacing = 0;
  3059. this.textHScale = 1;
  3060. this.textRenderingMode = TextRenderingMode.FILL;
  3061. this.textRise = 0;
  3062. // Default fore and background colors
  3063. this.fillColor = '#000000';
  3064. this.strokeColor = '#000000';
  3065. this.patternFill = false;
  3066. // Note: fill alpha applies to all non-stroking operations
  3067. this.fillAlpha = 1;
  3068. this.strokeAlpha = 1;
  3069. this.lineWidth = 1;
  3070. this.activeSMask = null; // nonclonable field (see the save method below)
  3071. this.old = old;
  3072. }
  3073. CanvasExtraState.prototype = {
  3074. clone: function CanvasExtraState_clone() {
  3075. return Object.create(this);
  3076. },
  3077. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  3078. this.x = x;
  3079. this.y = y;
  3080. }
  3081. };
  3082. return CanvasExtraState;
  3083. })();
  3084. var CanvasGraphics = (function CanvasGraphicsClosure() {
  3085. // Defines the time the executeOperatorList is going to be executing
  3086. // before it stops and shedules a continue of execution.
  3087. var EXECUTION_TIME = 15;
  3088. // Defines the number of steps before checking the execution time
  3089. var EXECUTION_STEPS = 10;
  3090. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  3091. this.ctx = canvasCtx;
  3092. this.current = new CanvasExtraState();
  3093. this.stateStack = [];
  3094. this.pendingClip = null;
  3095. this.pendingEOFill = false;
  3096. this.res = null;
  3097. this.xobjs = null;
  3098. this.commonObjs = commonObjs;
  3099. this.objs = objs;
  3100. this.imageLayer = imageLayer;
  3101. this.groupStack = [];
  3102. this.processingType3 = null;
  3103. // Patterns are painted relative to the initial page/form transform, see pdf
  3104. // spec 8.7.2 NOTE 1.
  3105. this.baseTransform = null;
  3106. this.baseTransformStack = [];
  3107. this.groupLevel = 0;
  3108. this.smaskStack = [];
  3109. this.smaskCounter = 0;
  3110. this.tempSMask = null;
  3111. if (canvasCtx) {
  3112. addContextCurrentTransform(canvasCtx);
  3113. }
  3114. this.cachedGetSinglePixelWidth = null;
  3115. }
  3116. function putBinaryImageData(ctx, imgData) {
  3117. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  3118. ctx.putImageData(imgData, 0, 0);
  3119. return;
  3120. }
  3121. // Put the image data to the canvas in chunks, rather than putting the
  3122. // whole image at once. This saves JS memory, because the ImageData object
  3123. // is smaller. It also possibly saves C++ memory within the implementation
  3124. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  3125. // the data passed to putImageData()). |n| shouldn't be too small, however,
  3126. // because too many putImageData() calls will slow things down.
  3127. //
  3128. // Note: as written, if the last chunk is partial, the putImageData() call
  3129. // will (conceptually) put pixels past the bounds of the canvas. But
  3130. // that's ok; any such pixels are ignored.
  3131. var height = imgData.height, width = imgData.width;
  3132. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3133. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3134. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3135. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3136. var srcPos = 0, destPos;
  3137. var src = imgData.data;
  3138. var dest = chunkImgData.data;
  3139. var i, j, thisChunkHeight, elemsInThisChunk;
  3140. // There are multiple forms in which the pixel data can be passed, and
  3141. // imgData.kind tells us which one this is.
  3142. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  3143. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  3144. var srcLength = src.byteLength;
  3145. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  3146. new Uint32ArrayView(dest);
  3147. var dest32DataLength = dest32.length;
  3148. var fullSrcDiff = (width + 7) >> 3;
  3149. var white = 0xFFFFFFFF;
  3150. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  3151. 0xFF000000 : 0x000000FF;
  3152. for (i = 0; i < totalChunks; i++) {
  3153. thisChunkHeight =
  3154. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3155. destPos = 0;
  3156. for (j = 0; j < thisChunkHeight; j++) {
  3157. var srcDiff = srcLength - srcPos;
  3158. var k = 0;
  3159. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  3160. var kEndUnrolled = kEnd & ~7;
  3161. var mask = 0;
  3162. var srcByte = 0;
  3163. for (; k < kEndUnrolled; k += 8) {
  3164. srcByte = src[srcPos++];
  3165. dest32[destPos++] = (srcByte & 128) ? white : black;
  3166. dest32[destPos++] = (srcByte & 64) ? white : black;
  3167. dest32[destPos++] = (srcByte & 32) ? white : black;
  3168. dest32[destPos++] = (srcByte & 16) ? white : black;
  3169. dest32[destPos++] = (srcByte & 8) ? white : black;
  3170. dest32[destPos++] = (srcByte & 4) ? white : black;
  3171. dest32[destPos++] = (srcByte & 2) ? white : black;
  3172. dest32[destPos++] = (srcByte & 1) ? white : black;
  3173. }
  3174. for (; k < kEnd; k++) {
  3175. if (mask === 0) {
  3176. srcByte = src[srcPos++];
  3177. mask = 128;
  3178. }
  3179. dest32[destPos++] = (srcByte & mask) ? white : black;
  3180. mask >>= 1;
  3181. }
  3182. }
  3183. // We ran out of input. Make all remaining pixels transparent.
  3184. while (destPos < dest32DataLength) {
  3185. dest32[destPos++] = 0;
  3186. }
  3187. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3188. }
  3189. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  3190. // RGBA, 32-bits per pixel.
  3191. j = 0;
  3192. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  3193. for (i = 0; i < fullChunks; i++) {
  3194. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3195. srcPos += elemsInThisChunk;
  3196. ctx.putImageData(chunkImgData, 0, j);
  3197. j += FULL_CHUNK_HEIGHT;
  3198. }
  3199. if (i < totalChunks) {
  3200. elemsInThisChunk = width * partialChunkHeight * 4;
  3201. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3202. ctx.putImageData(chunkImgData, 0, j);
  3203. }
  3204. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  3205. // RGB, 24-bits per pixel.
  3206. thisChunkHeight = FULL_CHUNK_HEIGHT;
  3207. elemsInThisChunk = width * thisChunkHeight;
  3208. for (i = 0; i < totalChunks; i++) {
  3209. if (i >= fullChunks) {
  3210. thisChunkHeight = partialChunkHeight;
  3211. elemsInThisChunk = width * thisChunkHeight;
  3212. }
  3213. destPos = 0;
  3214. for (j = elemsInThisChunk; j--;) {
  3215. dest[destPos++] = src[srcPos++];
  3216. dest[destPos++] = src[srcPos++];
  3217. dest[destPos++] = src[srcPos++];
  3218. dest[destPos++] = 255;
  3219. }
  3220. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3221. }
  3222. } else {
  3223. error('bad image kind: ' + imgData.kind);
  3224. }
  3225. }
  3226. function putBinaryImageMask(ctx, imgData) {
  3227. var height = imgData.height, width = imgData.width;
  3228. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3229. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3230. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3231. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3232. var srcPos = 0;
  3233. var src = imgData.data;
  3234. var dest = chunkImgData.data;
  3235. for (var i = 0; i < totalChunks; i++) {
  3236. var thisChunkHeight =
  3237. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3238. // Expand the mask so it can be used by the canvas. Any required
  3239. // inversion has already been handled.
  3240. var destPos = 3; // alpha component offset
  3241. for (var j = 0; j < thisChunkHeight; j++) {
  3242. var mask = 0;
  3243. for (var k = 0; k < width; k++) {
  3244. if (!mask) {
  3245. var elem = src[srcPos++];
  3246. mask = 128;
  3247. }
  3248. dest[destPos] = (elem & mask) ? 0 : 255;
  3249. destPos += 4;
  3250. mask >>= 1;
  3251. }
  3252. }
  3253. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3254. }
  3255. }
  3256. function copyCtxState(sourceCtx, destCtx) {
  3257. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  3258. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  3259. 'globalCompositeOperation', 'font'];
  3260. for (var i = 0, ii = properties.length; i < ii; i++) {
  3261. var property = properties[i];
  3262. if (sourceCtx[property] !== undefined) {
  3263. destCtx[property] = sourceCtx[property];
  3264. }
  3265. }
  3266. if (sourceCtx.setLineDash !== undefined) {
  3267. destCtx.setLineDash(sourceCtx.getLineDash());
  3268. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  3269. } else if (sourceCtx.mozDashOffset !== undefined) {
  3270. destCtx.mozDash = sourceCtx.mozDash;
  3271. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  3272. }
  3273. }
  3274. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  3275. var length = bytes.length;
  3276. for (var i = 3; i < length; i += 4) {
  3277. var alpha = bytes[i];
  3278. if (alpha === 0) {
  3279. bytes[i - 3] = r0;
  3280. bytes[i - 2] = g0;
  3281. bytes[i - 1] = b0;
  3282. } else if (alpha < 255) {
  3283. var alpha_ = 255 - alpha;
  3284. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  3285. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  3286. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  3287. }
  3288. }
  3289. }
  3290. function composeSMaskAlpha(maskData, layerData) {
  3291. var length = maskData.length;
  3292. var scale = 1 / 255;
  3293. for (var i = 3; i < length; i += 4) {
  3294. var alpha = maskData[i];
  3295. layerData[i] = (layerData[i] * alpha * scale) | 0;
  3296. }
  3297. }
  3298. function composeSMaskLuminosity(maskData, layerData) {
  3299. var length = maskData.length;
  3300. for (var i = 3; i < length; i += 4) {
  3301. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  3302. (maskData[i - 2] * 152) + // * 0.59 ....
  3303. (maskData[i - 1] * 28); // * 0.11 ....
  3304. layerData[i] = (layerData[i] * y) >> 16;
  3305. }
  3306. }
  3307. function genericComposeSMask(maskCtx, layerCtx, width, height,
  3308. subtype, backdrop) {
  3309. var hasBackdrop = !!backdrop;
  3310. var r0 = hasBackdrop ? backdrop[0] : 0;
  3311. var g0 = hasBackdrop ? backdrop[1] : 0;
  3312. var b0 = hasBackdrop ? backdrop[2] : 0;
  3313. var composeFn;
  3314. if (subtype === 'Luminosity') {
  3315. composeFn = composeSMaskLuminosity;
  3316. } else {
  3317. composeFn = composeSMaskAlpha;
  3318. }
  3319. // processing image in chunks to save memory
  3320. var PIXELS_TO_PROCESS = 1048576;
  3321. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  3322. for (var row = 0; row < height; row += chunkSize) {
  3323. var chunkHeight = Math.min(chunkSize, height - row);
  3324. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  3325. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  3326. if (hasBackdrop) {
  3327. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  3328. }
  3329. composeFn(maskData.data, layerData.data);
  3330. maskCtx.putImageData(layerData, 0, row);
  3331. }
  3332. }
  3333. function composeSMask(ctx, smask, layerCtx) {
  3334. var mask = smask.canvas;
  3335. var maskCtx = smask.context;
  3336. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  3337. smask.offsetX, smask.offsetY);
  3338. var backdrop = smask.backdrop || null;
  3339. if (WebGLUtils.isEnabled) {
  3340. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  3341. {subtype: smask.subtype, backdrop: backdrop});
  3342. ctx.setTransform(1, 0, 0, 1, 0, 0);
  3343. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  3344. return;
  3345. }
  3346. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  3347. smask.subtype, backdrop);
  3348. ctx.drawImage(mask, 0, 0);
  3349. }
  3350. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3351. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3352. var NORMAL_CLIP = {};
  3353. var EO_CLIP = {};
  3354. CanvasGraphics.prototype = {
  3355. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  3356. // For pdfs that use blend modes we have to clear the canvas else certain
  3357. // blend modes can look wrong since we'd be blending with a white
  3358. // backdrop. The problem with a transparent backdrop though is we then
  3359. // don't get sub pixel anti aliasing on text, so we fill with white if
  3360. // we can.
  3361. var width = this.ctx.canvas.width;
  3362. var height = this.ctx.canvas.height;
  3363. if (transparency) {
  3364. this.ctx.clearRect(0, 0, width, height);
  3365. } else {
  3366. this.ctx.mozOpaque = true;
  3367. this.ctx.save();
  3368. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  3369. this.ctx.fillRect(0, 0, width, height);
  3370. this.ctx.restore();
  3371. }
  3372. var transform = viewport.transform;
  3373. this.ctx.save();
  3374. this.ctx.transform.apply(this.ctx, transform);
  3375. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  3376. if (this.imageLayer) {
  3377. this.imageLayer.beginLayout();
  3378. }
  3379. },
  3380. executeOperatorList: function CanvasGraphics_executeOperatorList(
  3381. operatorList,
  3382. executionStartIdx, continueCallback,
  3383. stepper) {
  3384. var argsArray = operatorList.argsArray;
  3385. var fnArray = operatorList.fnArray;
  3386. var i = executionStartIdx || 0;
  3387. var argsArrayLen = argsArray.length;
  3388. // Sometimes the OperatorList to execute is empty.
  3389. if (argsArrayLen === i) {
  3390. return i;
  3391. }
  3392. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  3393. typeof continueCallback === 'function');
  3394. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  3395. var steps = 0;
  3396. var commonObjs = this.commonObjs;
  3397. var objs = this.objs;
  3398. var fnId;
  3399. while (true) {
  3400. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  3401. stepper.breakIt(i, continueCallback);
  3402. return i;
  3403. }
  3404. fnId = fnArray[i];
  3405. if (fnId !== OPS.dependency) {
  3406. this[fnId].apply(this, argsArray[i]);
  3407. } else {
  3408. var deps = argsArray[i];
  3409. for (var n = 0, nn = deps.length; n < nn; n++) {
  3410. var depObjId = deps[n];
  3411. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  3412. var objsPool = common ? commonObjs : objs;
  3413. // If the promise isn't resolved yet, add the continueCallback
  3414. // to the promise and bail out.
  3415. if (!objsPool.isResolved(depObjId)) {
  3416. objsPool.get(depObjId, continueCallback);
  3417. return i;
  3418. }
  3419. }
  3420. }
  3421. i++;
  3422. // If the entire operatorList was executed, stop as were done.
  3423. if (i === argsArrayLen) {
  3424. return i;
  3425. }
  3426. // If the execution took longer then a certain amount of time and
  3427. // `continueCallback` is specified, interrupt the execution.
  3428. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  3429. if (Date.now() > endTime) {
  3430. continueCallback();
  3431. return i;
  3432. }
  3433. steps = 0;
  3434. }
  3435. // If the operatorList isn't executed completely yet OR the execution
  3436. // time was short enough, do another execution round.
  3437. }
  3438. },
  3439. endDrawing: function CanvasGraphics_endDrawing() {
  3440. this.ctx.restore();
  3441. CachedCanvases.clear();
  3442. WebGLUtils.clear();
  3443. if (this.imageLayer) {
  3444. this.imageLayer.endLayout();
  3445. }
  3446. },
  3447. // Graphics state
  3448. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  3449. this.current.lineWidth = width;
  3450. this.ctx.lineWidth = width;
  3451. },
  3452. setLineCap: function CanvasGraphics_setLineCap(style) {
  3453. this.ctx.lineCap = LINE_CAP_STYLES[style];
  3454. },
  3455. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  3456. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  3457. },
  3458. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  3459. this.ctx.miterLimit = limit;
  3460. },
  3461. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  3462. var ctx = this.ctx;
  3463. if (ctx.setLineDash !== undefined) {
  3464. ctx.setLineDash(dashArray);
  3465. ctx.lineDashOffset = dashPhase;
  3466. } else {
  3467. ctx.mozDash = dashArray;
  3468. ctx.mozDashOffset = dashPhase;
  3469. }
  3470. },
  3471. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  3472. // Maybe if we one day fully support color spaces this will be important
  3473. // for now we can ignore.
  3474. // TODO set rendering intent?
  3475. },
  3476. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  3477. // There's no way to control this with canvas, but we can safely ignore.
  3478. // TODO set flatness?
  3479. },
  3480. setGState: function CanvasGraphics_setGState(states) {
  3481. for (var i = 0, ii = states.length; i < ii; i++) {
  3482. var state = states[i];
  3483. var key = state[0];
  3484. var value = state[1];
  3485. switch (key) {
  3486. case 'LW':
  3487. this.setLineWidth(value);
  3488. break;
  3489. case 'LC':
  3490. this.setLineCap(value);
  3491. break;
  3492. case 'LJ':
  3493. this.setLineJoin(value);
  3494. break;
  3495. case 'ML':
  3496. this.setMiterLimit(value);
  3497. break;
  3498. case 'D':
  3499. this.setDash(value[0], value[1]);
  3500. break;
  3501. case 'RI':
  3502. this.setRenderingIntent(value);
  3503. break;
  3504. case 'FL':
  3505. this.setFlatness(value);
  3506. break;
  3507. case 'Font':
  3508. this.setFont(value[0], value[1]);
  3509. break;
  3510. case 'CA':
  3511. this.current.strokeAlpha = state[1];
  3512. break;
  3513. case 'ca':
  3514. this.current.fillAlpha = state[1];
  3515. this.ctx.globalAlpha = state[1];
  3516. break;
  3517. case 'BM':
  3518. if (value && value.name && (value.name !== 'Normal')) {
  3519. var mode = value.name.replace(/([A-Z])/g,
  3520. function(c) {
  3521. return '-' + c.toLowerCase();
  3522. }
  3523. ).substring(1);
  3524. this.ctx.globalCompositeOperation = mode;
  3525. if (this.ctx.globalCompositeOperation !== mode) {
  3526. warn('globalCompositeOperation "' + mode +
  3527. '" is not supported');
  3528. }
  3529. } else {
  3530. this.ctx.globalCompositeOperation = 'source-over';
  3531. }
  3532. break;
  3533. case 'SMask':
  3534. if (this.current.activeSMask) {
  3535. this.endSMaskGroup();
  3536. }
  3537. this.current.activeSMask = value ? this.tempSMask : null;
  3538. if (this.current.activeSMask) {
  3539. this.beginSMaskGroup();
  3540. }
  3541. this.tempSMask = null;
  3542. break;
  3543. }
  3544. }
  3545. },
  3546. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  3547. var activeSMask = this.current.activeSMask;
  3548. var drawnWidth = activeSMask.canvas.width;
  3549. var drawnHeight = activeSMask.canvas.height;
  3550. var cacheId = 'smaskGroupAt' + this.groupLevel;
  3551. var scratchCanvas = CachedCanvases.getCanvas(
  3552. cacheId, drawnWidth, drawnHeight, true);
  3553. var currentCtx = this.ctx;
  3554. var currentTransform = currentCtx.mozCurrentTransform;
  3555. this.ctx.save();
  3556. var groupCtx = scratchCanvas.context;
  3557. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  3558. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  3559. groupCtx.transform.apply(groupCtx, currentTransform);
  3560. copyCtxState(currentCtx, groupCtx);
  3561. this.ctx = groupCtx;
  3562. this.setGState([
  3563. ['BM', 'Normal'],
  3564. ['ca', 1],
  3565. ['CA', 1]
  3566. ]);
  3567. this.groupStack.push(currentCtx);
  3568. this.groupLevel++;
  3569. },
  3570. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  3571. var groupCtx = this.ctx;
  3572. this.groupLevel--;
  3573. this.ctx = this.groupStack.pop();
  3574. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  3575. this.ctx.restore();
  3576. },
  3577. save: function CanvasGraphics_save() {
  3578. this.ctx.save();
  3579. var old = this.current;
  3580. this.stateStack.push(old);
  3581. this.current = old.clone();
  3582. this.current.activeSMask = null;
  3583. },
  3584. restore: function CanvasGraphics_restore() {
  3585. if (this.stateStack.length !== 0) {
  3586. if (this.current.activeSMask !== null) {
  3587. this.endSMaskGroup();
  3588. }
  3589. this.current = this.stateStack.pop();
  3590. this.ctx.restore();
  3591. this.cachedGetSinglePixelWidth = null;
  3592. }
  3593. },
  3594. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  3595. this.ctx.transform(a, b, c, d, e, f);
  3596. this.cachedGetSinglePixelWidth = null;
  3597. },
  3598. // Path
  3599. constructPath: function CanvasGraphics_constructPath(ops, args) {
  3600. var ctx = this.ctx;
  3601. var current = this.current;
  3602. var x = current.x, y = current.y;
  3603. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  3604. switch (ops[i] | 0) {
  3605. case OPS.rectangle:
  3606. x = args[j++];
  3607. y = args[j++];
  3608. var width = args[j++];
  3609. var height = args[j++];
  3610. if (width === 0) {
  3611. width = this.getSinglePixelWidth();
  3612. }
  3613. if (height === 0) {
  3614. height = this.getSinglePixelWidth();
  3615. }
  3616. var xw = x + width;
  3617. var yh = y + height;
  3618. this.ctx.moveTo(x, y);
  3619. this.ctx.lineTo(xw, y);
  3620. this.ctx.lineTo(xw, yh);
  3621. this.ctx.lineTo(x, yh);
  3622. this.ctx.lineTo(x, y);
  3623. this.ctx.closePath();
  3624. break;
  3625. case OPS.moveTo:
  3626. x = args[j++];
  3627. y = args[j++];
  3628. ctx.moveTo(x, y);
  3629. break;
  3630. case OPS.lineTo:
  3631. x = args[j++];
  3632. y = args[j++];
  3633. ctx.lineTo(x, y);
  3634. break;
  3635. case OPS.curveTo:
  3636. x = args[j + 4];
  3637. y = args[j + 5];
  3638. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  3639. x, y);
  3640. j += 6;
  3641. break;
  3642. case OPS.curveTo2:
  3643. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  3644. args[j + 2], args[j + 3]);
  3645. x = args[j + 2];
  3646. y = args[j + 3];
  3647. j += 4;
  3648. break;
  3649. case OPS.curveTo3:
  3650. x = args[j + 2];
  3651. y = args[j + 3];
  3652. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  3653. j += 4;
  3654. break;
  3655. case OPS.closePath:
  3656. ctx.closePath();
  3657. break;
  3658. }
  3659. }
  3660. current.setCurrentPoint(x, y);
  3661. },
  3662. closePath: function CanvasGraphics_closePath() {
  3663. this.ctx.closePath();
  3664. },
  3665. stroke: function CanvasGraphics_stroke(consumePath) {
  3666. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3667. var ctx = this.ctx;
  3668. var strokeColor = this.current.strokeColor;
  3669. // Prevent drawing too thin lines by enforcing a minimum line width.
  3670. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  3671. this.current.lineWidth);
  3672. // For stroke we want to temporarily change the global alpha to the
  3673. // stroking alpha.
  3674. ctx.globalAlpha = this.current.strokeAlpha;
  3675. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  3676. strokeColor.type === 'Pattern') {
  3677. // for patterns, we transform to pattern space, calculate
  3678. // the pattern, call stroke, and restore to user space
  3679. ctx.save();
  3680. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  3681. ctx.stroke();
  3682. ctx.restore();
  3683. } else {
  3684. ctx.stroke();
  3685. }
  3686. if (consumePath) {
  3687. this.consumePath();
  3688. }
  3689. // Restore the global alpha to the fill alpha
  3690. ctx.globalAlpha = this.current.fillAlpha;
  3691. },
  3692. closeStroke: function CanvasGraphics_closeStroke() {
  3693. this.closePath();
  3694. this.stroke();
  3695. },
  3696. fill: function CanvasGraphics_fill(consumePath) {
  3697. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3698. var ctx = this.ctx;
  3699. var fillColor = this.current.fillColor;
  3700. var isPatternFill = this.current.patternFill;
  3701. var needRestore = false;
  3702. if (isPatternFill) {
  3703. ctx.save();
  3704. ctx.fillStyle = fillColor.getPattern(ctx, this);
  3705. needRestore = true;
  3706. }
  3707. if (this.pendingEOFill) {
  3708. if (ctx.mozFillRule !== undefined) {
  3709. ctx.mozFillRule = 'evenodd';
  3710. ctx.fill();
  3711. ctx.mozFillRule = 'nonzero';
  3712. } else {
  3713. try {
  3714. ctx.fill('evenodd');
  3715. } catch (ex) {
  3716. // shouldn't really happen, but browsers might think differently
  3717. ctx.fill();
  3718. }
  3719. }
  3720. this.pendingEOFill = false;
  3721. } else {
  3722. ctx.fill();
  3723. }
  3724. if (needRestore) {
  3725. ctx.restore();
  3726. }
  3727. if (consumePath) {
  3728. this.consumePath();
  3729. }
  3730. },
  3731. eoFill: function CanvasGraphics_eoFill() {
  3732. this.pendingEOFill = true;
  3733. this.fill();
  3734. },
  3735. fillStroke: function CanvasGraphics_fillStroke() {
  3736. this.fill(false);
  3737. this.stroke(false);
  3738. this.consumePath();
  3739. },
  3740. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  3741. this.pendingEOFill = true;
  3742. this.fillStroke();
  3743. },
  3744. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  3745. this.closePath();
  3746. this.fillStroke();
  3747. },
  3748. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  3749. this.pendingEOFill = true;
  3750. this.closePath();
  3751. this.fillStroke();
  3752. },
  3753. endPath: function CanvasGraphics_endPath() {
  3754. this.consumePath();
  3755. },
  3756. // Clipping
  3757. clip: function CanvasGraphics_clip() {
  3758. this.pendingClip = NORMAL_CLIP;
  3759. },
  3760. eoClip: function CanvasGraphics_eoClip() {
  3761. this.pendingClip = EO_CLIP;
  3762. },
  3763. // Text
  3764. beginText: function CanvasGraphics_beginText() {
  3765. this.current.textMatrix = IDENTITY_MATRIX;
  3766. this.current.textMatrixScale = 1;
  3767. this.current.x = this.current.lineX = 0;
  3768. this.current.y = this.current.lineY = 0;
  3769. },
  3770. endText: function CanvasGraphics_endText() {
  3771. var paths = this.pendingTextPaths;
  3772. var ctx = this.ctx;
  3773. if (paths === undefined) {
  3774. ctx.beginPath();
  3775. return;
  3776. }
  3777. ctx.save();
  3778. ctx.beginPath();
  3779. for (var i = 0; i < paths.length; i++) {
  3780. var path = paths[i];
  3781. ctx.setTransform.apply(ctx, path.transform);
  3782. ctx.translate(path.x, path.y);
  3783. path.addToPath(ctx, path.fontSize);
  3784. }
  3785. ctx.restore();
  3786. ctx.clip();
  3787. ctx.beginPath();
  3788. delete this.pendingTextPaths;
  3789. },
  3790. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  3791. this.current.charSpacing = spacing;
  3792. },
  3793. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  3794. this.current.wordSpacing = spacing;
  3795. },
  3796. setHScale: function CanvasGraphics_setHScale(scale) {
  3797. this.current.textHScale = scale / 100;
  3798. },
  3799. setLeading: function CanvasGraphics_setLeading(leading) {
  3800. this.current.leading = -leading;
  3801. },
  3802. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  3803. var fontObj = this.commonObjs.get(fontRefName);
  3804. var current = this.current;
  3805. if (!fontObj) {
  3806. error('Can\'t find font for ' + fontRefName);
  3807. }
  3808. current.fontMatrix = (fontObj.fontMatrix ?
  3809. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  3810. // A valid matrix needs all main diagonal elements to be non-zero
  3811. // This also ensures we bypass FF bugzilla bug #719844.
  3812. if (current.fontMatrix[0] === 0 ||
  3813. current.fontMatrix[3] === 0) {
  3814. warn('Invalid font matrix for font ' + fontRefName);
  3815. }
  3816. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  3817. // and in some docs this can be negative (inverted x-y axes).
  3818. if (size < 0) {
  3819. size = -size;
  3820. current.fontDirection = -1;
  3821. } else {
  3822. current.fontDirection = 1;
  3823. }
  3824. this.current.font = fontObj;
  3825. this.current.fontSize = size;
  3826. if (fontObj.isType3Font) {
  3827. return; // we don't need ctx.font for Type3 fonts
  3828. }
  3829. var name = fontObj.loadedName || 'sans-serif';
  3830. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  3831. (fontObj.bold ? 'bold' : 'normal');
  3832. var italic = fontObj.italic ? 'italic' : 'normal';
  3833. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  3834. // Some font backends cannot handle fonts below certain size.
  3835. // Keeping the font at minimal size and using the fontSizeScale to change
  3836. // the current transformation matrix before the fillText/strokeText.
  3837. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  3838. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  3839. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  3840. this.current.fontSizeScale = size / browserFontSize;
  3841. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  3842. this.ctx.font = rule;
  3843. },
  3844. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  3845. this.current.textRenderingMode = mode;
  3846. },
  3847. setTextRise: function CanvasGraphics_setTextRise(rise) {
  3848. this.current.textRise = rise;
  3849. },
  3850. moveText: function CanvasGraphics_moveText(x, y) {
  3851. this.current.x = this.current.lineX += x;
  3852. this.current.y = this.current.lineY += y;
  3853. },
  3854. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  3855. this.setLeading(-y);
  3856. this.moveText(x, y);
  3857. },
  3858. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  3859. this.current.textMatrix = [a, b, c, d, e, f];
  3860. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  3861. this.current.x = this.current.lineX = 0;
  3862. this.current.y = this.current.lineY = 0;
  3863. },
  3864. nextLine: function CanvasGraphics_nextLine() {
  3865. this.moveText(0, this.current.leading);
  3866. },
  3867. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  3868. var ctx = this.ctx;
  3869. var current = this.current;
  3870. var font = current.font;
  3871. var textRenderingMode = current.textRenderingMode;
  3872. var fontSize = current.fontSize / current.fontSizeScale;
  3873. var fillStrokeMode = textRenderingMode &
  3874. TextRenderingMode.FILL_STROKE_MASK;
  3875. var isAddToPathSet = !!(textRenderingMode &
  3876. TextRenderingMode.ADD_TO_PATH_FLAG);
  3877. var addToPath;
  3878. if (font.disableFontFace || isAddToPathSet) {
  3879. addToPath = font.getPathGenerator(this.commonObjs, character);
  3880. }
  3881. if (font.disableFontFace) {
  3882. ctx.save();
  3883. ctx.translate(x, y);
  3884. ctx.beginPath();
  3885. addToPath(ctx, fontSize);
  3886. if (fillStrokeMode === TextRenderingMode.FILL ||
  3887. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3888. ctx.fill();
  3889. }
  3890. if (fillStrokeMode === TextRenderingMode.STROKE ||
  3891. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3892. ctx.stroke();
  3893. }
  3894. ctx.restore();
  3895. } else {
  3896. if (fillStrokeMode === TextRenderingMode.FILL ||
  3897. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3898. ctx.fillText(character, x, y);
  3899. }
  3900. if (fillStrokeMode === TextRenderingMode.STROKE ||
  3901. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3902. ctx.strokeText(character, x, y);
  3903. }
  3904. }
  3905. if (isAddToPathSet) {
  3906. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  3907. paths.push({
  3908. transform: ctx.mozCurrentTransform,
  3909. x: x,
  3910. y: y,
  3911. fontSize: fontSize,
  3912. addToPath: addToPath
  3913. });
  3914. }
  3915. },
  3916. get isFontSubpixelAAEnabled() {
  3917. // Checks if anti-aliasing is enabled when scaled text is painted.
  3918. // On Windows GDI scaled fonts looks bad.
  3919. var ctx = document.createElement('canvas').getContext('2d');
  3920. ctx.scale(1.5, 1);
  3921. ctx.fillText('I', 0, 10);
  3922. var data = ctx.getImageData(0, 0, 10, 10).data;
  3923. var enabled = false;
  3924. for (var i = 3; i < data.length; i += 4) {
  3925. if (data[i] > 0 && data[i] < 255) {
  3926. enabled = true;
  3927. break;
  3928. }
  3929. }
  3930. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  3931. },
  3932. showText: function CanvasGraphics_showText(glyphs) {
  3933. var current = this.current;
  3934. var font = current.font;
  3935. if (font.isType3Font) {
  3936. return this.showType3Text(glyphs);
  3937. }
  3938. var fontSize = current.fontSize;
  3939. if (fontSize === 0) {
  3940. return;
  3941. }
  3942. var ctx = this.ctx;
  3943. var fontSizeScale = current.fontSizeScale;
  3944. var charSpacing = current.charSpacing;
  3945. var wordSpacing = current.wordSpacing;
  3946. var fontDirection = current.fontDirection;
  3947. var textHScale = current.textHScale * fontDirection;
  3948. var glyphsLength = glyphs.length;
  3949. var vertical = font.vertical;
  3950. var defaultVMetrics = font.defaultVMetrics;
  3951. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3952. var simpleFillText =
  3953. current.textRenderingMode === TextRenderingMode.FILL &&
  3954. !font.disableFontFace;
  3955. ctx.save();
  3956. ctx.transform.apply(ctx, current.textMatrix);
  3957. ctx.translate(current.x, current.y + current.textRise);
  3958. if (fontDirection > 0) {
  3959. ctx.scale(textHScale, -1);
  3960. } else {
  3961. ctx.scale(textHScale, 1);
  3962. }
  3963. var lineWidth = current.lineWidth;
  3964. var scale = current.textMatrixScale;
  3965. if (scale === 0 || lineWidth === 0) {
  3966. var fillStrokeMode = current.textRenderingMode &
  3967. TextRenderingMode.FILL_STROKE_MASK;
  3968. if (fillStrokeMode === TextRenderingMode.STROKE ||
  3969. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  3970. this.cachedGetSinglePixelWidth = null;
  3971. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  3972. }
  3973. } else {
  3974. lineWidth /= scale;
  3975. }
  3976. if (fontSizeScale !== 1.0) {
  3977. ctx.scale(fontSizeScale, fontSizeScale);
  3978. lineWidth /= fontSizeScale;
  3979. }
  3980. ctx.lineWidth = lineWidth;
  3981. var x = 0, i;
  3982. for (i = 0; i < glyphsLength; ++i) {
  3983. var glyph = glyphs[i];
  3984. if (glyph === null) {
  3985. // word break
  3986. x += fontDirection * wordSpacing;
  3987. continue;
  3988. } else if (isNum(glyph)) {
  3989. x += -glyph * fontSize * 0.001;
  3990. continue;
  3991. }
  3992. var restoreNeeded = false;
  3993. var character = glyph.fontChar;
  3994. var accent = glyph.accent;
  3995. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  3996. var width = glyph.width;
  3997. if (vertical) {
  3998. var vmetric, vx, vy;
  3999. vmetric = glyph.vmetric || defaultVMetrics;
  4000. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  4001. vx = -vx * widthAdvanceScale;
  4002. vy = vmetric[2] * widthAdvanceScale;
  4003. width = vmetric ? -vmetric[0] : width;
  4004. scaledX = vx / fontSizeScale;
  4005. scaledY = (x + vy) / fontSizeScale;
  4006. } else {
  4007. scaledX = x / fontSizeScale;
  4008. scaledY = 0;
  4009. }
  4010. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  4011. // some standard fonts may not have the exact width, trying to
  4012. // rescale per character
  4013. var measuredWidth = ctx.measureText(character).width * 1000 /
  4014. fontSize * fontSizeScale;
  4015. var characterScaleX = width / measuredWidth;
  4016. restoreNeeded = true;
  4017. ctx.save();
  4018. ctx.scale(characterScaleX, 1);
  4019. scaledX /= characterScaleX;
  4020. }
  4021. if (simpleFillText && !accent) {
  4022. // common case
  4023. ctx.fillText(character, scaledX, scaledY);
  4024. } else {
  4025. this.paintChar(character, scaledX, scaledY);
  4026. if (accent) {
  4027. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  4028. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  4029. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  4030. }
  4031. }
  4032. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  4033. x += charWidth;
  4034. if (restoreNeeded) {
  4035. ctx.restore();
  4036. }
  4037. }
  4038. if (vertical) {
  4039. current.y -= x * textHScale;
  4040. } else {
  4041. current.x += x * textHScale;
  4042. }
  4043. ctx.restore();
  4044. },
  4045. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  4046. // Type3 fonts - each glyph is a "mini-PDF"
  4047. var ctx = this.ctx;
  4048. var current = this.current;
  4049. var font = current.font;
  4050. var fontSize = current.fontSize;
  4051. var fontDirection = current.fontDirection;
  4052. var charSpacing = current.charSpacing;
  4053. var wordSpacing = current.wordSpacing;
  4054. var textHScale = current.textHScale * fontDirection;
  4055. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  4056. var glyphsLength = glyphs.length;
  4057. var isTextInvisible =
  4058. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  4059. var i, glyph, width;
  4060. if (isTextInvisible || fontSize === 0) {
  4061. return;
  4062. }
  4063. ctx.save();
  4064. ctx.transform.apply(ctx, current.textMatrix);
  4065. ctx.translate(current.x, current.y);
  4066. ctx.scale(textHScale, fontDirection);
  4067. for (i = 0; i < glyphsLength; ++i) {
  4068. glyph = glyphs[i];
  4069. if (glyph === null) {
  4070. // word break
  4071. this.ctx.translate(wordSpacing, 0);
  4072. current.x += wordSpacing * textHScale;
  4073. continue;
  4074. } else if (isNum(glyph)) {
  4075. var spacingLength = -glyph * 0.001 * fontSize;
  4076. this.ctx.translate(spacingLength, 0);
  4077. current.x += spacingLength * textHScale;
  4078. continue;
  4079. }
  4080. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4081. if (!operatorList) {
  4082. warn('Type3 character \"' + glyph.operatorListId +
  4083. '\" is not available');
  4084. continue;
  4085. }
  4086. this.processingType3 = glyph;
  4087. this.save();
  4088. ctx.scale(fontSize, fontSize);
  4089. ctx.transform.apply(ctx, fontMatrix);
  4090. this.executeOperatorList(operatorList);
  4091. this.restore();
  4092. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4093. width = transformed[0] * fontSize + charSpacing;
  4094. ctx.translate(width, 0);
  4095. current.x += width * textHScale;
  4096. }
  4097. ctx.restore();
  4098. this.processingType3 = null;
  4099. },
  4100. // Type3 fonts
  4101. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4102. // We can safely ignore this since the width should be the same
  4103. // as the width in the Widths array.
  4104. },
  4105. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4106. yWidth,
  4107. llx,
  4108. lly,
  4109. urx,
  4110. ury) {
  4111. // TODO According to the spec we're also suppose to ignore any operators
  4112. // that set color or include images while processing this type3 font.
  4113. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  4114. this.clip();
  4115. this.endPath();
  4116. },
  4117. // Color
  4118. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4119. var pattern;
  4120. if (IR[0] === 'TilingPattern') {
  4121. var color = IR[1];
  4122. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4123. this.commonObjs, this.baseTransform);
  4124. } else {
  4125. pattern = getShadingPatternFromIR(IR);
  4126. }
  4127. return pattern;
  4128. },
  4129. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4130. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4131. },
  4132. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4133. this.current.fillColor = this.getColorN_Pattern(arguments);
  4134. this.current.patternFill = true;
  4135. },
  4136. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4137. var color = Util.makeCssRgb(r, g, b);
  4138. this.ctx.strokeStyle = color;
  4139. this.current.strokeColor = color;
  4140. },
  4141. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4142. var color = Util.makeCssRgb(r, g, b);
  4143. this.ctx.fillStyle = color;
  4144. this.current.fillColor = color;
  4145. this.current.patternFill = false;
  4146. },
  4147. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4148. var ctx = this.ctx;
  4149. this.save();
  4150. var pattern = getShadingPatternFromIR(patternIR);
  4151. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4152. var inv = ctx.mozCurrentTransformInverse;
  4153. if (inv) {
  4154. var canvas = ctx.canvas;
  4155. var width = canvas.width;
  4156. var height = canvas.height;
  4157. var bl = Util.applyTransform([0, 0], inv);
  4158. var br = Util.applyTransform([0, height], inv);
  4159. var ul = Util.applyTransform([width, 0], inv);
  4160. var ur = Util.applyTransform([width, height], inv);
  4161. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4162. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4163. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4164. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4165. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4166. } else {
  4167. // HACK to draw the gradient onto an infinite rectangle.
  4168. // PDF gradients are drawn across the entire image while
  4169. // Canvas only allows gradients to be drawn in a rectangle
  4170. // The following bug should allow us to remove this.
  4171. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4172. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4173. }
  4174. this.restore();
  4175. },
  4176. // Images
  4177. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4178. error('Should not call beginInlineImage');
  4179. },
  4180. beginImageData: function CanvasGraphics_beginImageData() {
  4181. error('Should not call beginImageData');
  4182. },
  4183. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4184. bbox) {
  4185. this.save();
  4186. this.baseTransformStack.push(this.baseTransform);
  4187. if (isArray(matrix) && 6 === matrix.length) {
  4188. this.transform.apply(this, matrix);
  4189. }
  4190. this.baseTransform = this.ctx.mozCurrentTransform;
  4191. if (isArray(bbox) && 4 === bbox.length) {
  4192. var width = bbox[2] - bbox[0];
  4193. var height = bbox[3] - bbox[1];
  4194. this.ctx.rect(bbox[0], bbox[1], width, height);
  4195. this.clip();
  4196. this.endPath();
  4197. }
  4198. },
  4199. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4200. this.restore();
  4201. this.baseTransform = this.baseTransformStack.pop();
  4202. },
  4203. beginGroup: function CanvasGraphics_beginGroup(group) {
  4204. this.save();
  4205. var currentCtx = this.ctx;
  4206. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4207. // group results aren't usually that different and they even have tools
  4208. // that ignore this setting. Notes from Rik on implmenting:
  4209. // - When you encounter an transparency group, create a new canvas with
  4210. // the dimensions of the bbox
  4211. // - copy the content from the previous canvas to the new canvas
  4212. // - draw as usual
  4213. // - remove the backdrop alpha:
  4214. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4215. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4216. // backdrop
  4217. // - remove background color:
  4218. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4219. if (!group.isolated) {
  4220. info('TODO: Support non-isolated groups.');
  4221. }
  4222. // TODO knockout - supposedly possible with the clever use of compositing
  4223. // modes.
  4224. if (group.knockout) {
  4225. warn('Knockout groups not supported.');
  4226. }
  4227. var currentTransform = currentCtx.mozCurrentTransform;
  4228. if (group.matrix) {
  4229. currentCtx.transform.apply(currentCtx, group.matrix);
  4230. }
  4231. assert(group.bbox, 'Bounding box is required.');
  4232. // Based on the current transform figure out how big the bounding box
  4233. // will actually be.
  4234. var bounds = Util.getAxialAlignedBoundingBox(
  4235. group.bbox,
  4236. currentCtx.mozCurrentTransform);
  4237. // Clip the bounding box to the current canvas.
  4238. var canvasBounds = [0,
  4239. 0,
  4240. currentCtx.canvas.width,
  4241. currentCtx.canvas.height];
  4242. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4243. // Use ceil in case we're between sizes so we don't create canvas that is
  4244. // too small and make the canvas at least 1x1 pixels.
  4245. var offsetX = Math.floor(bounds[0]);
  4246. var offsetY = Math.floor(bounds[1]);
  4247. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4248. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4249. var scaleX = 1, scaleY = 1;
  4250. if (drawnWidth > MAX_GROUP_SIZE) {
  4251. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4252. drawnWidth = MAX_GROUP_SIZE;
  4253. }
  4254. if (drawnHeight > MAX_GROUP_SIZE) {
  4255. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4256. drawnHeight = MAX_GROUP_SIZE;
  4257. }
  4258. var cacheId = 'groupAt' + this.groupLevel;
  4259. if (group.smask) {
  4260. // Using two cache entries is case if masks are used one after another.
  4261. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4262. }
  4263. var scratchCanvas = CachedCanvases.getCanvas(
  4264. cacheId, drawnWidth, drawnHeight, true);
  4265. var groupCtx = scratchCanvas.context;
  4266. // Since we created a new canvas that is just the size of the bounding box
  4267. // we have to translate the group ctx.
  4268. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4269. groupCtx.translate(-offsetX, -offsetY);
  4270. groupCtx.transform.apply(groupCtx, currentTransform);
  4271. if (group.smask) {
  4272. // Saving state and cached mask to be used in setGState.
  4273. this.smaskStack.push({
  4274. canvas: scratchCanvas.canvas,
  4275. context: groupCtx,
  4276. offsetX: offsetX,
  4277. offsetY: offsetY,
  4278. scaleX: scaleX,
  4279. scaleY: scaleY,
  4280. subtype: group.smask.subtype,
  4281. backdrop: group.smask.backdrop
  4282. });
  4283. } else {
  4284. // Setup the current ctx so when the group is popped we draw it at the
  4285. // right location.
  4286. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4287. currentCtx.translate(offsetX, offsetY);
  4288. currentCtx.scale(scaleX, scaleY);
  4289. }
  4290. // The transparency group inherits all off the current graphics state
  4291. // except the blend mode, soft mask, and alpha constants.
  4292. copyCtxState(currentCtx, groupCtx);
  4293. this.ctx = groupCtx;
  4294. this.setGState([
  4295. ['BM', 'Normal'],
  4296. ['ca', 1],
  4297. ['CA', 1]
  4298. ]);
  4299. this.groupStack.push(currentCtx);
  4300. this.groupLevel++;
  4301. },
  4302. endGroup: function CanvasGraphics_endGroup(group) {
  4303. this.groupLevel--;
  4304. var groupCtx = this.ctx;
  4305. this.ctx = this.groupStack.pop();
  4306. // Turn off image smoothing to avoid sub pixel interpolation which can
  4307. // look kind of blurry for some pdfs.
  4308. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4309. this.ctx.imageSmoothingEnabled = false;
  4310. } else {
  4311. this.ctx.mozImageSmoothingEnabled = false;
  4312. }
  4313. if (group.smask) {
  4314. this.tempSMask = this.smaskStack.pop();
  4315. } else {
  4316. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4317. }
  4318. this.restore();
  4319. },
  4320. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4321. this.save();
  4322. this.current = new CanvasExtraState();
  4323. },
  4324. endAnnotations: function CanvasGraphics_endAnnotations() {
  4325. this.restore();
  4326. },
  4327. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4328. matrix) {
  4329. this.save();
  4330. if (isArray(rect) && 4 === rect.length) {
  4331. var width = rect[2] - rect[0];
  4332. var height = rect[3] - rect[1];
  4333. this.ctx.rect(rect[0], rect[1], width, height);
  4334. this.clip();
  4335. this.endPath();
  4336. }
  4337. this.transform.apply(this, transform);
  4338. this.transform.apply(this, matrix);
  4339. },
  4340. endAnnotation: function CanvasGraphics_endAnnotation() {
  4341. this.restore();
  4342. },
  4343. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4344. var domImage = this.objs.get(objId);
  4345. if (!domImage) {
  4346. warn('Dependent image isn\'t ready yet');
  4347. return;
  4348. }
  4349. this.save();
  4350. var ctx = this.ctx;
  4351. // scale the image to the unit square
  4352. ctx.scale(1 / w, -1 / h);
  4353. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4354. 0, -h, w, h);
  4355. if (this.imageLayer) {
  4356. var currentTransform = ctx.mozCurrentTransformInverse;
  4357. var position = this.getCanvasPosition(0, 0);
  4358. this.imageLayer.appendImage({
  4359. objId: objId,
  4360. left: position[0],
  4361. top: position[1],
  4362. width: w / currentTransform[0],
  4363. height: h / currentTransform[3]
  4364. });
  4365. }
  4366. this.restore();
  4367. },
  4368. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  4369. var ctx = this.ctx;
  4370. var width = img.width, height = img.height;
  4371. var fillColor = this.current.fillColor;
  4372. var isPatternFill = this.current.patternFill;
  4373. var glyph = this.processingType3;
  4374. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  4375. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  4376. glyph.compiled =
  4377. compileType3Glyph({data: img.data, width: width, height: height});
  4378. } else {
  4379. glyph.compiled = null;
  4380. }
  4381. }
  4382. if (glyph && glyph.compiled) {
  4383. glyph.compiled(ctx);
  4384. return;
  4385. }
  4386. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4387. var maskCtx = maskCanvas.context;
  4388. maskCtx.save();
  4389. putBinaryImageMask(maskCtx, img);
  4390. maskCtx.globalCompositeOperation = 'source-in';
  4391. maskCtx.fillStyle = isPatternFill ?
  4392. fillColor.getPattern(maskCtx, this) : fillColor;
  4393. maskCtx.fillRect(0, 0, width, height);
  4394. maskCtx.restore();
  4395. this.paintInlineImageXObject(maskCanvas.canvas);
  4396. },
  4397. paintImageMaskXObjectRepeat:
  4398. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  4399. scaleY, positions) {
  4400. var width = imgData.width;
  4401. var height = imgData.height;
  4402. var fillColor = this.current.fillColor;
  4403. var isPatternFill = this.current.patternFill;
  4404. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4405. var maskCtx = maskCanvas.context;
  4406. maskCtx.save();
  4407. putBinaryImageMask(maskCtx, imgData);
  4408. maskCtx.globalCompositeOperation = 'source-in';
  4409. maskCtx.fillStyle = isPatternFill ?
  4410. fillColor.getPattern(maskCtx, this) : fillColor;
  4411. maskCtx.fillRect(0, 0, width, height);
  4412. maskCtx.restore();
  4413. var ctx = this.ctx;
  4414. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4415. ctx.save();
  4416. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  4417. ctx.scale(1, -1);
  4418. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4419. 0, -1, 1, 1);
  4420. ctx.restore();
  4421. }
  4422. },
  4423. paintImageMaskXObjectGroup:
  4424. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  4425. var ctx = this.ctx;
  4426. var fillColor = this.current.fillColor;
  4427. var isPatternFill = this.current.patternFill;
  4428. for (var i = 0, ii = images.length; i < ii; i++) {
  4429. var image = images[i];
  4430. var width = image.width, height = image.height;
  4431. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4432. var maskCtx = maskCanvas.context;
  4433. maskCtx.save();
  4434. putBinaryImageMask(maskCtx, image);
  4435. maskCtx.globalCompositeOperation = 'source-in';
  4436. maskCtx.fillStyle = isPatternFill ?
  4437. fillColor.getPattern(maskCtx, this) : fillColor;
  4438. maskCtx.fillRect(0, 0, width, height);
  4439. maskCtx.restore();
  4440. ctx.save();
  4441. ctx.transform.apply(ctx, image.transform);
  4442. ctx.scale(1, -1);
  4443. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4444. 0, -1, 1, 1);
  4445. ctx.restore();
  4446. }
  4447. },
  4448. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  4449. var imgData = this.objs.get(objId);
  4450. if (!imgData) {
  4451. warn('Dependent image isn\'t ready yet');
  4452. return;
  4453. }
  4454. this.paintInlineImageXObject(imgData);
  4455. },
  4456. paintImageXObjectRepeat:
  4457. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  4458. positions) {
  4459. var imgData = this.objs.get(objId);
  4460. if (!imgData) {
  4461. warn('Dependent image isn\'t ready yet');
  4462. return;
  4463. }
  4464. var width = imgData.width;
  4465. var height = imgData.height;
  4466. var map = [];
  4467. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4468. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  4469. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  4470. }
  4471. this.paintInlineImageXObjectGroup(imgData, map);
  4472. },
  4473. paintInlineImageXObject:
  4474. function CanvasGraphics_paintInlineImageXObject(imgData) {
  4475. var width = imgData.width;
  4476. var height = imgData.height;
  4477. var ctx = this.ctx;
  4478. this.save();
  4479. // scale the image to the unit square
  4480. ctx.scale(1 / width, -1 / height);
  4481. var currentTransform = ctx.mozCurrentTransformInverse;
  4482. var a = currentTransform[0], b = currentTransform[1];
  4483. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  4484. var c = currentTransform[2], d = currentTransform[3];
  4485. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  4486. var imgToPaint, tmpCanvas;
  4487. // instanceof HTMLElement does not work in jsdom node.js module
  4488. if (imgData instanceof HTMLElement || !imgData.data) {
  4489. imgToPaint = imgData;
  4490. } else {
  4491. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  4492. var tmpCtx = tmpCanvas.context;
  4493. putBinaryImageData(tmpCtx, imgData);
  4494. imgToPaint = tmpCanvas.canvas;
  4495. }
  4496. var paintWidth = width, paintHeight = height;
  4497. var tmpCanvasId = 'prescale1';
  4498. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  4499. // pixels during drawImage operation, painting on the temporary canvas(es)
  4500. // that are twice smaller in size
  4501. while ((widthScale > 2 && paintWidth > 1) ||
  4502. (heightScale > 2 && paintHeight > 1)) {
  4503. var newWidth = paintWidth, newHeight = paintHeight;
  4504. if (widthScale > 2 && paintWidth > 1) {
  4505. newWidth = Math.ceil(paintWidth / 2);
  4506. widthScale /= paintWidth / newWidth;
  4507. }
  4508. if (heightScale > 2 && paintHeight > 1) {
  4509. newHeight = Math.ceil(paintHeight / 2);
  4510. heightScale /= paintHeight / newHeight;
  4511. }
  4512. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  4513. tmpCtx = tmpCanvas.context;
  4514. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  4515. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4516. 0, 0, newWidth, newHeight);
  4517. imgToPaint = tmpCanvas.canvas;
  4518. paintWidth = newWidth;
  4519. paintHeight = newHeight;
  4520. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  4521. }
  4522. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4523. 0, -height, width, height);
  4524. if (this.imageLayer) {
  4525. var position = this.getCanvasPosition(0, -height);
  4526. this.imageLayer.appendImage({
  4527. imgData: imgData,
  4528. left: position[0],
  4529. top: position[1],
  4530. width: width / currentTransform[0],
  4531. height: height / currentTransform[3]
  4532. });
  4533. }
  4534. this.restore();
  4535. },
  4536. paintInlineImageXObjectGroup:
  4537. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  4538. var ctx = this.ctx;
  4539. var w = imgData.width;
  4540. var h = imgData.height;
  4541. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  4542. var tmpCtx = tmpCanvas.context;
  4543. putBinaryImageData(tmpCtx, imgData);
  4544. for (var i = 0, ii = map.length; i < ii; i++) {
  4545. var entry = map[i];
  4546. ctx.save();
  4547. ctx.transform.apply(ctx, entry.transform);
  4548. ctx.scale(1, -1);
  4549. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  4550. 0, -1, 1, 1);
  4551. if (this.imageLayer) {
  4552. var position = this.getCanvasPosition(entry.x, entry.y);
  4553. this.imageLayer.appendImage({
  4554. imgData: imgData,
  4555. left: position[0],
  4556. top: position[1],
  4557. width: w,
  4558. height: h
  4559. });
  4560. }
  4561. ctx.restore();
  4562. }
  4563. },
  4564. paintSolidColorImageMask:
  4565. function CanvasGraphics_paintSolidColorImageMask() {
  4566. this.ctx.fillRect(0, 0, 1, 1);
  4567. },
  4568. // Marked content
  4569. markPoint: function CanvasGraphics_markPoint(tag) {
  4570. // TODO Marked content.
  4571. },
  4572. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  4573. // TODO Marked content.
  4574. },
  4575. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  4576. // TODO Marked content.
  4577. },
  4578. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  4579. tag, properties) {
  4580. // TODO Marked content.
  4581. },
  4582. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  4583. // TODO Marked content.
  4584. },
  4585. // Compatibility
  4586. beginCompat: function CanvasGraphics_beginCompat() {
  4587. // TODO ignore undefined operators (should we do that anyway?)
  4588. },
  4589. endCompat: function CanvasGraphics_endCompat() {
  4590. // TODO stop ignoring undefined operators
  4591. },
  4592. // Helper functions
  4593. consumePath: function CanvasGraphics_consumePath() {
  4594. var ctx = this.ctx;
  4595. if (this.pendingClip) {
  4596. if (this.pendingClip === EO_CLIP) {
  4597. if (ctx.mozFillRule !== undefined) {
  4598. ctx.mozFillRule = 'evenodd';
  4599. ctx.clip();
  4600. ctx.mozFillRule = 'nonzero';
  4601. } else {
  4602. try {
  4603. ctx.clip('evenodd');
  4604. } catch (ex) {
  4605. // shouldn't really happen, but browsers might think differently
  4606. ctx.clip();
  4607. }
  4608. }
  4609. } else {
  4610. ctx.clip();
  4611. }
  4612. this.pendingClip = null;
  4613. }
  4614. ctx.beginPath();
  4615. },
  4616. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  4617. if (this.cachedGetSinglePixelWidth === null) {
  4618. var inverse = this.ctx.mozCurrentTransformInverse;
  4619. // max of the current horizontal and vertical scale
  4620. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  4621. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  4622. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  4623. }
  4624. return this.cachedGetSinglePixelWidth;
  4625. },
  4626. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  4627. var transform = this.ctx.mozCurrentTransform;
  4628. return [
  4629. transform[0] * x + transform[2] * y + transform[4],
  4630. transform[1] * x + transform[3] * y + transform[5]
  4631. ];
  4632. }
  4633. };
  4634. for (var op in OPS) {
  4635. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  4636. }
  4637. return CanvasGraphics;
  4638. })();
  4639. var WebGLUtils = (function WebGLUtilsClosure() {
  4640. function loadShader(gl, code, shaderType) {
  4641. var shader = gl.createShader(shaderType);
  4642. gl.shaderSource(shader, code);
  4643. gl.compileShader(shader);
  4644. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4645. if (!compiled) {
  4646. var errorMsg = gl.getShaderInfoLog(shader);
  4647. throw new Error('Error during shader compilation: ' + errorMsg);
  4648. }
  4649. return shader;
  4650. }
  4651. function createVertexShader(gl, code) {
  4652. return loadShader(gl, code, gl.VERTEX_SHADER);
  4653. }
  4654. function createFragmentShader(gl, code) {
  4655. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4656. }
  4657. function createProgram(gl, shaders) {
  4658. var program = gl.createProgram();
  4659. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4660. gl.attachShader(program, shaders[i]);
  4661. }
  4662. gl.linkProgram(program);
  4663. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4664. if (!linked) {
  4665. var errorMsg = gl.getProgramInfoLog(program);
  4666. throw new Error('Error during program linking: ' + errorMsg);
  4667. }
  4668. return program;
  4669. }
  4670. function createTexture(gl, image, textureId) {
  4671. gl.activeTexture(textureId);
  4672. var texture = gl.createTexture();
  4673. gl.bindTexture(gl.TEXTURE_2D, texture);
  4674. // Set the parameters so we can render any size image.
  4675. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4679. // Upload the image into the texture.
  4680. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4681. return texture;
  4682. }
  4683. var currentGL, currentCanvas;
  4684. function generateGL() {
  4685. if (currentGL) {
  4686. return;
  4687. }
  4688. currentCanvas = document.createElement('canvas');
  4689. currentGL = currentCanvas.getContext('webgl',
  4690. { premultipliedalpha: false });
  4691. }
  4692. var smaskVertexShaderCode = '\
  4693. attribute vec2 a_position; \
  4694. attribute vec2 a_texCoord; \
  4695. \
  4696. uniform vec2 u_resolution; \
  4697. \
  4698. varying vec2 v_texCoord; \
  4699. \
  4700. void main() { \
  4701. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4702. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4703. \
  4704. v_texCoord = a_texCoord; \
  4705. } ';
  4706. var smaskFragmentShaderCode = '\
  4707. precision mediump float; \
  4708. \
  4709. uniform vec4 u_backdrop; \
  4710. uniform int u_subtype; \
  4711. uniform sampler2D u_image; \
  4712. uniform sampler2D u_mask; \
  4713. \
  4714. varying vec2 v_texCoord; \
  4715. \
  4716. void main() { \
  4717. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4718. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4719. if (u_backdrop.a > 0.0) { \
  4720. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4721. u_backdrop.rgb * (1.0 - maskColor.a); \
  4722. } \
  4723. float lum; \
  4724. if (u_subtype == 0) { \
  4725. lum = maskColor.a; \
  4726. } else { \
  4727. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4728. maskColor.b * 0.11; \
  4729. } \
  4730. imageColor.a *= lum; \
  4731. imageColor.rgb *= imageColor.a; \
  4732. gl_FragColor = imageColor; \
  4733. } ';
  4734. var smaskCache = null;
  4735. function initSmaskGL() {
  4736. var canvas, gl;
  4737. generateGL();
  4738. canvas = currentCanvas;
  4739. currentCanvas = null;
  4740. gl = currentGL;
  4741. currentGL = null;
  4742. // setup a GLSL program
  4743. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  4744. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  4745. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4746. gl.useProgram(program);
  4747. var cache = {};
  4748. cache.gl = gl;
  4749. cache.canvas = canvas;
  4750. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4751. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4752. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  4753. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  4754. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  4755. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  4756. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  4757. // provide texture coordinates for the rectangle.
  4758. var texCoordBuffer = gl.createBuffer();
  4759. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  4760. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4761. 0.0, 0.0,
  4762. 1.0, 0.0,
  4763. 0.0, 1.0,
  4764. 0.0, 1.0,
  4765. 1.0, 0.0,
  4766. 1.0, 1.0]), gl.STATIC_DRAW);
  4767. gl.enableVertexAttribArray(texCoordLocation);
  4768. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  4769. gl.uniform1i(texLayerLocation, 0);
  4770. gl.uniform1i(texMaskLocation, 1);
  4771. smaskCache = cache;
  4772. }
  4773. function composeSMask(layer, mask, properties) {
  4774. var width = layer.width, height = layer.height;
  4775. if (!smaskCache) {
  4776. initSmaskGL();
  4777. }
  4778. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  4779. canvas.width = width;
  4780. canvas.height = height;
  4781. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4782. gl.uniform2f(cache.resolutionLocation, width, height);
  4783. if (properties.backdrop) {
  4784. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  4785. properties.backdrop[1], properties.backdrop[2], 1);
  4786. } else {
  4787. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  4788. }
  4789. gl.uniform1i(cache.subtypeLocation,
  4790. properties.subtype === 'Luminosity' ? 1 : 0);
  4791. // Create a textures
  4792. var texture = createTexture(gl, layer, gl.TEXTURE0);
  4793. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  4794. // Create a buffer and put a single clipspace rectangle in
  4795. // it (2 triangles)
  4796. var buffer = gl.createBuffer();
  4797. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  4798. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4799. 0, 0,
  4800. width, 0,
  4801. 0, height,
  4802. 0, height,
  4803. width, 0,
  4804. width, height]), gl.STATIC_DRAW);
  4805. gl.enableVertexAttribArray(cache.positionLocation);
  4806. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4807. // draw
  4808. gl.clearColor(0, 0, 0, 0);
  4809. gl.enable(gl.BLEND);
  4810. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  4811. gl.clear(gl.COLOR_BUFFER_BIT);
  4812. gl.drawArrays(gl.TRIANGLES, 0, 6);
  4813. gl.flush();
  4814. gl.deleteTexture(texture);
  4815. gl.deleteTexture(maskTexture);
  4816. gl.deleteBuffer(buffer);
  4817. return canvas;
  4818. }
  4819. var figuresVertexShaderCode = '\
  4820. attribute vec2 a_position; \
  4821. attribute vec3 a_color; \
  4822. \
  4823. uniform vec2 u_resolution; \
  4824. uniform vec2 u_scale; \
  4825. uniform vec2 u_offset; \
  4826. \
  4827. varying vec4 v_color; \
  4828. \
  4829. void main() { \
  4830. vec2 position = (a_position + u_offset) * u_scale; \
  4831. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  4832. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4833. \
  4834. v_color = vec4(a_color / 255.0, 1.0); \
  4835. } ';
  4836. var figuresFragmentShaderCode = '\
  4837. precision mediump float; \
  4838. \
  4839. varying vec4 v_color; \
  4840. \
  4841. void main() { \
  4842. gl_FragColor = v_color; \
  4843. } ';
  4844. var figuresCache = null;
  4845. function initFiguresGL() {
  4846. var canvas, gl;
  4847. generateGL();
  4848. canvas = currentCanvas;
  4849. currentCanvas = null;
  4850. gl = currentGL;
  4851. currentGL = null;
  4852. // setup a GLSL program
  4853. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  4854. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  4855. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4856. gl.useProgram(program);
  4857. var cache = {};
  4858. cache.gl = gl;
  4859. cache.canvas = canvas;
  4860. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4861. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  4862. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  4863. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4864. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  4865. figuresCache = cache;
  4866. }
  4867. function drawFigures(width, height, backgroundColor, figures, context) {
  4868. if (!figuresCache) {
  4869. initFiguresGL();
  4870. }
  4871. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  4872. canvas.width = width;
  4873. canvas.height = height;
  4874. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  4875. gl.uniform2f(cache.resolutionLocation, width, height);
  4876. // count triangle points
  4877. var count = 0;
  4878. var i, ii, rows;
  4879. for (i = 0, ii = figures.length; i < ii; i++) {
  4880. switch (figures[i].type) {
  4881. case 'lattice':
  4882. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  4883. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  4884. break;
  4885. case 'triangles':
  4886. count += figures[i].coords.length;
  4887. break;
  4888. }
  4889. }
  4890. // transfer data
  4891. var coords = new Float32Array(count * 2);
  4892. var colors = new Uint8Array(count * 3);
  4893. var coordsMap = context.coords, colorsMap = context.colors;
  4894. var pIndex = 0, cIndex = 0;
  4895. for (i = 0, ii = figures.length; i < ii; i++) {
  4896. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  4897. switch (figure.type) {
  4898. case 'lattice':
  4899. var cols = figure.verticesPerRow;
  4900. rows = (ps.length / cols) | 0;
  4901. for (var row = 1; row < rows; row++) {
  4902. var offset = row * cols + 1;
  4903. for (var col = 1; col < cols; col++, offset++) {
  4904. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  4905. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  4906. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  4907. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  4908. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  4909. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  4910. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  4911. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  4912. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  4913. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  4914. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  4915. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  4916. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  4917. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  4918. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  4919. coords[pIndex + 6] = coords[pIndex + 2];
  4920. coords[pIndex + 7] = coords[pIndex + 3];
  4921. coords[pIndex + 8] = coords[pIndex + 4];
  4922. coords[pIndex + 9] = coords[pIndex + 5];
  4923. coords[pIndex + 10] = coordsMap[ps[offset]];
  4924. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  4925. colors[cIndex + 9] = colors[cIndex + 3];
  4926. colors[cIndex + 10] = colors[cIndex + 4];
  4927. colors[cIndex + 11] = colors[cIndex + 5];
  4928. colors[cIndex + 12] = colors[cIndex + 6];
  4929. colors[cIndex + 13] = colors[cIndex + 7];
  4930. colors[cIndex + 14] = colors[cIndex + 8];
  4931. colors[cIndex + 15] = colorsMap[cs[offset]];
  4932. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  4933. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  4934. pIndex += 12;
  4935. cIndex += 18;
  4936. }
  4937. }
  4938. break;
  4939. case 'triangles':
  4940. for (var j = 0, jj = ps.length; j < jj; j++) {
  4941. coords[pIndex] = coordsMap[ps[j]];
  4942. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  4943. colors[cIndex] = colorsMap[cs[i]];
  4944. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  4945. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  4946. pIndex += 2;
  4947. cIndex += 3;
  4948. }
  4949. break;
  4950. }
  4951. }
  4952. // draw
  4953. if (backgroundColor) {
  4954. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  4955. backgroundColor[2] / 255, 1.0);
  4956. } else {
  4957. gl.clearColor(0, 0, 0, 0);
  4958. }
  4959. gl.clear(gl.COLOR_BUFFER_BIT);
  4960. var coordsBuffer = gl.createBuffer();
  4961. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  4962. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  4963. gl.enableVertexAttribArray(cache.positionLocation);
  4964. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  4965. var colorsBuffer = gl.createBuffer();
  4966. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  4967. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  4968. gl.enableVertexAttribArray(cache.colorLocation);
  4969. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  4970. 0, 0);
  4971. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  4972. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  4973. gl.drawArrays(gl.TRIANGLES, 0, count);
  4974. gl.flush();
  4975. gl.deleteBuffer(coordsBuffer);
  4976. gl.deleteBuffer(colorsBuffer);
  4977. return canvas;
  4978. }
  4979. function cleanup() {
  4980. if (smaskCache && smaskCache.canvas) {
  4981. smaskCache.canvas.width = 0;
  4982. smaskCache.canvas.height = 0;
  4983. }
  4984. if (figuresCache && figuresCache.canvas) {
  4985. figuresCache.canvas.width = 0;
  4986. figuresCache.canvas.height = 0;
  4987. }
  4988. smaskCache = null;
  4989. figuresCache = null;
  4990. }
  4991. return {
  4992. get isEnabled() {
  4993. if (PDFJS.disableWebGL) {
  4994. return false;
  4995. }
  4996. var enabled = false;
  4997. try {
  4998. generateGL();
  4999. enabled = !!currentGL;
  5000. } catch (e) { }
  5001. return shadow(this, 'isEnabled', enabled);
  5002. },
  5003. composeSMask: composeSMask,
  5004. drawFigures: drawFigures,
  5005. clear: cleanup
  5006. };
  5007. })();
  5008. var ShadingIRs = {};
  5009. ShadingIRs.RadialAxial = {
  5010. fromIR: function RadialAxial_fromIR(raw) {
  5011. var type = raw[1];
  5012. var colorStops = raw[2];
  5013. var p0 = raw[3];
  5014. var p1 = raw[4];
  5015. var r0 = raw[5];
  5016. var r1 = raw[6];
  5017. return {
  5018. type: 'Pattern',
  5019. getPattern: function RadialAxial_getPattern(ctx) {
  5020. var grad;
  5021. if (type === 'axial') {
  5022. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5023. } else if (type === 'radial') {
  5024. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5025. }
  5026. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5027. var c = colorStops[i];
  5028. grad.addColorStop(c[0], c[1]);
  5029. }
  5030. return grad;
  5031. }
  5032. };
  5033. }
  5034. };
  5035. var createMeshCanvas = (function createMeshCanvasClosure() {
  5036. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5037. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5038. var coords = context.coords, colors = context.colors;
  5039. var bytes = data.data, rowSize = data.width * 4;
  5040. var tmp;
  5041. if (coords[p1 + 1] > coords[p2 + 1]) {
  5042. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5043. }
  5044. if (coords[p2 + 1] > coords[p3 + 1]) {
  5045. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5046. }
  5047. if (coords[p1 + 1] > coords[p2 + 1]) {
  5048. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5049. }
  5050. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5051. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5052. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5053. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5054. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5055. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5056. if (y1 >= y3) {
  5057. return;
  5058. }
  5059. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5060. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5061. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5062. var minY = Math.round(y1), maxY = Math.round(y3);
  5063. var xa, car, cag, cab;
  5064. var xb, cbr, cbg, cbb;
  5065. var k;
  5066. for (var y = minY; y <= maxY; y++) {
  5067. if (y < y2) {
  5068. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5069. xa = x1 - (x1 - x2) * k;
  5070. car = c1r - (c1r - c2r) * k;
  5071. cag = c1g - (c1g - c2g) * k;
  5072. cab = c1b - (c1b - c2b) * k;
  5073. } else {
  5074. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5075. xa = x2 - (x2 - x3) * k;
  5076. car = c2r - (c2r - c3r) * k;
  5077. cag = c2g - (c2g - c3g) * k;
  5078. cab = c2b - (c2b - c3b) * k;
  5079. }
  5080. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5081. xb = x1 - (x1 - x3) * k;
  5082. cbr = c1r - (c1r - c3r) * k;
  5083. cbg = c1g - (c1g - c3g) * k;
  5084. cbb = c1b - (c1b - c3b) * k;
  5085. var x1_ = Math.round(Math.min(xa, xb));
  5086. var x2_ = Math.round(Math.max(xa, xb));
  5087. var j = rowSize * y + x1_ * 4;
  5088. for (var x = x1_; x <= x2_; x++) {
  5089. k = (xa - x) / (xa - xb);
  5090. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5091. bytes[j++] = (car - (car - cbr) * k) | 0;
  5092. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5093. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5094. bytes[j++] = 255;
  5095. }
  5096. }
  5097. }
  5098. function drawFigure(data, figure, context) {
  5099. var ps = figure.coords;
  5100. var cs = figure.colors;
  5101. var i, ii;
  5102. switch (figure.type) {
  5103. case 'lattice':
  5104. var verticesPerRow = figure.verticesPerRow;
  5105. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5106. var cols = verticesPerRow - 1;
  5107. for (i = 0; i < rows; i++) {
  5108. var q = i * verticesPerRow;
  5109. for (var j = 0; j < cols; j++, q++) {
  5110. drawTriangle(data, context,
  5111. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5112. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5113. drawTriangle(data, context,
  5114. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5115. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5116. }
  5117. }
  5118. break;
  5119. case 'triangles':
  5120. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5121. drawTriangle(data, context,
  5122. ps[i], ps[i + 1], ps[i + 2],
  5123. cs[i], cs[i + 1], cs[i + 2]);
  5124. }
  5125. break;
  5126. default:
  5127. error('illigal figure');
  5128. break;
  5129. }
  5130. }
  5131. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5132. backgroundColor) {
  5133. // we will increase scale on some weird factor to let antialiasing take
  5134. // care of "rough" edges
  5135. var EXPECTED_SCALE = 1.1;
  5136. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5137. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5138. var offsetX = Math.floor(bounds[0]);
  5139. var offsetY = Math.floor(bounds[1]);
  5140. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5141. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5142. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5143. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5144. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5145. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5146. var scaleX = boundsWidth / width;
  5147. var scaleY = boundsHeight / height;
  5148. var context = {
  5149. coords: coords,
  5150. colors: colors,
  5151. offsetX: -offsetX,
  5152. offsetY: -offsetY,
  5153. scaleX: 1 / scaleX,
  5154. scaleY: 1 / scaleY
  5155. };
  5156. var canvas, tmpCanvas, i, ii;
  5157. if (WebGLUtils.isEnabled) {
  5158. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5159. figures, context);
  5160. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5161. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5162. tmpCanvas.context.drawImage(canvas, 0, 0);
  5163. canvas = tmpCanvas.canvas;
  5164. } else {
  5165. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5166. var tmpCtx = tmpCanvas.context;
  5167. var data = tmpCtx.createImageData(width, height);
  5168. if (backgroundColor) {
  5169. var bytes = data.data;
  5170. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5171. bytes[i] = backgroundColor[0];
  5172. bytes[i + 1] = backgroundColor[1];
  5173. bytes[i + 2] = backgroundColor[2];
  5174. bytes[i + 3] = 255;
  5175. }
  5176. }
  5177. for (i = 0; i < figures.length; i++) {
  5178. drawFigure(data, figures[i], context);
  5179. }
  5180. tmpCtx.putImageData(data, 0, 0);
  5181. canvas = tmpCanvas.canvas;
  5182. }
  5183. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5184. scaleX: scaleX, scaleY: scaleY};
  5185. }
  5186. return createMeshCanvas;
  5187. })();
  5188. ShadingIRs.Mesh = {
  5189. fromIR: function Mesh_fromIR(raw) {
  5190. //var type = raw[1];
  5191. var coords = raw[2];
  5192. var colors = raw[3];
  5193. var figures = raw[4];
  5194. var bounds = raw[5];
  5195. var matrix = raw[6];
  5196. //var bbox = raw[7];
  5197. var background = raw[8];
  5198. return {
  5199. type: 'Pattern',
  5200. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5201. var scale;
  5202. if (shadingFill) {
  5203. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5204. } else {
  5205. // Obtain scale from matrix and current transformation matrix.
  5206. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5207. if (matrix) {
  5208. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5209. scale = [scale[0] * matrixScale[0],
  5210. scale[1] * matrixScale[1]];
  5211. }
  5212. }
  5213. // Rasterizing on the main thread since sending/queue large canvases
  5214. // might cause OOM.
  5215. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5216. colors, figures, shadingFill ? null : background);
  5217. if (!shadingFill) {
  5218. ctx.setTransform.apply(ctx, owner.baseTransform);
  5219. if (matrix) {
  5220. ctx.transform.apply(ctx, matrix);
  5221. }
  5222. }
  5223. ctx.translate(temporaryPatternCanvas.offsetX,
  5224. temporaryPatternCanvas.offsetY);
  5225. ctx.scale(temporaryPatternCanvas.scaleX,
  5226. temporaryPatternCanvas.scaleY);
  5227. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5228. }
  5229. };
  5230. }
  5231. };
  5232. ShadingIRs.Dummy = {
  5233. fromIR: function Dummy_fromIR() {
  5234. return {
  5235. type: 'Pattern',
  5236. getPattern: function Dummy_fromIR_getPattern() {
  5237. return 'hotpink';
  5238. }
  5239. };
  5240. }
  5241. };
  5242. function getShadingPatternFromIR(raw) {
  5243. var shadingIR = ShadingIRs[raw[0]];
  5244. if (!shadingIR) {
  5245. error('Unknown IR type: ' + raw[0]);
  5246. }
  5247. return shadingIR.fromIR(raw);
  5248. }
  5249. var TilingPattern = (function TilingPatternClosure() {
  5250. var PaintType = {
  5251. COLORED: 1,
  5252. UNCOLORED: 2
  5253. };
  5254. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5255. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5256. this.operatorList = IR[2];
  5257. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5258. this.bbox = IR[4];
  5259. this.xstep = IR[5];
  5260. this.ystep = IR[6];
  5261. this.paintType = IR[7];
  5262. this.tilingType = IR[8];
  5263. this.color = color;
  5264. this.objs = objs;
  5265. this.commonObjs = commonObjs;
  5266. this.baseTransform = baseTransform;
  5267. this.type = 'Pattern';
  5268. this.ctx = ctx;
  5269. }
  5270. TilingPattern.prototype = {
  5271. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5272. var operatorList = this.operatorList;
  5273. var bbox = this.bbox;
  5274. var xstep = this.xstep;
  5275. var ystep = this.ystep;
  5276. var paintType = this.paintType;
  5277. var tilingType = this.tilingType;
  5278. var color = this.color;
  5279. var objs = this.objs;
  5280. var commonObjs = this.commonObjs;
  5281. info('TilingType: ' + tilingType);
  5282. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5283. var topLeft = [x0, y0];
  5284. // we want the canvas to be as large as the step size
  5285. var botRight = [x0 + xstep, y0 + ystep];
  5286. var width = botRight[0] - topLeft[0];
  5287. var height = botRight[1] - topLeft[1];
  5288. // Obtain scale from matrix and current transformation matrix.
  5289. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5290. var curMatrixScale = Util.singularValueDecompose2dScale(
  5291. this.baseTransform);
  5292. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5293. matrixScale[1] * curMatrixScale[1]];
  5294. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5295. // Use width and height values that are as close as possible to the end
  5296. // result when the pattern is used. Too low value makes the pattern look
  5297. // blurry. Too large value makes it look too crispy.
  5298. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5299. MAX_PATTERN_SIZE);
  5300. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5301. MAX_PATTERN_SIZE);
  5302. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  5303. var tmpCtx = tmpCanvas.context;
  5304. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5305. graphics.groupLevel = owner.groupLevel;
  5306. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5307. this.setScale(width, height, xstep, ystep);
  5308. this.transformToScale(graphics);
  5309. // transform coordinates to pattern space
  5310. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5311. graphics.transform.apply(graphics, tmpTranslate);
  5312. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5313. graphics.executeOperatorList(operatorList);
  5314. return tmpCanvas.canvas;
  5315. },
  5316. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5317. this.scale = [width / xstep, height / ystep];
  5318. },
  5319. transformToScale: function TilingPattern_transformToScale(graphics) {
  5320. var scale = this.scale;
  5321. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5322. graphics.transform.apply(graphics, tmpScale);
  5323. },
  5324. scaleToContext: function TilingPattern_scaleToContext() {
  5325. var scale = this.scale;
  5326. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5327. },
  5328. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5329. if (bbox && isArray(bbox) && bbox.length === 4) {
  5330. var bboxWidth = x1 - x0;
  5331. var bboxHeight = y1 - y0;
  5332. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5333. graphics.clip();
  5334. graphics.endPath();
  5335. }
  5336. },
  5337. setFillAndStrokeStyleToContext:
  5338. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5339. switch (paintType) {
  5340. case PaintType.COLORED:
  5341. var ctx = this.ctx;
  5342. context.fillStyle = ctx.fillStyle;
  5343. context.strokeStyle = ctx.strokeStyle;
  5344. break;
  5345. case PaintType.UNCOLORED:
  5346. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5347. context.fillStyle = cssColor;
  5348. context.strokeStyle = cssColor;
  5349. break;
  5350. default:
  5351. error('Unsupported paint type: ' + paintType);
  5352. }
  5353. },
  5354. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5355. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5356. ctx = this.ctx;
  5357. ctx.setTransform.apply(ctx, this.baseTransform);
  5358. ctx.transform.apply(ctx, this.matrix);
  5359. this.scaleToContext();
  5360. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5361. }
  5362. };
  5363. return TilingPattern;
  5364. })();
  5365. PDFJS.disableFontFace = false;
  5366. var FontLoader = {
  5367. insertRule: function fontLoaderInsertRule(rule) {
  5368. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5369. if (!styleElement) {
  5370. styleElement = document.createElement('style');
  5371. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  5372. document.documentElement.getElementsByTagName('head')[0].appendChild(
  5373. styleElement);
  5374. }
  5375. var styleSheet = styleElement.sheet;
  5376. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5377. },
  5378. clear: function fontLoaderClear() {
  5379. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5380. if (styleElement) {
  5381. styleElement.parentNode.removeChild(styleElement);
  5382. }
  5383. this.nativeFontFaces.forEach(function(nativeFontFace) {
  5384. document.fonts.delete(nativeFontFace);
  5385. });
  5386. this.nativeFontFaces.length = 0;
  5387. },
  5388. get loadTestFont() {
  5389. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  5390. // height.
  5391. return shadow(this, 'loadTestFont', atob(
  5392. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  5393. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  5394. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  5395. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  5396. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  5397. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  5398. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  5399. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  5400. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  5401. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  5402. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  5403. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  5404. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  5405. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5406. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5407. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5408. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  5409. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  5410. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  5411. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  5412. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  5413. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  5414. ));
  5415. },
  5416. loadTestFontId: 0,
  5417. loadingContext: {
  5418. requests: [],
  5419. nextRequestId: 0
  5420. },
  5421. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  5422. if (isWorker) {
  5423. return false;
  5424. }
  5425. // User agent string sniffing is bad, but there is no reliable way to tell
  5426. // if font is fully loaded and ready to be used with canvas.
  5427. var userAgent = window.navigator.userAgent;
  5428. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  5429. if (m && m[1] >= 14) {
  5430. return true;
  5431. }
  5432. // TODO other browsers
  5433. if (userAgent === 'node') {
  5434. return true;
  5435. }
  5436. return false;
  5437. })(),
  5438. nativeFontFaces: [],
  5439. isFontLoadingAPISupported: !isWorker && !!document.fonts,
  5440. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  5441. this.nativeFontFaces.push(nativeFontFace);
  5442. document.fonts.add(nativeFontFace);
  5443. },
  5444. bind: function fontLoaderBind(fonts, callback) {
  5445. assert(!isWorker, 'bind() shall be called from main thread');
  5446. var rules = [];
  5447. var fontsToLoad = [];
  5448. var fontLoadPromises = [];
  5449. for (var i = 0, ii = fonts.length; i < ii; i++) {
  5450. var font = fonts[i];
  5451. // Add the font to the DOM only once or skip if the font
  5452. // is already loaded.
  5453. if (font.attached || font.loading === false) {
  5454. continue;
  5455. }
  5456. font.attached = true;
  5457. if (this.isFontLoadingAPISupported) {
  5458. var nativeFontFace = font.createNativeFontFace();
  5459. if (nativeFontFace) {
  5460. fontLoadPromises.push(nativeFontFace.loaded);
  5461. }
  5462. } else {
  5463. var rule = font.bindDOM();
  5464. if (rule) {
  5465. rules.push(rule);
  5466. fontsToLoad.push(font);
  5467. }
  5468. }
  5469. }
  5470. var request = FontLoader.queueLoadingCallback(callback);
  5471. if (this.isFontLoadingAPISupported) {
  5472. Promise.all(fontsToLoad).then(function() {
  5473. request.complete();
  5474. });
  5475. } else if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  5476. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  5477. } else {
  5478. request.complete();
  5479. }
  5480. },
  5481. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  5482. function LoadLoader_completeRequest() {
  5483. assert(!request.end, 'completeRequest() cannot be called twice');
  5484. request.end = Date.now();
  5485. // sending all completed requests in order how they were queued
  5486. while (context.requests.length > 0 && context.requests[0].end) {
  5487. var otherRequest = context.requests.shift();
  5488. setTimeout(otherRequest.callback, 0);
  5489. }
  5490. }
  5491. var context = FontLoader.loadingContext;
  5492. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  5493. var request = {
  5494. id: requestId,
  5495. complete: LoadLoader_completeRequest,
  5496. callback: callback,
  5497. started: Date.now()
  5498. };
  5499. context.requests.push(request);
  5500. return request;
  5501. },
  5502. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  5503. fonts,
  5504. request) {
  5505. /** Hack begin */
  5506. // There's currently no event when a font has finished downloading so the
  5507. // following code is a dirty hack to 'guess' when a font is
  5508. // ready. It's assumed fonts are loaded in order, so add a known test
  5509. // font after the desired fonts and then test for the loading of that
  5510. // test font.
  5511. function int32(data, offset) {
  5512. return (data.charCodeAt(offset) << 24) |
  5513. (data.charCodeAt(offset + 1) << 16) |
  5514. (data.charCodeAt(offset + 2) << 8) |
  5515. (data.charCodeAt(offset + 3) & 0xff);
  5516. }
  5517. function spliceString(s, offset, remove, insert) {
  5518. var chunk1 = s.substr(0, offset);
  5519. var chunk2 = s.substr(offset + remove);
  5520. return chunk1 + insert + chunk2;
  5521. }
  5522. var i, ii;
  5523. var canvas = document.createElement('canvas');
  5524. canvas.width = 1;
  5525. canvas.height = 1;
  5526. var ctx = canvas.getContext('2d');
  5527. var called = 0;
  5528. function isFontReady(name, callback) {
  5529. called++;
  5530. // With setTimeout clamping this gives the font ~100ms to load.
  5531. if(called > 30) {
  5532. warn('Load test font never loaded.');
  5533. callback();
  5534. return;
  5535. }
  5536. ctx.font = '30px ' + name;
  5537. ctx.fillText('.', 0, 20);
  5538. var imageData = ctx.getImageData(0, 0, 1, 1);
  5539. if (imageData.data[3] > 0) {
  5540. callback();
  5541. return;
  5542. }
  5543. setTimeout(isFontReady.bind(null, name, callback));
  5544. }
  5545. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  5546. // Chromium seems to cache fonts based on a hash of the actual font data,
  5547. // so the font must be modified for each load test else it will appear to
  5548. // be loaded already.
  5549. // TODO: This could maybe be made faster by avoiding the btoa of the full
  5550. // font by splitting it in chunks before hand and padding the font id.
  5551. var data = this.loadTestFont;
  5552. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  5553. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  5554. loadTestFontId);
  5555. // CFF checksum is important for IE, adjusting it
  5556. var CFF_CHECKSUM_OFFSET = 16;
  5557. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  5558. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5559. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5560. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  5561. }
  5562. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  5563. checksum = (checksum - XXXX_VALUE +
  5564. int32(loadTestFontId + 'XXX', i)) | 0;
  5565. }
  5566. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  5567. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  5568. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  5569. url + '}';
  5570. FontLoader.insertRule(rule);
  5571. var names = [];
  5572. for (i = 0, ii = fonts.length; i < ii; i++) {
  5573. names.push(fonts[i].loadedName);
  5574. }
  5575. names.push(loadTestFontId);
  5576. var div = document.createElement('div');
  5577. div.setAttribute('style',
  5578. 'visibility: hidden;' +
  5579. 'width: 10px; height: 10px;' +
  5580. 'position: absolute; top: 0px; left: 0px;');
  5581. for (i = 0, ii = names.length; i < ii; ++i) {
  5582. var span = document.createElement('span');
  5583. span.textContent = 'Hi';
  5584. span.style.fontFamily = names[i];
  5585. div.appendChild(span);
  5586. }
  5587. document.body.appendChild(div);
  5588. isFontReady(loadTestFontId, function() {
  5589. document.body.removeChild(div);
  5590. request.complete();
  5591. });
  5592. /** Hack end */
  5593. }
  5594. };
  5595. var FontFaceObject = (function FontFaceObjectClosure() {
  5596. function FontFaceObject(name, file, properties) {
  5597. this.compiledGlyphs = {};
  5598. if (arguments.length === 1) {
  5599. // importing translated data
  5600. var data = arguments[0];
  5601. for (var i in data) {
  5602. this[i] = data[i];
  5603. }
  5604. return;
  5605. }
  5606. }
  5607. FontFaceObject.prototype = {
  5608. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  5609. if (!this.data) {
  5610. return null;
  5611. }
  5612. if (PDFJS.disableFontFace) {
  5613. this.disableFontFace = true;
  5614. return null;
  5615. }
  5616. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  5617. FontLoader.addNativeFontFace(nativeFontFace);
  5618. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5619. globalScope['FontInspector'].enabled) {
  5620. globalScope['FontInspector'].fontAdded(this);
  5621. }
  5622. return nativeFontFace;
  5623. },
  5624. bindDOM: function FontFaceObject_bindDOM() {
  5625. if (!this.data) {
  5626. return null;
  5627. }
  5628. if (PDFJS.disableFontFace) {
  5629. this.disableFontFace = true;
  5630. return null;
  5631. }
  5632. var data = bytesToString(new Uint8Array(this.data));
  5633. var fontName = this.loadedName;
  5634. // Add the font-face rule to the document
  5635. var url = ('url(data:' + this.mimetype + ';base64,' +
  5636. window.btoa(data) + ');');
  5637. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  5638. FontLoader.insertRule(rule);
  5639. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5640. globalScope['FontInspector'].enabled) {
  5641. globalScope['FontInspector'].fontAdded(this, url);
  5642. }
  5643. return rule;
  5644. },
  5645. getPathGenerator: function FontLoader_getPathGenerator(objs, character) {
  5646. if (!(character in this.compiledGlyphs)) {
  5647. var js = objs.get(this.loadedName + '_path_' + character);
  5648. /*jshint -W054 */
  5649. this.compiledGlyphs[character] = new Function('c', 'size', js);
  5650. }
  5651. return this.compiledGlyphs[character];
  5652. }
  5653. };
  5654. return FontFaceObject;
  5655. })();
  5656. var ANNOT_MIN_SIZE = 10; // px
  5657. var AnnotationUtils = (function AnnotationUtilsClosure() {
  5658. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  5659. function setTextStyles(element, item, fontObj) {
  5660. var style = element.style;
  5661. style.fontSize = item.fontSize + 'px';
  5662. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  5663. if (!fontObj) {
  5664. return;
  5665. }
  5666. style.fontWeight = fontObj.black ?
  5667. (fontObj.bold ? 'bolder' : 'bold') :
  5668. (fontObj.bold ? 'bold' : 'normal');
  5669. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  5670. var fontName = fontObj.loadedName;
  5671. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  5672. // Use a reasonable default font if the font doesn't specify a fallback
  5673. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  5674. style.fontFamily = fontFamily + fallbackName;
  5675. }
  5676. function initContainer(item, drawBorder) {
  5677. var container = document.createElement('section');
  5678. var cstyle = container.style;
  5679. var width = item.rect[2] - item.rect[0];
  5680. var height = item.rect[3] - item.rect[1];
  5681. var bWidth = item.borderWidth || 0;
  5682. if (bWidth) {
  5683. width = width - 2 * bWidth;
  5684. height = height - 2 * bWidth;
  5685. cstyle.borderWidth = bWidth + 'px';
  5686. var color = item.color;
  5687. if (drawBorder && color) {
  5688. cstyle.borderStyle = 'solid';
  5689. cstyle.borderColor = Util.makeCssRgb(Math.round(color[0] * 255),
  5690. Math.round(color[1] * 255),
  5691. Math.round(color[2] * 255));
  5692. }
  5693. }
  5694. cstyle.width = width + 'px';
  5695. cstyle.height = height + 'px';
  5696. return container;
  5697. }
  5698. function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
  5699. var element = document.createElement('div');
  5700. var width = item.rect[2] - item.rect[0];
  5701. var height = item.rect[3] - item.rect[1];
  5702. element.style.width = width + 'px';
  5703. element.style.height = height + 'px';
  5704. element.style.display = 'table';
  5705. var content = document.createElement('div');
  5706. content.textContent = item.fieldValue;
  5707. var textAlignment = item.textAlignment;
  5708. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  5709. content.style.verticalAlign = 'middle';
  5710. content.style.display = 'table-cell';
  5711. var fontObj = item.fontRefName ?
  5712. commonObjs.getData(item.fontRefName) : null;
  5713. setTextStyles(content, item, fontObj);
  5714. element.appendChild(content);
  5715. return element;
  5716. }
  5717. function getHtmlElementForTextAnnotation(item) {
  5718. var rect = item.rect;
  5719. // sanity check because of OOo-generated PDFs
  5720. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  5721. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  5722. }
  5723. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  5724. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  5725. }
  5726. var container = initContainer(item, false);
  5727. container.className = 'annotText';
  5728. var image = document.createElement('img');
  5729. image.style.height = container.style.height;
  5730. image.style.width = container.style.width;
  5731. var iconName = item.name;
  5732. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  5733. iconName.toLowerCase() + '.svg';
  5734. image.alt = '[{{type}} Annotation]';
  5735. image.dataset.l10nId = 'text_annotation_type';
  5736. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  5737. var contentWrapper = document.createElement('div');
  5738. contentWrapper.className = 'annotTextContentWrapper';
  5739. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  5740. contentWrapper.style.top = '-10px';
  5741. var content = document.createElement('div');
  5742. content.className = 'annotTextContent';
  5743. content.setAttribute('hidden', true);
  5744. var i, ii;
  5745. if (item.hasBgColor) {
  5746. var color = item.color;
  5747. // Enlighten the color (70%)
  5748. var BACKGROUND_ENLIGHT = 0.7;
  5749. var r = BACKGROUND_ENLIGHT * (1.0 - color[0]) + color[0];
  5750. var g = BACKGROUND_ENLIGHT * (1.0 - color[1]) + color[1];
  5751. var b = BACKGROUND_ENLIGHT * (1.0 - color[2]) + color[2];
  5752. content.style.backgroundColor = Util.makeCssRgb((r * 255) | 0,
  5753. (g * 255) | 0,
  5754. (b * 255) | 0);
  5755. }
  5756. var title = document.createElement('h1');
  5757. var text = document.createElement('p');
  5758. title.textContent = item.title;
  5759. if (!item.content && !item.title) {
  5760. content.setAttribute('hidden', true);
  5761. } else {
  5762. var e = document.createElement('span');
  5763. var lines = item.content.split(/(?:\r\n?|\n)/);
  5764. for (i = 0, ii = lines.length; i < ii; ++i) {
  5765. var line = lines[i];
  5766. e.appendChild(document.createTextNode(line));
  5767. if (i < (ii - 1)) {
  5768. e.appendChild(document.createElement('br'));
  5769. }
  5770. }
  5771. text.appendChild(e);
  5772. var pinned = false;
  5773. var showAnnotation = function showAnnotation(pin) {
  5774. if (pin) {
  5775. pinned = true;
  5776. }
  5777. if (content.hasAttribute('hidden')) {
  5778. container.style.zIndex += 1;
  5779. content.removeAttribute('hidden');
  5780. }
  5781. };
  5782. var hideAnnotation = function hideAnnotation(unpin) {
  5783. if (unpin) {
  5784. pinned = false;
  5785. }
  5786. if (!content.hasAttribute('hidden') && !pinned) {
  5787. container.style.zIndex -= 1;
  5788. content.setAttribute('hidden', true);
  5789. }
  5790. };
  5791. var toggleAnnotation = function toggleAnnotation() {
  5792. if (pinned) {
  5793. hideAnnotation(true);
  5794. } else {
  5795. showAnnotation(true);
  5796. }
  5797. };
  5798. image.addEventListener('click', function image_clickHandler() {
  5799. toggleAnnotation();
  5800. }, false);
  5801. image.addEventListener('mouseover', function image_mouseOverHandler() {
  5802. showAnnotation();
  5803. }, false);
  5804. image.addEventListener('mouseout', function image_mouseOutHandler() {
  5805. hideAnnotation();
  5806. }, false);
  5807. content.addEventListener('click', function content_clickHandler() {
  5808. hideAnnotation(true);
  5809. }, false);
  5810. }
  5811. content.appendChild(title);
  5812. content.appendChild(text);
  5813. contentWrapper.appendChild(content);
  5814. container.appendChild(image);
  5815. container.appendChild(contentWrapper);
  5816. return container;
  5817. }
  5818. function getHtmlElementForLinkAnnotation(item) {
  5819. var container = initContainer(item, true);
  5820. container.className = 'annotLink';
  5821. var link = document.createElement('a');
  5822. link.href = link.title = item.url || '';
  5823. container.appendChild(link);
  5824. return container;
  5825. }
  5826. function getHtmlElement(data, objs) {
  5827. switch (data.annotationType) {
  5828. case AnnotationType.WIDGET:
  5829. return getHtmlElementForTextWidgetAnnotation(data, objs);
  5830. case AnnotationType.TEXT:
  5831. return getHtmlElementForTextAnnotation(data);
  5832. case AnnotationType.LINK:
  5833. return getHtmlElementForLinkAnnotation(data);
  5834. default:
  5835. throw new Error('Unsupported annotationType: ' + data.annotationType);
  5836. }
  5837. }
  5838. return {
  5839. getHtmlElement: getHtmlElement
  5840. };
  5841. })();
  5842. PDFJS.AnnotationUtils = AnnotationUtils;
  5843. var SVG_DEFAULTS = {
  5844. fontStyle: 'normal',
  5845. fontWeight: 'normal',
  5846. fillColor: '#000000'
  5847. };
  5848. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  5849. var PNG_HEADER =
  5850. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  5851. var CHUNK_WRAPPER_SIZE = 12;
  5852. var crcTable = new Int32Array(256);
  5853. for (var i = 0; i < 256; i++) {
  5854. var c = i;
  5855. for (var h = 0; h < 8; h++) {
  5856. if (c & 1) {
  5857. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  5858. } else {
  5859. c = (c >> 1) & 0x7fffffff;
  5860. }
  5861. }
  5862. crcTable[i] = c;
  5863. }
  5864. function crc32(data, start, end) {
  5865. var crc = -1;
  5866. for (var i = start; i < end; i++) {
  5867. var a = (crc ^ data[i]) & 0xff;
  5868. var b = crcTable[a];
  5869. crc = (crc >>> 8) ^ b;
  5870. }
  5871. return crc ^ -1;
  5872. }
  5873. function writePngChunk(type, body, data, offset) {
  5874. var p = offset;
  5875. var len = body.length;
  5876. data[p] = len >> 24 & 0xff;
  5877. data[p + 1] = len >> 16 & 0xff;
  5878. data[p + 2] = len >> 8 & 0xff;
  5879. data[p + 3] = len & 0xff;
  5880. p += 4;
  5881. data[p] = type.charCodeAt(0) & 0xff;
  5882. data[p + 1] = type.charCodeAt(1) & 0xff;
  5883. data[p + 2] = type.charCodeAt(2) & 0xff;
  5884. data[p + 3] = type.charCodeAt(3) & 0xff;
  5885. p += 4;
  5886. data.set(body, p);
  5887. p += body.length;
  5888. var crc = crc32(data, offset + 4, p);
  5889. data[p] = crc >> 24 & 0xff;
  5890. data[p + 1] = crc >> 16 & 0xff;
  5891. data[p + 2] = crc >> 8 & 0xff;
  5892. data[p + 3] = crc & 0xff;
  5893. }
  5894. function adler32(data, start, end) {
  5895. var a = 1;
  5896. var b = 0;
  5897. for (var i = start; i < end; ++i) {
  5898. a = (a + (data[i] & 0xff)) % 65521;
  5899. b = (b + a) % 65521;
  5900. }
  5901. return (b << 16) | a;
  5902. }
  5903. function encode(imgData, kind) {
  5904. var width = imgData.width;
  5905. var height = imgData.height;
  5906. var bitDepth, colorType, lineSize;
  5907. var bytes = imgData.data;
  5908. switch (kind) {
  5909. case ImageKind.GRAYSCALE_1BPP:
  5910. colorType = 0;
  5911. bitDepth = 1;
  5912. lineSize = (width + 7) >> 3;
  5913. break;
  5914. case ImageKind.RGB_24BPP:
  5915. colorType = 2;
  5916. bitDepth = 8;
  5917. lineSize = width * 3;
  5918. break;
  5919. case ImageKind.RGBA_32BPP:
  5920. colorType = 6;
  5921. bitDepth = 8;
  5922. lineSize = width * 4;
  5923. break;
  5924. default:
  5925. throw new Error('invalid format');
  5926. }
  5927. // prefix every row with predictor 0
  5928. var literals = new Uint8Array((1 + lineSize) * height);
  5929. var offsetLiterals = 0, offsetBytes = 0;
  5930. var y, i;
  5931. for (y = 0; y < height; ++y) {
  5932. literals[offsetLiterals++] = 0; // no prediction
  5933. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  5934. offsetLiterals);
  5935. offsetBytes += lineSize;
  5936. offsetLiterals += lineSize;
  5937. }
  5938. if (kind === ImageKind.GRAYSCALE_1BPP) {
  5939. // inverting for B/W
  5940. offsetLiterals = 0;
  5941. for (y = 0; y < height; y++) {
  5942. offsetLiterals++; // skipping predictor
  5943. for (i = 0; i < lineSize; i++) {
  5944. literals[offsetLiterals++] ^= 0xFF;
  5945. }
  5946. }
  5947. }
  5948. var ihdr = new Uint8Array([
  5949. width >> 24 & 0xff,
  5950. width >> 16 & 0xff,
  5951. width >> 8 & 0xff,
  5952. width & 0xff,
  5953. height >> 24 & 0xff,
  5954. height >> 16 & 0xff,
  5955. height >> 8 & 0xff,
  5956. height & 0xff,
  5957. bitDepth, // bit depth
  5958. colorType, // color type
  5959. 0x00, // compression method
  5960. 0x00, // filter method
  5961. 0x00 // interlace method
  5962. ]);
  5963. var len = literals.length;
  5964. var maxBlockLength = 0xFFFF;
  5965. var deflateBlocks = Math.ceil(len / maxBlockLength);
  5966. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  5967. var pi = 0;
  5968. idat[pi++] = 0x78; // compression method and flags
  5969. idat[pi++] = 0x9c; // flags
  5970. var pos = 0;
  5971. while (len > maxBlockLength) {
  5972. // writing non-final DEFLATE blocks type 0 and length of 65535
  5973. idat[pi++] = 0x00;
  5974. idat[pi++] = 0xff;
  5975. idat[pi++] = 0xff;
  5976. idat[pi++] = 0x00;
  5977. idat[pi++] = 0x00;
  5978. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  5979. pi += maxBlockLength;
  5980. pos += maxBlockLength;
  5981. len -= maxBlockLength;
  5982. }
  5983. // writing non-final DEFLATE blocks type 0
  5984. idat[pi++] = 0x01;
  5985. idat[pi++] = len & 0xff;
  5986. idat[pi++] = len >> 8 & 0xff;
  5987. idat[pi++] = (~len & 0xffff) & 0xff;
  5988. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  5989. idat.set(literals.subarray(pos), pi);
  5990. pi += literals.length - pos;
  5991. var adler = adler32(literals, 0, literals.length); // checksum
  5992. idat[pi++] = adler >> 24 & 0xff;
  5993. idat[pi++] = adler >> 16 & 0xff;
  5994. idat[pi++] = adler >> 8 & 0xff;
  5995. idat[pi++] = adler & 0xff;
  5996. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  5997. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  5998. ihdr.length + idat.length;
  5999. var data = new Uint8Array(pngLength);
  6000. var offset = 0;
  6001. data.set(PNG_HEADER, offset);
  6002. offset += PNG_HEADER.length;
  6003. writePngChunk('IHDR', ihdr, data, offset);
  6004. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  6005. writePngChunk('IDATA', idat, data, offset);
  6006. offset += CHUNK_WRAPPER_SIZE + idat.length;
  6007. writePngChunk('IEND', new Uint8Array(0), data, offset);
  6008. return PDFJS.createObjectURL(data, 'image/png');
  6009. }
  6010. return function convertImgDataToPng(imgData) {
  6011. var kind = (imgData.kind === undefined ?
  6012. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  6013. return encode(imgData, kind);
  6014. };
  6015. })();
  6016. var SVGExtraState = (function SVGExtraStateClosure() {
  6017. function SVGExtraState() {
  6018. this.fontSizeScale = 1;
  6019. this.fontWeight = SVG_DEFAULTS.fontWeight;
  6020. this.fontSize = 0;
  6021. this.textMatrix = IDENTITY_MATRIX;
  6022. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6023. this.leading = 0;
  6024. // Current point (in user coordinates)
  6025. this.x = 0;
  6026. this.y = 0;
  6027. // Start of text line (in text coordinates)
  6028. this.lineX = 0;
  6029. this.lineY = 0;
  6030. // Character and word spacing
  6031. this.charSpacing = 0;
  6032. this.wordSpacing = 0;
  6033. this.textHScale = 1;
  6034. this.textRise = 0;
  6035. // Default foreground and background colors
  6036. this.fillColor = SVG_DEFAULTS.fillColor;
  6037. this.strokeColor = '#000000';
  6038. this.fillAlpha = 1;
  6039. this.strokeAlpha = 1;
  6040. this.lineWidth = 1;
  6041. this.lineJoin = '';
  6042. this.lineCap = '';
  6043. this.miterLimit = 0;
  6044. this.dashArray = [];
  6045. this.dashPhase = 0;
  6046. this.dependencies = [];
  6047. // Clipping
  6048. this.clipId = '';
  6049. this.pendingClip = false;
  6050. this.maskId = '';
  6051. }
  6052. SVGExtraState.prototype = {
  6053. clone: function SVGExtraState_clone() {
  6054. return Object.create(this);
  6055. },
  6056. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  6057. this.x = x;
  6058. this.y = y;
  6059. }
  6060. };
  6061. return SVGExtraState;
  6062. })();
  6063. var SVGGraphics = (function SVGGraphicsClosure() {
  6064. function createScratchSVG(width, height) {
  6065. var NS = 'http://www.w3.org/2000/svg';
  6066. var svg = document.createElementNS(NS, 'svg:svg');
  6067. svg.setAttributeNS(null, 'version', '1.1');
  6068. svg.setAttributeNS(null, 'width', width + 'px');
  6069. svg.setAttributeNS(null, 'height', height + 'px');
  6070. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  6071. return svg;
  6072. }
  6073. function opListToTree(opList) {
  6074. var opTree = [];
  6075. var tmp = [];
  6076. var opListLen = opList.length;
  6077. for (var x = 0; x < opListLen; x++) {
  6078. if (opList[x].fn === 'save') {
  6079. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  6080. tmp.push(opTree);
  6081. opTree = opTree[opTree.length - 1].items;
  6082. continue;
  6083. }
  6084. if(opList[x].fn === 'restore') {
  6085. opTree = tmp.pop();
  6086. } else {
  6087. opTree.push(opList[x]);
  6088. }
  6089. }
  6090. return opTree;
  6091. }
  6092. /**
  6093. * Formats float number.
  6094. * @param value {number} number to format.
  6095. * @returns {string}
  6096. */
  6097. function pf(value) {
  6098. if (value === (value | 0)) { // integer number
  6099. return value.toString();
  6100. }
  6101. var s = value.toFixed(10);
  6102. var i = s.length - 1;
  6103. if (s[i] !== '0') {
  6104. return s;
  6105. }
  6106. // removing trailing zeros
  6107. do {
  6108. i--;
  6109. } while (s[i] === '0');
  6110. return s.substr(0, s[i] === '.' ? i : i + 1);
  6111. }
  6112. /**
  6113. * Formats transform matrix. The standard rotation, scale and translate
  6114. * matrices are replaced by their shorter forms, and for identity matrix
  6115. * returns empty string to save the memory.
  6116. * @param m {Array} matrix to format.
  6117. * @returns {string}
  6118. */
  6119. function pm(m) {
  6120. if (m[4] === 0 && m[5] === 0) {
  6121. if (m[1] === 0 && m[2] === 0) {
  6122. if (m[0] === 1 && m[3] === 1) {
  6123. return '';
  6124. }
  6125. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  6126. }
  6127. if (m[0] === m[3] && m[1] === -m[2]) {
  6128. var a = Math.acos(m[0]) * 180 / Math.PI;
  6129. return 'rotate(' + pf(a) + ')';
  6130. }
  6131. } else {
  6132. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  6133. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  6134. }
  6135. }
  6136. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  6137. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  6138. }
  6139. function SVGGraphics(commonObjs, objs) {
  6140. this.current = new SVGExtraState();
  6141. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  6142. this.transformStack = [];
  6143. this.extraStack = [];
  6144. this.commonObjs = commonObjs;
  6145. this.objs = objs;
  6146. this.pendingEOFill = false;
  6147. this.embedFonts = false;
  6148. this.embeddedFonts = {};
  6149. this.cssStyle = null;
  6150. }
  6151. var NS = 'http://www.w3.org/2000/svg';
  6152. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  6153. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  6154. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6155. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6156. var clipCount = 0;
  6157. var maskCount = 0;
  6158. SVGGraphics.prototype = {
  6159. save: function SVGGraphics_save() {
  6160. this.transformStack.push(this.transformMatrix);
  6161. var old = this.current;
  6162. this.extraStack.push(old);
  6163. this.current = old.clone();
  6164. },
  6165. restore: function SVGGraphics_restore() {
  6166. this.transformMatrix = this.transformStack.pop();
  6167. this.current = this.extraStack.pop();
  6168. this.tgrp = document.createElementNS(NS, 'svg:g');
  6169. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6170. this.pgrp.appendChild(this.tgrp);
  6171. },
  6172. group: function SVGGraphics_group(items) {
  6173. this.save();
  6174. this.executeOpTree(items);
  6175. this.restore();
  6176. },
  6177. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  6178. var fnArray = operatorList.fnArray;
  6179. var fnArrayLen = fnArray.length;
  6180. var argsArray = operatorList.argsArray;
  6181. var self = this;
  6182. for (var i = 0; i < fnArrayLen; i++) {
  6183. if (OPS.dependency === fnArray[i]) {
  6184. var deps = argsArray[i];
  6185. for (var n = 0, nn = deps.length; n < nn; n++) {
  6186. var obj = deps[n];
  6187. var common = obj.substring(0, 2) === 'g_';
  6188. var promise;
  6189. if (common) {
  6190. promise = new Promise(function(resolve) {
  6191. self.commonObjs.get(obj, resolve);
  6192. });
  6193. } else {
  6194. promise = new Promise(function(resolve) {
  6195. self.objs.get(obj, resolve);
  6196. });
  6197. }
  6198. this.current.dependencies.push(promise);
  6199. }
  6200. }
  6201. }
  6202. return Promise.all(this.current.dependencies);
  6203. },
  6204. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  6205. var transformMatrix = [a, b, c, d, e, f];
  6206. this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,
  6207. transformMatrix);
  6208. this.tgrp = document.createElementNS(NS, 'svg:g');
  6209. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6210. },
  6211. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  6212. this.svg = createScratchSVG(viewport.width, viewport.height);
  6213. this.viewport = viewport;
  6214. return this.loadDependencies(operatorList).then(function () {
  6215. this.transformMatrix = IDENTITY_MATRIX;
  6216. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  6217. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  6218. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  6219. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6220. this.defs = document.createElementNS(NS, 'svg:defs');
  6221. this.pgrp.appendChild(this.defs);
  6222. this.pgrp.appendChild(this.tgrp);
  6223. this.svg.appendChild(this.pgrp);
  6224. var opTree = this.convertOpList(operatorList);
  6225. this.executeOpTree(opTree);
  6226. return this.svg;
  6227. }.bind(this));
  6228. },
  6229. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  6230. var argsArray = operatorList.argsArray;
  6231. var fnArray = operatorList.fnArray;
  6232. var fnArrayLen = fnArray.length;
  6233. var REVOPS = [];
  6234. var opList = [];
  6235. for (var op in OPS) {
  6236. REVOPS[OPS[op]] = op;
  6237. }
  6238. for (var x = 0; x < fnArrayLen; x++) {
  6239. var fnId = fnArray[x];
  6240. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  6241. }
  6242. return opListToTree(opList);
  6243. },
  6244. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  6245. var opTreeLen = opTree.length;
  6246. for(var x = 0; x < opTreeLen; x++) {
  6247. var fn = opTree[x].fn;
  6248. var fnId = opTree[x].fnId;
  6249. var args = opTree[x].args;
  6250. switch (fnId | 0) {
  6251. case OPS.beginText:
  6252. this.beginText();
  6253. break;
  6254. case OPS.setLeading:
  6255. this.setLeading(args);
  6256. break;
  6257. case OPS.setLeadingMoveText:
  6258. this.setLeadingMoveText(args[0], args[1]);
  6259. break;
  6260. case OPS.setFont:
  6261. this.setFont(args);
  6262. break;
  6263. case OPS.showText:
  6264. this.showText(args[0]);
  6265. break;
  6266. case OPS.showSpacedText:
  6267. this.showText(args[0]);
  6268. break;
  6269. case OPS.endText:
  6270. this.endText();
  6271. break;
  6272. case OPS.moveText:
  6273. this.moveText(args[0], args[1]);
  6274. break;
  6275. case OPS.setCharSpacing:
  6276. this.setCharSpacing(args[0]);
  6277. break;
  6278. case OPS.setWordSpacing:
  6279. this.setWordSpacing(args[0]);
  6280. break;
  6281. case OPS.setTextMatrix:
  6282. this.setTextMatrix(args[0], args[1], args[2],
  6283. args[3], args[4], args[5]);
  6284. break;
  6285. case OPS.setLineWidth:
  6286. this.setLineWidth(args[0]);
  6287. break;
  6288. case OPS.setLineJoin:
  6289. this.setLineJoin(args[0]);
  6290. break;
  6291. case OPS.setLineCap:
  6292. this.setLineCap(args[0]);
  6293. break;
  6294. case OPS.setMiterLimit:
  6295. this.setMiterLimit(args[0]);
  6296. break;
  6297. case OPS.setFillRGBColor:
  6298. this.setFillRGBColor(args[0], args[1], args[2]);
  6299. break;
  6300. case OPS.setStrokeRGBColor:
  6301. this.setStrokeRGBColor(args[0], args[1], args[2]);
  6302. break;
  6303. case OPS.setDash:
  6304. this.setDash(args[0], args[1]);
  6305. break;
  6306. case OPS.setGState:
  6307. this.setGState(args[0]);
  6308. break;
  6309. case OPS.fill:
  6310. this.fill();
  6311. break;
  6312. case OPS.eoFill:
  6313. this.eoFill();
  6314. break;
  6315. case OPS.stroke:
  6316. this.stroke();
  6317. break;
  6318. case OPS.fillStroke:
  6319. this.fillStroke();
  6320. break;
  6321. case OPS.eoFillStroke:
  6322. this.eoFillStroke();
  6323. break;
  6324. case OPS.clip:
  6325. this.clip('nonzero');
  6326. break;
  6327. case OPS.eoClip:
  6328. this.clip('evenodd');
  6329. break;
  6330. case OPS.paintSolidColorImageMask:
  6331. this.paintSolidColorImageMask();
  6332. break;
  6333. case OPS.paintJpegXObject:
  6334. this.paintJpegXObject(args[0], args[1], args[2]);
  6335. break;
  6336. case OPS.paintImageXObject:
  6337. this.paintImageXObject(args[0]);
  6338. break;
  6339. case OPS.paintInlineImageXObject:
  6340. this.paintInlineImageXObject(args[0]);
  6341. break;
  6342. case OPS.paintImageMaskXObject:
  6343. this.paintImageMaskXObject(args[0]);
  6344. break;
  6345. case OPS.paintFormXObjectBegin:
  6346. this.paintFormXObjectBegin(args[0], args[1]);
  6347. break;
  6348. case OPS.paintFormXObjectEnd:
  6349. this.paintFormXObjectEnd();
  6350. break;
  6351. case OPS.closePath:
  6352. this.closePath();
  6353. break;
  6354. case OPS.closeStroke:
  6355. this.closeStroke();
  6356. break;
  6357. case OPS.closeFillStroke:
  6358. this.closeFillStroke();
  6359. break;
  6360. case OPS.nextLine:
  6361. this.nextLine();
  6362. break;
  6363. case OPS.transform:
  6364. this.transform(args[0], args[1], args[2], args[3],
  6365. args[4], args[5]);
  6366. break;
  6367. case OPS.constructPath:
  6368. this.constructPath(args[0], args[1]);
  6369. break;
  6370. case OPS.endPath:
  6371. this.endPath();
  6372. break;
  6373. case 92:
  6374. this.group(opTree[x].items);
  6375. break;
  6376. default:
  6377. warn('Unimplemented method '+ fn);
  6378. break;
  6379. }
  6380. }
  6381. },
  6382. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  6383. this.current.wordSpacing = wordSpacing;
  6384. },
  6385. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  6386. this.current.charSpacing = charSpacing;
  6387. },
  6388. nextLine: function SVGGraphics_nextLine() {
  6389. this.moveText(0, this.current.leading);
  6390. },
  6391. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  6392. var current = this.current;
  6393. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  6394. this.current.x = this.current.lineX = 0;
  6395. this.current.y = this.current.lineY = 0;
  6396. current.xcoords = [];
  6397. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6398. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6399. current.tspan.setAttributeNS(null, 'font-size',
  6400. pf(current.fontSize) + 'px');
  6401. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6402. current.txtElement = document.createElementNS(NS, 'svg:text');
  6403. current.txtElement.appendChild(current.tspan);
  6404. },
  6405. beginText: function SVGGraphics_beginText() {
  6406. this.current.x = this.current.lineX = 0;
  6407. this.current.y = this.current.lineY = 0;
  6408. this.current.textMatrix = IDENTITY_MATRIX;
  6409. this.current.lineMatrix = IDENTITY_MATRIX;
  6410. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  6411. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  6412. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  6413. this.current.xcoords = [];
  6414. },
  6415. moveText: function SVGGraphics_moveText(x, y) {
  6416. var current = this.current;
  6417. this.current.x = this.current.lineX += x;
  6418. this.current.y = this.current.lineY += y;
  6419. current.xcoords = [];
  6420. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6421. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6422. current.tspan.setAttributeNS(null, 'font-size',
  6423. pf(current.fontSize) + 'px');
  6424. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6425. },
  6426. showText: function SVGGraphics_showText(glyphs) {
  6427. var current = this.current;
  6428. var font = current.font;
  6429. var fontSize = current.fontSize;
  6430. if (fontSize === 0) {
  6431. return;
  6432. }
  6433. var charSpacing = current.charSpacing;
  6434. var wordSpacing = current.wordSpacing;
  6435. var fontDirection = current.fontDirection;
  6436. var textHScale = current.textHScale * fontDirection;
  6437. var glyphsLength = glyphs.length;
  6438. var vertical = font.vertical;
  6439. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  6440. var x = 0, i;
  6441. for (i = 0; i < glyphsLength; ++i) {
  6442. var glyph = glyphs[i];
  6443. if (glyph === null) {
  6444. // word break
  6445. x += fontDirection * wordSpacing;
  6446. continue;
  6447. } else if (isNum(glyph)) {
  6448. x += -glyph * fontSize * 0.001;
  6449. continue;
  6450. }
  6451. current.xcoords.push(current.x + x * textHScale);
  6452. var width = glyph.width;
  6453. var character = glyph.fontChar;
  6454. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  6455. x += charWidth;
  6456. current.tspan.textContent += character;
  6457. }
  6458. if (vertical) {
  6459. current.y -= x * textHScale;
  6460. } else {
  6461. current.x += x * textHScale;
  6462. }
  6463. current.tspan.setAttributeNS(null, 'x',
  6464. current.xcoords.map(pf).join(' '));
  6465. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6466. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6467. current.tspan.setAttributeNS(null, 'font-size',
  6468. pf(current.fontSize) + 'px');
  6469. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  6470. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  6471. }
  6472. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  6473. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  6474. }
  6475. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  6476. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  6477. }
  6478. current.txtElement.setAttributeNS(null, 'transform',
  6479. pm(current.textMatrix) +
  6480. ' scale(1, -1)' );
  6481. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  6482. current.txtElement.appendChild(current.tspan);
  6483. current.txtgrp.appendChild(current.txtElement);
  6484. this.tgrp.appendChild(current.txtElement);
  6485. },
  6486. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  6487. this.setLeading(-y);
  6488. this.moveText(x, y);
  6489. },
  6490. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  6491. if (!this.cssStyle) {
  6492. this.cssStyle = document.createElementNS(NS, 'svg:style');
  6493. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  6494. this.defs.appendChild(this.cssStyle);
  6495. }
  6496. var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);
  6497. this.cssStyle.textContent +=
  6498. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  6499. ' src: url(' + url + '); }\n';
  6500. },
  6501. setFont: function SVGGraphics_setFont(details) {
  6502. var current = this.current;
  6503. var fontObj = this.commonObjs.get(details[0]);
  6504. var size = details[1];
  6505. this.current.font = fontObj;
  6506. if (this.embedFonts && fontObj.data &&
  6507. !this.embeddedFonts[fontObj.loadedName]) {
  6508. this.addFontStyle(fontObj);
  6509. this.embeddedFonts[fontObj.loadedName] = fontObj;
  6510. }
  6511. current.fontMatrix = (fontObj.fontMatrix ?
  6512. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  6513. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  6514. (fontObj.bold ? 'bold' : 'normal');
  6515. var italic = fontObj.italic ? 'italic' : 'normal';
  6516. if (size < 0) {
  6517. size = -size;
  6518. current.fontDirection = -1;
  6519. } else {
  6520. current.fontDirection = 1;
  6521. }
  6522. current.fontSize = size;
  6523. current.fontFamily = fontObj.loadedName;
  6524. current.fontWeight = bold;
  6525. current.fontStyle = italic;
  6526. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6527. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6528. current.xcoords = [];
  6529. },
  6530. endText: function SVGGraphics_endText() {
  6531. if (this.current.pendingClip) {
  6532. this.cgrp.appendChild(this.tgrp);
  6533. this.pgrp.appendChild(this.cgrp);
  6534. } else {
  6535. this.pgrp.appendChild(this.tgrp);
  6536. }
  6537. this.tgrp = document.createElementNS(NS, 'svg:g');
  6538. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6539. },
  6540. // Path properties
  6541. setLineWidth: function SVGGraphics_setLineWidth(width) {
  6542. this.current.lineWidth = width;
  6543. },
  6544. setLineCap: function SVGGraphics_setLineCap(style) {
  6545. this.current.lineCap = LINE_CAP_STYLES[style];
  6546. },
  6547. setLineJoin: function SVGGraphics_setLineJoin(style) {
  6548. this.current.lineJoin = LINE_JOIN_STYLES[style];
  6549. },
  6550. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  6551. this.current.miterLimit = limit;
  6552. },
  6553. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  6554. var color = Util.makeCssRgb(r, g, b);
  6555. this.current.strokeColor = color;
  6556. },
  6557. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  6558. var color = Util.makeCssRgb(r, g, b);
  6559. this.current.fillColor = color;
  6560. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  6561. this.current.xcoords = [];
  6562. },
  6563. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  6564. this.current.dashArray = dashArray;
  6565. this.current.dashPhase = dashPhase;
  6566. },
  6567. constructPath: function SVGGraphics_constructPath(ops, args) {
  6568. var current = this.current;
  6569. var x = current.x, y = current.y;
  6570. current.path = document.createElementNS(NS, 'svg:path');
  6571. var d = [];
  6572. var opLength = ops.length;
  6573. for (var i = 0, j = 0; i < opLength; i++) {
  6574. switch (ops[i] | 0) {
  6575. case OPS.rectangle:
  6576. x = args[j++];
  6577. y = args[j++];
  6578. var width = args[j++];
  6579. var height = args[j++];
  6580. var xw = x + width;
  6581. var yh = y + height;
  6582. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  6583. 'L', pf(x), pf(yh), 'Z');
  6584. break;
  6585. case OPS.moveTo:
  6586. x = args[j++];
  6587. y = args[j++];
  6588. d.push('M', pf(x), pf(y));
  6589. break;
  6590. case OPS.lineTo:
  6591. x = args[j++];
  6592. y = args[j++];
  6593. d.push('L', pf(x) , pf(y));
  6594. break;
  6595. case OPS.curveTo:
  6596. x = args[j + 4];
  6597. y = args[j + 5];
  6598. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  6599. pf(args[j + 3]), pf(x), pf(y));
  6600. j += 6;
  6601. break;
  6602. case OPS.curveTo2:
  6603. x = args[j + 2];
  6604. y = args[j + 3];
  6605. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  6606. pf(args[j + 2]), pf(args[j + 3]));
  6607. j += 4;
  6608. break;
  6609. case OPS.curveTo3:
  6610. x = args[j + 2];
  6611. y = args[j + 3];
  6612. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  6613. pf(x), pf(y));
  6614. j += 4;
  6615. break;
  6616. case OPS.closePath:
  6617. d.push('Z');
  6618. break;
  6619. }
  6620. }
  6621. current.path.setAttributeNS(null, 'd', d.join(' '));
  6622. current.path.setAttributeNS(null, 'stroke-miterlimit',
  6623. pf(current.miterLimit));
  6624. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  6625. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  6626. current.path.setAttributeNS(null, 'stroke-width',
  6627. pf(current.lineWidth) + 'px');
  6628. current.path.setAttributeNS(null, 'stroke-dasharray',
  6629. current.dashArray.map(pf).join(' '));
  6630. current.path.setAttributeNS(null, 'stroke-dashoffset',
  6631. pf(current.dashPhase) + 'px');
  6632. current.path.setAttributeNS(null, 'fill', 'none');
  6633. this.tgrp.appendChild(current.path);
  6634. if (current.pendingClip) {
  6635. this.cgrp.appendChild(this.tgrp);
  6636. this.pgrp.appendChild(this.cgrp);
  6637. } else {
  6638. this.pgrp.appendChild(this.tgrp);
  6639. }
  6640. // Saving a reference in current.element so that it can be addressed
  6641. // in 'fill' and 'stroke'
  6642. current.element = current.path;
  6643. current.setCurrentPoint(x, y);
  6644. },
  6645. endPath: function SVGGraphics_endPath() {
  6646. var current = this.current;
  6647. if (current.pendingClip) {
  6648. this.cgrp.appendChild(this.tgrp);
  6649. this.pgrp.appendChild(this.cgrp);
  6650. } else {
  6651. this.pgrp.appendChild(this.tgrp);
  6652. }
  6653. this.tgrp = document.createElementNS(NS, 'svg:g');
  6654. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6655. },
  6656. clip: function SVGGraphics_clip(type) {
  6657. var current = this.current;
  6658. // Add current path to clipping path
  6659. current.clipId = 'clippath' + clipCount;
  6660. clipCount++;
  6661. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  6662. this.clippath.setAttributeNS(null, 'id', current.clipId);
  6663. var clipElement = current.element.cloneNode();
  6664. if (type === 'evenodd') {
  6665. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  6666. } else {
  6667. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  6668. }
  6669. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6670. this.clippath.appendChild(clipElement);
  6671. this.defs.appendChild(this.clippath);
  6672. // Create a new group with that attribute
  6673. current.pendingClip = true;
  6674. this.cgrp = document.createElementNS(NS, 'svg:g');
  6675. this.cgrp.setAttributeNS(null, 'clip-path',
  6676. 'url(#' + current.clipId + ')');
  6677. this.pgrp.appendChild(this.cgrp);
  6678. },
  6679. closePath: function SVGGraphics_closePath() {
  6680. var current = this.current;
  6681. var d = current.path.getAttributeNS(null, 'd');
  6682. d += 'Z';
  6683. current.path.setAttributeNS(null, 'd', d);
  6684. },
  6685. setLeading: function SVGGraphics_setLeading(leading) {
  6686. this.current.leading = -leading;
  6687. },
  6688. setTextRise: function SVGGraphics_setTextRise(textRise) {
  6689. this.current.textRise = textRise;
  6690. },
  6691. setHScale: function SVGGraphics_setHScale(scale) {
  6692. this.current.textHScale = scale / 100;
  6693. },
  6694. setGState: function SVGGraphics_setGState(states) {
  6695. for (var i = 0, ii = states.length; i < ii; i++) {
  6696. var state = states[i];
  6697. var key = state[0];
  6698. var value = state[1];
  6699. switch (key) {
  6700. case 'LW':
  6701. this.setLineWidth(value);
  6702. break;
  6703. case 'LC':
  6704. this.setLineCap(value);
  6705. break;
  6706. case 'LJ':
  6707. this.setLineJoin(value);
  6708. break;
  6709. case 'ML':
  6710. this.setMiterLimit(value);
  6711. break;
  6712. case 'D':
  6713. this.setDash(value[0], value[1]);
  6714. break;
  6715. case 'RI':
  6716. break;
  6717. case 'FL':
  6718. break;
  6719. case 'Font':
  6720. this.setFont(value);
  6721. break;
  6722. case 'CA':
  6723. break;
  6724. case 'ca':
  6725. break;
  6726. case 'BM':
  6727. break;
  6728. case 'SMask':
  6729. break;
  6730. }
  6731. }
  6732. },
  6733. fill: function SVGGraphics_fill() {
  6734. var current = this.current;
  6735. current.element.setAttributeNS(null, 'fill', current.fillColor);
  6736. },
  6737. stroke: function SVGGraphics_stroke() {
  6738. var current = this.current;
  6739. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  6740. current.element.setAttributeNS(null, 'fill', 'none');
  6741. },
  6742. eoFill: function SVGGraphics_eoFill() {
  6743. var current = this.current;
  6744. current.element.setAttributeNS(null, 'fill', current.fillColor);
  6745. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  6746. },
  6747. fillStroke: function SVGGraphics_fillStroke() {
  6748. // Order is important since stroke wants fill to be none.
  6749. // First stroke, then if fill needed, it will be overwritten.
  6750. this.stroke();
  6751. this.fill();
  6752. },
  6753. eoFillStroke: function SVGGraphics_eoFillStroke() {
  6754. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  6755. this.fillStroke();
  6756. },
  6757. closeStroke: function SVGGraphics_closeStroke() {
  6758. this.closePath();
  6759. this.stroke();
  6760. },
  6761. closeFillStroke: function SVGGraphics_closeFillStroke() {
  6762. this.closePath();
  6763. this.fillStroke();
  6764. },
  6765. paintSolidColorImageMask:
  6766. function SVGGraphics_paintSolidColorImageMask() {
  6767. var current = this.current;
  6768. var rect = document.createElementNS(NS, 'svg:rect');
  6769. rect.setAttributeNS(null, 'x', '0');
  6770. rect.setAttributeNS(null, 'y', '0');
  6771. rect.setAttributeNS(null, 'width', '1px');
  6772. rect.setAttributeNS(null, 'height', '1px');
  6773. rect.setAttributeNS(null, 'fill', current.fillColor);
  6774. this.tgrp.appendChild(rect);
  6775. },
  6776. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  6777. var current = this.current;
  6778. var imgObj = this.objs.get(objId);
  6779. var imgEl = document.createElementNS(NS, 'svg:image');
  6780. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  6781. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  6782. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  6783. imgEl.setAttributeNS(null, 'x', '0');
  6784. imgEl.setAttributeNS(null, 'y', pf(-h));
  6785. imgEl.setAttributeNS(null, 'transform',
  6786. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  6787. this.tgrp.appendChild(imgEl);
  6788. if (current.pendingClip) {
  6789. this.cgrp.appendChild(this.tgrp);
  6790. this.pgrp.appendChild(this.cgrp);
  6791. } else {
  6792. this.pgrp.appendChild(this.tgrp);
  6793. }
  6794. },
  6795. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  6796. var imgData = this.objs.get(objId);
  6797. if (!imgData) {
  6798. warn('Dependent image isn\'t ready yet');
  6799. return;
  6800. }
  6801. this.paintInlineImageXObject(imgData);
  6802. },
  6803. paintInlineImageXObject:
  6804. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  6805. var current = this.current;
  6806. var width = imgData.width;
  6807. var height = imgData.height;
  6808. var imgSrc = convertImgDataToPng(imgData);
  6809. var cliprect = document.createElementNS(NS, 'svg:rect');
  6810. cliprect.setAttributeNS(null, 'x', '0');
  6811. cliprect.setAttributeNS(null, 'y', '0');
  6812. cliprect.setAttributeNS(null, 'width', pf(width));
  6813. cliprect.setAttributeNS(null, 'height', pf(height));
  6814. current.element = cliprect;
  6815. this.clip('nonzero');
  6816. var imgEl = document.createElementNS(NS, 'svg:image');
  6817. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  6818. imgEl.setAttributeNS(null, 'x', '0');
  6819. imgEl.setAttributeNS(null, 'y', pf(-height));
  6820. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  6821. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  6822. imgEl.setAttributeNS(null, 'transform',
  6823. 'scale(' + pf(1 / width) + ' ' +
  6824. pf(-1 / height) + ')');
  6825. if (mask) {
  6826. mask.appendChild(imgEl);
  6827. } else {
  6828. this.tgrp.appendChild(imgEl);
  6829. }
  6830. if (current.pendingClip) {
  6831. this.cgrp.appendChild(this.tgrp);
  6832. this.pgrp.appendChild(this.cgrp);
  6833. } else {
  6834. this.pgrp.appendChild(this.tgrp);
  6835. }
  6836. },
  6837. paintImageMaskXObject:
  6838. function SVGGraphics_paintImageMaskXObject(imgData) {
  6839. var current = this.current;
  6840. var width = imgData.width;
  6841. var height = imgData.height;
  6842. var fillColor = current.fillColor;
  6843. current.maskId = 'mask' + maskCount++;
  6844. var mask = document.createElementNS(NS, 'svg:mask');
  6845. mask.setAttributeNS(null, 'id', current.maskId);
  6846. var rect = document.createElementNS(NS, 'svg:rect');
  6847. rect.setAttributeNS(null, 'x', '0');
  6848. rect.setAttributeNS(null, 'y', '0');
  6849. rect.setAttributeNS(null, 'width', pf(width));
  6850. rect.setAttributeNS(null, 'height', pf(height));
  6851. rect.setAttributeNS(null, 'fill', fillColor);
  6852. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  6853. this.defs.appendChild(mask);
  6854. this.tgrp.appendChild(rect);
  6855. this.paintInlineImageXObject(imgData, mask);
  6856. },
  6857. paintFormXObjectBegin:
  6858. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  6859. this.save();
  6860. if (isArray(matrix) && matrix.length === 6) {
  6861. this.transform(matrix[0], matrix[1], matrix[2],
  6862. matrix[3], matrix[4], matrix[5]);
  6863. }
  6864. if (isArray(bbox) && bbox.length === 4) {
  6865. var width = bbox[2] - bbox[0];
  6866. var height = bbox[3] - bbox[1];
  6867. var cliprect = document.createElementNS(NS, 'svg:rect');
  6868. cliprect.setAttributeNS(null, 'x', bbox[0]);
  6869. cliprect.setAttributeNS(null, 'y', bbox[1]);
  6870. cliprect.setAttributeNS(null, 'width', pf(width));
  6871. cliprect.setAttributeNS(null, 'height', pf(height));
  6872. this.current.element = cliprect;
  6873. this.clip('nonzero');
  6874. this.endPath();
  6875. }
  6876. },
  6877. paintFormXObjectEnd:
  6878. function SVGGraphics_paintFormXObjectEnd() {
  6879. this.restore();
  6880. }
  6881. };
  6882. return SVGGraphics;
  6883. })();
  6884. PDFJS.SVGGraphics = SVGGraphics;
  6885. var NetworkManager = (function NetworkManagerClosure() {
  6886. var OK_RESPONSE = 200;
  6887. var PARTIAL_CONTENT_RESPONSE = 206;
  6888. function NetworkManager(url, args) {
  6889. this.url = url;
  6890. args = args || {};
  6891. this.isHttp = /^https?:/i.test(url);
  6892. this.httpHeaders = (this.isHttp && args.httpHeaders) || {};
  6893. this.withCredentials = args.withCredentials || false;
  6894. this.getXhr = args.getXhr ||
  6895. function NetworkManager_getXhr() {
  6896. return new XMLHttpRequest();
  6897. };
  6898. this.currXhrId = 0;
  6899. this.pendingRequests = {};
  6900. this.loadedRequests = {};
  6901. }
  6902. function getArrayBuffer(xhr) {
  6903. var data = xhr.response;
  6904. if (typeof data !== 'string') {
  6905. return data;
  6906. }
  6907. var length = data.length;
  6908. var array = new Uint8Array(length);
  6909. for (var i = 0; i < length; i++) {
  6910. array[i] = data.charCodeAt(i) & 0xFF;
  6911. }
  6912. return array.buffer;
  6913. }
  6914. NetworkManager.prototype = {
  6915. requestRange: function NetworkManager_requestRange(begin, end, listeners) {
  6916. var args = {
  6917. begin: begin,
  6918. end: end
  6919. };
  6920. for (var prop in listeners) {
  6921. args[prop] = listeners[prop];
  6922. }
  6923. return this.request(args);
  6924. },
  6925. requestFull: function NetworkManager_requestFull(listeners) {
  6926. return this.request(listeners);
  6927. },
  6928. request: function NetworkManager_request(args) {
  6929. var xhr = this.getXhr();
  6930. var xhrId = this.currXhrId++;
  6931. var pendingRequest = this.pendingRequests[xhrId] = {
  6932. xhr: xhr
  6933. };
  6934. xhr.open('GET', this.url);
  6935. xhr.withCredentials = this.withCredentials;
  6936. for (var property in this.httpHeaders) {
  6937. var value = this.httpHeaders[property];
  6938. if (typeof value === 'undefined') {
  6939. continue;
  6940. }
  6941. xhr.setRequestHeader(property, value);
  6942. }
  6943. if (this.isHttp && 'begin' in args && 'end' in args) {
  6944. var rangeStr = args.begin + '-' + (args.end - 1);
  6945. xhr.setRequestHeader('Range', 'bytes=' + rangeStr);
  6946. pendingRequest.expectedStatus = 206;
  6947. } else {
  6948. pendingRequest.expectedStatus = 200;
  6949. }
  6950. if (args.onProgressiveData) {
  6951. // Some legacy browsers might throw an exception.
  6952. try {
  6953. xhr.responseType = 'moz-chunked-arraybuffer';
  6954. } catch(e) {}
  6955. if (xhr.responseType === 'moz-chunked-arraybuffer') {
  6956. pendingRequest.onProgressiveData = args.onProgressiveData;
  6957. pendingRequest.mozChunked = true;
  6958. } else {
  6959. xhr.responseType = 'arraybuffer';
  6960. }
  6961. } else {
  6962. xhr.responseType = 'arraybuffer';
  6963. }
  6964. if (args.onError) {
  6965. xhr.onerror = function(evt) {
  6966. args.onError(xhr.status);
  6967. };
  6968. }
  6969. xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
  6970. xhr.onprogress = this.onProgress.bind(this, xhrId);
  6971. pendingRequest.onHeadersReceived = args.onHeadersReceived;
  6972. pendingRequest.onDone = args.onDone;
  6973. pendingRequest.onError = args.onError;
  6974. pendingRequest.onProgress = args.onProgress;
  6975. xhr.send(null);
  6976. return xhrId;
  6977. },
  6978. onProgress: function NetworkManager_onProgress(xhrId, evt) {
  6979. var pendingRequest = this.pendingRequests[xhrId];
  6980. if (!pendingRequest) {
  6981. // Maybe abortRequest was called...
  6982. return;
  6983. }
  6984. if (pendingRequest.mozChunked) {
  6985. var chunk = getArrayBuffer(pendingRequest.xhr);
  6986. pendingRequest.onProgressiveData(chunk);
  6987. }
  6988. var onProgress = pendingRequest.onProgress;
  6989. if (onProgress) {
  6990. onProgress(evt);
  6991. }
  6992. },
  6993. onStateChange: function NetworkManager_onStateChange(xhrId, evt) {
  6994. var pendingRequest = this.pendingRequests[xhrId];
  6995. if (!pendingRequest) {
  6996. // Maybe abortRequest was called...
  6997. return;
  6998. }
  6999. var xhr = pendingRequest.xhr;
  7000. if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
  7001. pendingRequest.onHeadersReceived();
  7002. delete pendingRequest.onHeadersReceived;
  7003. }
  7004. if (xhr.readyState !== 4) {
  7005. return;
  7006. }
  7007. if (!(xhrId in this.pendingRequests)) {
  7008. // The XHR request might have been aborted in onHeadersReceived()
  7009. // callback, in which case we should abort request
  7010. return;
  7011. }
  7012. delete this.pendingRequests[xhrId];
  7013. // success status == 0 can be on ftp, file and other protocols
  7014. if (xhr.status === 0 && this.isHttp) {
  7015. if (pendingRequest.onError) {
  7016. pendingRequest.onError(xhr.status);
  7017. }
  7018. return;
  7019. }
  7020. var xhrStatus = xhr.status || OK_RESPONSE;
  7021. // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2:
  7022. // "A server MAY ignore the Range header". This means it's possible to
  7023. // get a 200 rather than a 206 response from a range request.
  7024. var ok_response_on_range_request =
  7025. xhrStatus === OK_RESPONSE &&
  7026. pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
  7027. if (!ok_response_on_range_request &&
  7028. xhrStatus !== pendingRequest.expectedStatus) {
  7029. if (pendingRequest.onError) {
  7030. pendingRequest.onError(xhr.status);
  7031. }
  7032. return;
  7033. }
  7034. this.loadedRequests[xhrId] = true;
  7035. var chunk = getArrayBuffer(xhr);
  7036. if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
  7037. var rangeHeader = xhr.getResponseHeader('Content-Range');
  7038. var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
  7039. var begin = parseInt(matches[1], 10);
  7040. pendingRequest.onDone({
  7041. begin: begin,
  7042. chunk: chunk
  7043. });
  7044. } else if (pendingRequest.onProgressiveData) {
  7045. pendingRequest.onDone(null);
  7046. } else {
  7047. pendingRequest.onDone({
  7048. begin: 0,
  7049. chunk: chunk
  7050. });
  7051. }
  7052. },
  7053. hasPendingRequests: function NetworkManager_hasPendingRequests() {
  7054. for (var xhrId in this.pendingRequests) {
  7055. return true;
  7056. }
  7057. return false;
  7058. },
  7059. getRequestXhr: function NetworkManager_getXhr(xhrId) {
  7060. return this.pendingRequests[xhrId].xhr;
  7061. },
  7062. isStreamingRequest: function NetworkManager_isStreamingRequest(xhrId) {
  7063. return !!(this.pendingRequests[xhrId].onProgressiveData);
  7064. },
  7065. isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {
  7066. return xhrId in this.pendingRequests;
  7067. },
  7068. isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {
  7069. return xhrId in this.loadedRequests;
  7070. },
  7071. abortAllRequests: function NetworkManager_abortAllRequests() {
  7072. for (var xhrId in this.pendingRequests) {
  7073. this.abortRequest(xhrId | 0);
  7074. }
  7075. },
  7076. abortRequest: function NetworkManager_abortRequest(xhrId) {
  7077. var xhr = this.pendingRequests[xhrId].xhr;
  7078. delete this.pendingRequests[xhrId];
  7079. xhr.abort();
  7080. }
  7081. };
  7082. return NetworkManager;
  7083. })();
  7084. var ChunkedStream = (function ChunkedStreamClosure() {
  7085. function ChunkedStream(length, chunkSize, manager) {
  7086. this.bytes = new Uint8Array(length);
  7087. this.start = 0;
  7088. this.pos = 0;
  7089. this.end = length;
  7090. this.chunkSize = chunkSize;
  7091. this.loadedChunks = [];
  7092. this.numChunksLoaded = 0;
  7093. this.numChunks = Math.ceil(length / chunkSize);
  7094. this.manager = manager;
  7095. this.progressiveDataLength = 0;
  7096. this.lastSuccessfulEnsureByteChunk = -1; // a single-entry cache
  7097. }
  7098. // required methods for a stream. if a particular stream does not
  7099. // implement these, an error should be thrown
  7100. ChunkedStream.prototype = {
  7101. getMissingChunks: function ChunkedStream_getMissingChunks() {
  7102. var chunks = [];
  7103. for (var chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
  7104. if (!this.loadedChunks[chunk]) {
  7105. chunks.push(chunk);
  7106. }
  7107. }
  7108. return chunks;
  7109. },
  7110. getBaseStreams: function ChunkedStream_getBaseStreams() {
  7111. return [this];
  7112. },
  7113. allChunksLoaded: function ChunkedStream_allChunksLoaded() {
  7114. return this.numChunksLoaded === this.numChunks;
  7115. },
  7116. onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) {
  7117. var end = begin + chunk.byteLength;
  7118. assert(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin);
  7119. // Using this.length is inaccurate here since this.start can be moved
  7120. // See ChunkedStream.moveStart()
  7121. var length = this.bytes.length;
  7122. assert(end % this.chunkSize === 0 || end === length,
  7123. 'Bad end offset: ' + end);
  7124. this.bytes.set(new Uint8Array(chunk), begin);
  7125. var chunkSize = this.chunkSize;
  7126. var beginChunk = Math.floor(begin / chunkSize);
  7127. var endChunk = Math.floor((end - 1) / chunkSize) + 1;
  7128. var curChunk;
  7129. for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  7130. if (!this.loadedChunks[curChunk]) {
  7131. this.loadedChunks[curChunk] = true;
  7132. ++this.numChunksLoaded;
  7133. }
  7134. }
  7135. },
  7136. onReceiveProgressiveData:
  7137. function ChunkedStream_onReceiveProgressiveData(data) {
  7138. var position = this.progressiveDataLength;
  7139. var beginChunk = Math.floor(position / this.chunkSize);
  7140. this.bytes.set(new Uint8Array(data), position);
  7141. position += data.byteLength;
  7142. this.progressiveDataLength = position;
  7143. var endChunk = position >= this.end ? this.numChunks :
  7144. Math.floor(position / this.chunkSize);
  7145. var curChunk;
  7146. for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  7147. if (!this.loadedChunks[curChunk]) {
  7148. this.loadedChunks[curChunk] = true;
  7149. ++this.numChunksLoaded;
  7150. }
  7151. }
  7152. },
  7153. ensureByte: function ChunkedStream_ensureByte(pos) {
  7154. var chunk = Math.floor(pos / this.chunkSize);
  7155. if (chunk === this.lastSuccessfulEnsureByteChunk) {
  7156. return;
  7157. }
  7158. if (!this.loadedChunks[chunk]) {
  7159. throw new MissingDataException(pos, pos + 1);
  7160. }
  7161. this.lastSuccessfulEnsureByteChunk = chunk;
  7162. },
  7163. ensureRange: function ChunkedStream_ensureRange(begin, end) {
  7164. if (begin >= end) {
  7165. return;
  7166. }
  7167. if (end <= this.progressiveDataLength) {
  7168. return;
  7169. }
  7170. var chunkSize = this.chunkSize;
  7171. var beginChunk = Math.floor(begin / chunkSize);
  7172. var endChunk = Math.floor((end - 1) / chunkSize) + 1;
  7173. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7174. if (!this.loadedChunks[chunk]) {
  7175. throw new MissingDataException(begin, end);
  7176. }
  7177. }
  7178. },
  7179. nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) {
  7180. var chunk, n;
  7181. for (chunk = beginChunk, n = this.numChunks; chunk < n; ++chunk) {
  7182. if (!this.loadedChunks[chunk]) {
  7183. return chunk;
  7184. }
  7185. }
  7186. // Wrap around to beginning
  7187. for (chunk = 0; chunk < beginChunk; ++chunk) {
  7188. if (!this.loadedChunks[chunk]) {
  7189. return chunk;
  7190. }
  7191. }
  7192. return null;
  7193. },
  7194. hasChunk: function ChunkedStream_hasChunk(chunk) {
  7195. return !!this.loadedChunks[chunk];
  7196. },
  7197. get length() {
  7198. return this.end - this.start;
  7199. },
  7200. get isEmpty() {
  7201. return this.length === 0;
  7202. },
  7203. getByte: function ChunkedStream_getByte() {
  7204. var pos = this.pos;
  7205. if (pos >= this.end) {
  7206. return -1;
  7207. }
  7208. this.ensureByte(pos);
  7209. return this.bytes[this.pos++];
  7210. },
  7211. getUint16: function ChunkedStream_getUint16() {
  7212. var b0 = this.getByte();
  7213. var b1 = this.getByte();
  7214. return (b0 << 8) + b1;
  7215. },
  7216. getInt32: function ChunkedStream_getInt32() {
  7217. var b0 = this.getByte();
  7218. var b1 = this.getByte();
  7219. var b2 = this.getByte();
  7220. var b3 = this.getByte();
  7221. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  7222. },
  7223. // returns subarray of original buffer
  7224. // should only be read
  7225. getBytes: function ChunkedStream_getBytes(length) {
  7226. var bytes = this.bytes;
  7227. var pos = this.pos;
  7228. var strEnd = this.end;
  7229. if (!length) {
  7230. this.ensureRange(pos, strEnd);
  7231. return bytes.subarray(pos, strEnd);
  7232. }
  7233. var end = pos + length;
  7234. if (end > strEnd) {
  7235. end = strEnd;
  7236. }
  7237. this.ensureRange(pos, end);
  7238. this.pos = end;
  7239. return bytes.subarray(pos, end);
  7240. },
  7241. peekByte: function ChunkedStream_peekByte() {
  7242. var peekedByte = this.getByte();
  7243. this.pos--;
  7244. return peekedByte;
  7245. },
  7246. peekBytes: function ChunkedStream_peekBytes(length) {
  7247. var bytes = this.getBytes(length);
  7248. this.pos -= bytes.length;
  7249. return bytes;
  7250. },
  7251. getByteRange: function ChunkedStream_getBytes(begin, end) {
  7252. this.ensureRange(begin, end);
  7253. return this.bytes.subarray(begin, end);
  7254. },
  7255. skip: function ChunkedStream_skip(n) {
  7256. if (!n) {
  7257. n = 1;
  7258. }
  7259. this.pos += n;
  7260. },
  7261. reset: function ChunkedStream_reset() {
  7262. this.pos = this.start;
  7263. },
  7264. moveStart: function ChunkedStream_moveStart() {
  7265. this.start = this.pos;
  7266. },
  7267. makeSubStream: function ChunkedStream_makeSubStream(start, length, dict) {
  7268. this.ensureRange(start, start + length);
  7269. function ChunkedStreamSubstream() {}
  7270. ChunkedStreamSubstream.prototype = Object.create(this);
  7271. ChunkedStreamSubstream.prototype.getMissingChunks = function() {
  7272. var chunkSize = this.chunkSize;
  7273. var beginChunk = Math.floor(this.start / chunkSize);
  7274. var endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
  7275. var missingChunks = [];
  7276. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7277. if (!this.loadedChunks[chunk]) {
  7278. missingChunks.push(chunk);
  7279. }
  7280. }
  7281. return missingChunks;
  7282. };
  7283. var subStream = new ChunkedStreamSubstream();
  7284. subStream.pos = subStream.start = start;
  7285. subStream.end = start + length || this.end;
  7286. subStream.dict = dict;
  7287. return subStream;
  7288. },
  7289. isStream: true
  7290. };
  7291. return ChunkedStream;
  7292. })();
  7293. var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {
  7294. function ChunkedStreamManager(length, chunkSize, url, args) {
  7295. this.stream = new ChunkedStream(length, chunkSize, this);
  7296. this.length = length;
  7297. this.chunkSize = chunkSize;
  7298. this.url = url;
  7299. this.disableAutoFetch = args.disableAutoFetch;
  7300. var msgHandler = this.msgHandler = args.msgHandler;
  7301. if (args.chunkedViewerLoading) {
  7302. msgHandler.on('OnDataRange', this.onReceiveData.bind(this));
  7303. msgHandler.on('OnDataProgress', this.onProgress.bind(this));
  7304. this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {
  7305. msgHandler.send('RequestDataRange', { begin: begin, end: end });
  7306. };
  7307. } else {
  7308. var getXhr = function getXhr() {
  7309. return new XMLHttpRequest();
  7310. };
  7311. this.networkManager = new NetworkManager(this.url, {
  7312. getXhr: getXhr,
  7313. httpHeaders: args.httpHeaders,
  7314. withCredentials: args.withCredentials
  7315. });
  7316. this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {
  7317. this.networkManager.requestRange(begin, end, {
  7318. onDone: this.onReceiveData.bind(this),
  7319. onProgress: this.onProgress.bind(this)
  7320. });
  7321. };
  7322. }
  7323. this.currRequestId = 0;
  7324. this.chunksNeededByRequest = {};
  7325. this.requestsByChunk = {};
  7326. this.callbacksByRequest = {};
  7327. this.progressiveDataLength = 0;
  7328. this._loadedStreamCapability = createPromiseCapability();
  7329. if (args.initialData) {
  7330. this.onReceiveData({chunk: args.initialData});
  7331. }
  7332. }
  7333. ChunkedStreamManager.prototype = {
  7334. onLoadedStream: function ChunkedStreamManager_getLoadedStream() {
  7335. return this._loadedStreamCapability.promise;
  7336. },
  7337. // Get all the chunks that are not yet loaded and groups them into
  7338. // contiguous ranges to load in as few requests as possible
  7339. requestAllChunks: function ChunkedStreamManager_requestAllChunks() {
  7340. var missingChunks = this.stream.getMissingChunks();
  7341. this.requestChunks(missingChunks);
  7342. return this._loadedStreamCapability.promise;
  7343. },
  7344. requestChunks: function ChunkedStreamManager_requestChunks(chunks,
  7345. callback) {
  7346. var requestId = this.currRequestId++;
  7347. var chunksNeeded;
  7348. var i, ii;
  7349. this.chunksNeededByRequest[requestId] = chunksNeeded = {};
  7350. for (i = 0, ii = chunks.length; i < ii; i++) {
  7351. if (!this.stream.hasChunk(chunks[i])) {
  7352. chunksNeeded[chunks[i]] = true;
  7353. }
  7354. }
  7355. if (isEmptyObj(chunksNeeded)) {
  7356. if (callback) {
  7357. callback();
  7358. }
  7359. return;
  7360. }
  7361. this.callbacksByRequest[requestId] = callback;
  7362. var chunksToRequest = [];
  7363. for (var chunk in chunksNeeded) {
  7364. chunk = chunk | 0;
  7365. if (!(chunk in this.requestsByChunk)) {
  7366. this.requestsByChunk[chunk] = [];
  7367. chunksToRequest.push(chunk);
  7368. }
  7369. this.requestsByChunk[chunk].push(requestId);
  7370. }
  7371. if (!chunksToRequest.length) {
  7372. return;
  7373. }
  7374. var groupedChunksToRequest = this.groupChunks(chunksToRequest);
  7375. for (i = 0; i < groupedChunksToRequest.length; ++i) {
  7376. var groupedChunk = groupedChunksToRequest[i];
  7377. var begin = groupedChunk.beginChunk * this.chunkSize;
  7378. var end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
  7379. this.sendRequest(begin, end);
  7380. }
  7381. },
  7382. getStream: function ChunkedStreamManager_getStream() {
  7383. return this.stream;
  7384. },
  7385. // Loads any chunks in the requested range that are not yet loaded
  7386. requestRange: function ChunkedStreamManager_requestRange(
  7387. begin, end, callback) {
  7388. end = Math.min(end, this.length);
  7389. var beginChunk = this.getBeginChunk(begin);
  7390. var endChunk = this.getEndChunk(end);
  7391. var chunks = [];
  7392. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7393. chunks.push(chunk);
  7394. }
  7395. this.requestChunks(chunks, callback);
  7396. },
  7397. requestRanges: function ChunkedStreamManager_requestRanges(ranges,
  7398. callback) {
  7399. ranges = ranges || [];
  7400. var chunksToRequest = [];
  7401. for (var i = 0; i < ranges.length; i++) {
  7402. var beginChunk = this.getBeginChunk(ranges[i].begin);
  7403. var endChunk = this.getEndChunk(ranges[i].end);
  7404. for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
  7405. if (chunksToRequest.indexOf(chunk) < 0) {
  7406. chunksToRequest.push(chunk);
  7407. }
  7408. }
  7409. }
  7410. chunksToRequest.sort(function(a, b) { return a - b; });
  7411. this.requestChunks(chunksToRequest, callback);
  7412. },
  7413. // Groups a sorted array of chunks into as few continguous larger
  7414. // chunks as possible
  7415. groupChunks: function ChunkedStreamManager_groupChunks(chunks) {
  7416. var groupedChunks = [];
  7417. var beginChunk = -1;
  7418. var prevChunk = -1;
  7419. for (var i = 0; i < chunks.length; ++i) {
  7420. var chunk = chunks[i];
  7421. if (beginChunk < 0) {
  7422. beginChunk = chunk;
  7423. }
  7424. if (prevChunk >= 0 && prevChunk + 1 !== chunk) {
  7425. groupedChunks.push({ beginChunk: beginChunk,
  7426. endChunk: prevChunk + 1 });
  7427. beginChunk = chunk;
  7428. }
  7429. if (i + 1 === chunks.length) {
  7430. groupedChunks.push({ beginChunk: beginChunk,
  7431. endChunk: chunk + 1 });
  7432. }
  7433. prevChunk = chunk;
  7434. }
  7435. return groupedChunks;
  7436. },
  7437. onProgress: function ChunkedStreamManager_onProgress(args) {
  7438. var bytesLoaded = (this.stream.numChunksLoaded * this.chunkSize +
  7439. args.loaded);
  7440. this.msgHandler.send('DocProgress', {
  7441. loaded: bytesLoaded,
  7442. total: this.length
  7443. });
  7444. },
  7445. onReceiveData: function ChunkedStreamManager_onReceiveData(args) {
  7446. var chunk = args.chunk;
  7447. var isProgressive = args.begin === undefined;
  7448. var begin = isProgressive ? this.progressiveDataLength : args.begin;
  7449. var end = begin + chunk.byteLength;
  7450. var beginChunk = Math.floor(begin / this.chunkSize);
  7451. var endChunk = end < this.length ? Math.floor(end / this.chunkSize) :
  7452. Math.ceil(end / this.chunkSize);
  7453. if (isProgressive) {
  7454. this.stream.onReceiveProgressiveData(chunk);
  7455. this.progressiveDataLength = end;
  7456. } else {
  7457. this.stream.onReceiveData(begin, chunk);
  7458. }
  7459. if (this.stream.allChunksLoaded()) {
  7460. this._loadedStreamCapability.resolve(this.stream);
  7461. }
  7462. var loadedRequests = [];
  7463. var i, requestId;
  7464. for (chunk = beginChunk; chunk < endChunk; ++chunk) {
  7465. // The server might return more chunks than requested
  7466. var requestIds = this.requestsByChunk[chunk] || [];
  7467. delete this.requestsByChunk[chunk];
  7468. for (i = 0; i < requestIds.length; ++i) {
  7469. requestId = requestIds[i];
  7470. var chunksNeeded = this.chunksNeededByRequest[requestId];
  7471. if (chunk in chunksNeeded) {
  7472. delete chunksNeeded[chunk];
  7473. }
  7474. if (!isEmptyObj(chunksNeeded)) {
  7475. continue;
  7476. }
  7477. loadedRequests.push(requestId);
  7478. }
  7479. }
  7480. // If there are no pending requests, automatically fetch the next
  7481. // unfetched chunk of the PDF
  7482. if (!this.disableAutoFetch && isEmptyObj(this.requestsByChunk)) {
  7483. var nextEmptyChunk;
  7484. if (this.stream.numChunksLoaded === 1) {
  7485. // This is a special optimization so that after fetching the first
  7486. // chunk, rather than fetching the second chunk, we fetch the last
  7487. // chunk.
  7488. var lastChunk = this.stream.numChunks - 1;
  7489. if (!this.stream.hasChunk(lastChunk)) {
  7490. nextEmptyChunk = lastChunk;
  7491. }
  7492. } else {
  7493. nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
  7494. }
  7495. if (isInt(nextEmptyChunk)) {
  7496. this.requestChunks([nextEmptyChunk]);
  7497. }
  7498. }
  7499. for (i = 0; i < loadedRequests.length; ++i) {
  7500. requestId = loadedRequests[i];
  7501. var callback = this.callbacksByRequest[requestId];
  7502. delete this.callbacksByRequest[requestId];
  7503. if (callback) {
  7504. callback();
  7505. }
  7506. }
  7507. this.msgHandler.send('DocProgress', {
  7508. loaded: this.stream.numChunksLoaded * this.chunkSize,
  7509. total: this.length
  7510. });
  7511. },
  7512. onError: function ChunkedStreamManager_onError(err) {
  7513. this._loadedStreamCapability.reject(err);
  7514. },
  7515. getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) {
  7516. var chunk = Math.floor(begin / this.chunkSize);
  7517. return chunk;
  7518. },
  7519. getEndChunk: function ChunkedStreamManager_getEndChunk(end) {
  7520. if (end % this.chunkSize === 0) {
  7521. return end / this.chunkSize;
  7522. }
  7523. // 0 -> 0
  7524. // 1 -> 1
  7525. // 99 -> 1
  7526. // 100 -> 1
  7527. // 101 -> 2
  7528. var chunk = Math.floor((end - 1) / this.chunkSize) + 1;
  7529. return chunk;
  7530. }
  7531. };
  7532. return ChunkedStreamManager;
  7533. })();
  7534. // The maximum number of bytes fetched per range request
  7535. var RANGE_CHUNK_SIZE = 65536;
  7536. // TODO(mack): Make use of PDFJS.Util.inherit() when it becomes available
  7537. var BasePdfManager = (function BasePdfManagerClosure() {
  7538. function BasePdfManager() {
  7539. throw new Error('Cannot initialize BaseManagerManager');
  7540. }
  7541. BasePdfManager.prototype = {
  7542. onLoadedStream: function BasePdfManager_onLoadedStream() {
  7543. throw new NotImplementedException();
  7544. },
  7545. ensureDoc: function BasePdfManager_ensureDoc(prop, args) {
  7546. return this.ensure(this.pdfDocument, prop, args);
  7547. },
  7548. ensureXRef: function BasePdfManager_ensureXRef(prop, args) {
  7549. return this.ensure(this.pdfDocument.xref, prop, args);
  7550. },
  7551. ensureCatalog: function BasePdfManager_ensureCatalog(prop, args) {
  7552. return this.ensure(this.pdfDocument.catalog, prop, args);
  7553. },
  7554. getPage: function BasePdfManager_pagePage(pageIndex) {
  7555. return this.pdfDocument.getPage(pageIndex);
  7556. },
  7557. cleanup: function BasePdfManager_cleanup() {
  7558. return this.pdfDocument.cleanup();
  7559. },
  7560. ensure: function BasePdfManager_ensure(obj, prop, args) {
  7561. return new NotImplementedException();
  7562. },
  7563. requestRange: function BasePdfManager_ensure(begin, end) {
  7564. return new NotImplementedException();
  7565. },
  7566. requestLoadedStream: function BasePdfManager_requestLoadedStream() {
  7567. return new NotImplementedException();
  7568. },
  7569. sendProgressiveData: function BasePdfManager_sendProgressiveData(chunk) {
  7570. return new NotImplementedException();
  7571. },
  7572. updatePassword: function BasePdfManager_updatePassword(password) {
  7573. this.pdfDocument.xref.password = this.password = password;
  7574. if (this._passwordChangedCapability) {
  7575. this._passwordChangedCapability.resolve();
  7576. }
  7577. },
  7578. passwordChanged: function BasePdfManager_passwordChanged() {
  7579. this._passwordChangedCapability = createPromiseCapability();
  7580. return this._passwordChangedCapability.promise;
  7581. },
  7582. terminate: function BasePdfManager_terminate() {
  7583. return new NotImplementedException();
  7584. }
  7585. };
  7586. return BasePdfManager;
  7587. })();
  7588. var LocalPdfManager = (function LocalPdfManagerClosure() {
  7589. function LocalPdfManager(data, password) {
  7590. var stream = new Stream(data);
  7591. this.pdfDocument = new PDFDocument(this, stream, password);
  7592. this._loadedStreamCapability = createPromiseCapability();
  7593. this._loadedStreamCapability.resolve(stream);
  7594. }
  7595. LocalPdfManager.prototype = Object.create(BasePdfManager.prototype);
  7596. LocalPdfManager.prototype.constructor = LocalPdfManager;
  7597. LocalPdfManager.prototype.ensure =
  7598. function LocalPdfManager_ensure(obj, prop, args) {
  7599. return new Promise(function (resolve, reject) {
  7600. try {
  7601. var value = obj[prop];
  7602. var result;
  7603. if (typeof value === 'function') {
  7604. result = value.apply(obj, args);
  7605. } else {
  7606. result = value;
  7607. }
  7608. resolve(result);
  7609. } catch (e) {
  7610. reject(e);
  7611. }
  7612. });
  7613. };
  7614. LocalPdfManager.prototype.requestRange =
  7615. function LocalPdfManager_requestRange(begin, end) {
  7616. return Promise.resolve();
  7617. };
  7618. LocalPdfManager.prototype.requestLoadedStream =
  7619. function LocalPdfManager_requestLoadedStream() {
  7620. };
  7621. LocalPdfManager.prototype.onLoadedStream =
  7622. function LocalPdfManager_getLoadedStream() {
  7623. return this._loadedStreamCapability.promise;
  7624. };
  7625. LocalPdfManager.prototype.terminate =
  7626. function LocalPdfManager_terminate() {
  7627. return;
  7628. };
  7629. return LocalPdfManager;
  7630. })();
  7631. var NetworkPdfManager = (function NetworkPdfManagerClosure() {
  7632. function NetworkPdfManager(args, msgHandler) {
  7633. this.msgHandler = msgHandler;
  7634. var params = {
  7635. msgHandler: msgHandler,
  7636. httpHeaders: args.httpHeaders,
  7637. withCredentials: args.withCredentials,
  7638. chunkedViewerLoading: args.chunkedViewerLoading,
  7639. disableAutoFetch: args.disableAutoFetch,
  7640. initialData: args.initialData
  7641. };
  7642. this.streamManager = new ChunkedStreamManager(args.length, RANGE_CHUNK_SIZE,
  7643. args.url, params);
  7644. this.pdfDocument = new PDFDocument(this, this.streamManager.getStream(),
  7645. args.password);
  7646. }
  7647. NetworkPdfManager.prototype = Object.create(BasePdfManager.prototype);
  7648. NetworkPdfManager.prototype.constructor = NetworkPdfManager;
  7649. NetworkPdfManager.prototype.ensure =
  7650. function NetworkPdfManager_ensure(obj, prop, args) {
  7651. var pdfManager = this;
  7652. return new Promise(function (resolve, reject) {
  7653. function ensureHelper() {
  7654. try {
  7655. var result;
  7656. var value = obj[prop];
  7657. if (typeof value === 'function') {
  7658. result = value.apply(obj, args);
  7659. } else {
  7660. result = value;
  7661. }
  7662. resolve(result);
  7663. } catch(e) {
  7664. if (!(e instanceof MissingDataException)) {
  7665. reject(e);
  7666. return;
  7667. }
  7668. pdfManager.streamManager.requestRange(e.begin, e.end, ensureHelper);
  7669. }
  7670. }
  7671. ensureHelper();
  7672. });
  7673. };
  7674. NetworkPdfManager.prototype.requestRange =
  7675. function NetworkPdfManager_requestRange(begin, end) {
  7676. return new Promise(function (resolve) {
  7677. this.streamManager.requestRange(begin, end, function() {
  7678. resolve();
  7679. });
  7680. }.bind(this));
  7681. };
  7682. NetworkPdfManager.prototype.requestLoadedStream =
  7683. function NetworkPdfManager_requestLoadedStream() {
  7684. this.streamManager.requestAllChunks();
  7685. };
  7686. NetworkPdfManager.prototype.sendProgressiveData =
  7687. function NetworkPdfManager_sendProgressiveData(chunk) {
  7688. this.streamManager.onReceiveData({ chunk: chunk });
  7689. };
  7690. NetworkPdfManager.prototype.onLoadedStream =
  7691. function NetworkPdfManager_getLoadedStream() {
  7692. return this.streamManager.onLoadedStream();
  7693. };
  7694. NetworkPdfManager.prototype.terminate =
  7695. function NetworkPdfManager_terminate() {
  7696. this.streamManager.networkManager.abortAllRequests();
  7697. };
  7698. return NetworkPdfManager;
  7699. })();
  7700. var Page = (function PageClosure() {
  7701. var LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
  7702. function Page(pdfManager, xref, pageIndex, pageDict, ref, fontCache) {
  7703. this.pdfManager = pdfManager;
  7704. this.pageIndex = pageIndex;
  7705. this.pageDict = pageDict;
  7706. this.xref = xref;
  7707. this.ref = ref;
  7708. this.fontCache = fontCache;
  7709. this.idCounters = {
  7710. obj: 0
  7711. };
  7712. this.resourcesPromise = null;
  7713. }
  7714. Page.prototype = {
  7715. getPageProp: function Page_getPageProp(key) {
  7716. return this.pageDict.get(key);
  7717. },
  7718. getInheritedPageProp: function Page_inheritPageProp(key) {
  7719. var dict = this.pageDict;
  7720. var value = dict.get(key);
  7721. while (value === undefined) {
  7722. dict = dict.get('Parent');
  7723. if (!dict) {
  7724. break;
  7725. }
  7726. value = dict.get(key);
  7727. }
  7728. return value;
  7729. },
  7730. get content() {
  7731. return this.getPageProp('Contents');
  7732. },
  7733. get resources() {
  7734. var value = this.getInheritedPageProp('Resources');
  7735. // For robustness: The spec states that a \Resources entry has to be
  7736. // present, but can be empty. Some document omit it still. In this case
  7737. // return an empty dictionary:
  7738. if (value === undefined) {
  7739. value = Dict.empty;
  7740. }
  7741. return shadow(this, 'resources', value);
  7742. },
  7743. get mediaBox() {
  7744. var obj = this.getInheritedPageProp('MediaBox');
  7745. // Reset invalid media box to letter size.
  7746. if (!isArray(obj) || obj.length !== 4) {
  7747. obj = LETTER_SIZE_MEDIABOX;
  7748. }
  7749. return shadow(this, 'mediaBox', obj);
  7750. },
  7751. get view() {
  7752. var mediaBox = this.mediaBox;
  7753. var cropBox = this.getInheritedPageProp('CropBox');
  7754. if (!isArray(cropBox) || cropBox.length !== 4) {
  7755. return shadow(this, 'view', mediaBox);
  7756. }
  7757. // From the spec, 6th ed., p.963:
  7758. // "The crop, bleed, trim, and art boxes should not ordinarily
  7759. // extend beyond the boundaries of the media box. If they do, they are
  7760. // effectively reduced to their intersection with the media box."
  7761. cropBox = Util.intersect(cropBox, mediaBox);
  7762. if (!cropBox) {
  7763. return shadow(this, 'view', mediaBox);
  7764. }
  7765. return shadow(this, 'view', cropBox);
  7766. },
  7767. get annotationRefs() {
  7768. return shadow(this, 'annotationRefs',
  7769. this.getInheritedPageProp('Annots'));
  7770. },
  7771. get rotate() {
  7772. var rotate = this.getInheritedPageProp('Rotate') || 0;
  7773. // Normalize rotation so it's a multiple of 90 and between 0 and 270
  7774. if (rotate % 90 !== 0) {
  7775. rotate = 0;
  7776. } else if (rotate >= 360) {
  7777. rotate = rotate % 360;
  7778. } else if (rotate < 0) {
  7779. // The spec doesn't cover negatives, assume its counterclockwise
  7780. // rotation. The following is the other implementation of modulo.
  7781. rotate = ((rotate % 360) + 360) % 360;
  7782. }
  7783. return shadow(this, 'rotate', rotate);
  7784. },
  7785. getContentStream: function Page_getContentStream() {
  7786. var content = this.content;
  7787. var stream;
  7788. if (isArray(content)) {
  7789. // fetching items
  7790. var xref = this.xref;
  7791. var i, n = content.length;
  7792. var streams = [];
  7793. for (i = 0; i < n; ++i) {
  7794. streams.push(xref.fetchIfRef(content[i]));
  7795. }
  7796. stream = new StreamsSequenceStream(streams);
  7797. } else if (isStream(content)) {
  7798. stream = content;
  7799. } else {
  7800. // replacing non-existent page content with empty one
  7801. stream = new NullStream();
  7802. }
  7803. return stream;
  7804. },
  7805. loadResources: function Page_loadResources(keys) {
  7806. if (!this.resourcesPromise) {
  7807. // TODO: add async getInheritedPageProp and remove this.
  7808. this.resourcesPromise = this.pdfManager.ensure(this, 'resources');
  7809. }
  7810. return this.resourcesPromise.then(function resourceSuccess() {
  7811. var objectLoader = new ObjectLoader(this.resources.map,
  7812. keys,
  7813. this.xref);
  7814. return objectLoader.load();
  7815. }.bind(this));
  7816. },
  7817. getOperatorList: function Page_getOperatorList(handler, intent) {
  7818. var self = this;
  7819. var pdfManager = this.pdfManager;
  7820. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',
  7821. []);
  7822. var resourcesPromise = this.loadResources([
  7823. 'ExtGState',
  7824. 'ColorSpace',
  7825. 'Pattern',
  7826. 'Shading',
  7827. 'XObject',
  7828. 'Font'
  7829. // ProcSet
  7830. // Properties
  7831. ]);
  7832. var partialEvaluator = new PartialEvaluator(pdfManager, this.xref,
  7833. handler, this.pageIndex,
  7834. 'p' + this.pageIndex + '_',
  7835. this.idCounters,
  7836. this.fontCache);
  7837. var dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  7838. var pageListPromise = dataPromises.then(function(data) {
  7839. var contentStream = data[0];
  7840. var opList = new OperatorList(intent, handler, self.pageIndex);
  7841. handler.send('StartRenderPage', {
  7842. transparency: partialEvaluator.hasBlendModes(self.resources),
  7843. pageIndex: self.pageIndex,
  7844. intent: intent
  7845. });
  7846. return partialEvaluator.getOperatorList(contentStream, self.resources,
  7847. opList).then(function () {
  7848. return opList;
  7849. });
  7850. });
  7851. var annotationsPromise = pdfManager.ensure(this, 'annotations');
  7852. return Promise.all([pageListPromise, annotationsPromise]).then(
  7853. function(datas) {
  7854. var pageOpList = datas[0];
  7855. var annotations = datas[1];
  7856. if (annotations.length === 0) {
  7857. pageOpList.flush(true);
  7858. return pageOpList;
  7859. }
  7860. var annotationsReadyPromise = Annotation.appendToOperatorList(
  7861. annotations, pageOpList, pdfManager, partialEvaluator, intent);
  7862. return annotationsReadyPromise.then(function () {
  7863. pageOpList.flush(true);
  7864. return pageOpList;
  7865. });
  7866. });
  7867. },
  7868. extractTextContent: function Page_extractTextContent() {
  7869. var handler = {
  7870. on: function nullHandlerOn() {},
  7871. send: function nullHandlerSend() {}
  7872. };
  7873. var self = this;
  7874. var pdfManager = this.pdfManager;
  7875. var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',
  7876. []);
  7877. var resourcesPromise = this.loadResources([
  7878. 'ExtGState',
  7879. 'XObject',
  7880. 'Font'
  7881. ]);
  7882. var dataPromises = Promise.all([contentStreamPromise,
  7883. resourcesPromise]);
  7884. return dataPromises.then(function(data) {
  7885. var contentStream = data[0];
  7886. var partialEvaluator = new PartialEvaluator(pdfManager, self.xref,
  7887. handler, self.pageIndex,
  7888. 'p' + self.pageIndex + '_',
  7889. self.idCounters,
  7890. self.fontCache);
  7891. return partialEvaluator.getTextContent(contentStream,
  7892. self.resources);
  7893. });
  7894. },
  7895. getAnnotationsData: function Page_getAnnotationsData() {
  7896. var annotations = this.annotations;
  7897. var annotationsData = [];
  7898. for (var i = 0, n = annotations.length; i < n; ++i) {
  7899. annotationsData.push(annotations[i].getData());
  7900. }
  7901. return annotationsData;
  7902. },
  7903. get annotations() {
  7904. var annotations = [];
  7905. var annotationRefs = (this.annotationRefs || []);
  7906. for (var i = 0, n = annotationRefs.length; i < n; ++i) {
  7907. var annotationRef = annotationRefs[i];
  7908. var annotation = Annotation.fromRef(this.xref, annotationRef);
  7909. if (annotation) {
  7910. annotations.push(annotation);
  7911. }
  7912. }
  7913. return shadow(this, 'annotations', annotations);
  7914. }
  7915. };
  7916. return Page;
  7917. })();
  7918. /**
  7919. * The `PDFDocument` holds all the data of the PDF file. Compared to the
  7920. * `PDFDoc`, this one doesn't have any job management code.
  7921. * Right now there exists one PDFDocument on the main thread + one object
  7922. * for each worker. If there is no worker support enabled, there are two
  7923. * `PDFDocument` objects on the main thread created.
  7924. */
  7925. var PDFDocument = (function PDFDocumentClosure() {
  7926. var FINGERPRINT_FIRST_BYTES = 1024;
  7927. var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' +
  7928. '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
  7929. function PDFDocument(pdfManager, arg, password) {
  7930. if (isStream(arg)) {
  7931. init.call(this, pdfManager, arg, password);
  7932. } else if (isArrayBuffer(arg)) {
  7933. init.call(this, pdfManager, new Stream(arg), password);
  7934. } else {
  7935. error('PDFDocument: Unknown argument type');
  7936. }
  7937. }
  7938. function init(pdfManager, stream, password) {
  7939. assert(stream.length > 0, 'stream must have data');
  7940. this.pdfManager = pdfManager;
  7941. this.stream = stream;
  7942. var xref = new XRef(this.stream, password, pdfManager);
  7943. this.xref = xref;
  7944. }
  7945. function find(stream, needle, limit, backwards) {
  7946. var pos = stream.pos;
  7947. var end = stream.end;
  7948. var strBuf = [];
  7949. if (pos + limit > end) {
  7950. limit = end - pos;
  7951. }
  7952. for (var n = 0; n < limit; ++n) {
  7953. strBuf.push(String.fromCharCode(stream.getByte()));
  7954. }
  7955. var str = strBuf.join('');
  7956. stream.pos = pos;
  7957. var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
  7958. if (index === -1) {
  7959. return false; /* not found */
  7960. }
  7961. stream.pos += index;
  7962. return true; /* found */
  7963. }
  7964. var DocumentInfoValidators = {
  7965. get entries() {
  7966. // Lazily build this since all the validation functions below are not
  7967. // defined until after this file loads.
  7968. return shadow(this, 'entries', {
  7969. Title: isString,
  7970. Author: isString,
  7971. Subject: isString,
  7972. Keywords: isString,
  7973. Creator: isString,
  7974. Producer: isString,
  7975. CreationDate: isString,
  7976. ModDate: isString,
  7977. Trapped: isName
  7978. });
  7979. }
  7980. };
  7981. PDFDocument.prototype = {
  7982. parse: function PDFDocument_parse(recoveryMode) {
  7983. this.setup(recoveryMode);
  7984. try {
  7985. // checking if AcroForm is present
  7986. this.acroForm = this.catalog.catDict.get('AcroForm');
  7987. if (this.acroForm) {
  7988. this.xfa = this.acroForm.get('XFA');
  7989. var fields = this.acroForm.get('Fields');
  7990. if ((!fields || !isArray(fields) || fields.length === 0) &&
  7991. !this.xfa) {
  7992. // no fields and no XFA -- not a form (?)
  7993. this.acroForm = null;
  7994. }
  7995. }
  7996. } catch (ex) {
  7997. info('Something wrong with AcroForm entry');
  7998. this.acroForm = null;
  7999. }
  8000. },
  8001. get linearization() {
  8002. var linearization = null;
  8003. if (this.stream.length) {
  8004. try {
  8005. linearization = Linearization.create(this.stream);
  8006. } catch (err) {
  8007. if (err instanceof MissingDataException) {
  8008. throw err;
  8009. }
  8010. info(err);
  8011. }
  8012. }
  8013. // shadow the prototype getter with a data property
  8014. return shadow(this, 'linearization', linearization);
  8015. },
  8016. get startXRef() {
  8017. var stream = this.stream;
  8018. var startXRef = 0;
  8019. var linearization = this.linearization;
  8020. if (linearization) {
  8021. // Find end of first obj.
  8022. stream.reset();
  8023. if (find(stream, 'endobj', 1024)) {
  8024. startXRef = stream.pos + 6;
  8025. }
  8026. } else {
  8027. // Find startxref by jumping backward from the end of the file.
  8028. var step = 1024;
  8029. var found = false, pos = stream.end;
  8030. while (!found && pos > 0) {
  8031. pos -= step - 'startxref'.length;
  8032. if (pos < 0) {
  8033. pos = 0;
  8034. }
  8035. stream.pos = pos;
  8036. found = find(stream, 'startxref', step, true);
  8037. }
  8038. if (found) {
  8039. stream.skip(9);
  8040. var ch;
  8041. do {
  8042. ch = stream.getByte();
  8043. } while (Lexer.isSpace(ch));
  8044. var str = '';
  8045. while (ch >= 0x20 && ch <= 0x39) { // < '9'
  8046. str += String.fromCharCode(ch);
  8047. ch = stream.getByte();
  8048. }
  8049. startXRef = parseInt(str, 10);
  8050. if (isNaN(startXRef)) {
  8051. startXRef = 0;
  8052. }
  8053. }
  8054. }
  8055. // shadow the prototype getter with a data property
  8056. return shadow(this, 'startXRef', startXRef);
  8057. },
  8058. get mainXRefEntriesOffset() {
  8059. var mainXRefEntriesOffset = 0;
  8060. var linearization = this.linearization;
  8061. if (linearization) {
  8062. mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
  8063. }
  8064. // shadow the prototype getter with a data property
  8065. return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
  8066. },
  8067. // Find the header, remove leading garbage and setup the stream
  8068. // starting from the header.
  8069. checkHeader: function PDFDocument_checkHeader() {
  8070. var stream = this.stream;
  8071. stream.reset();
  8072. if (find(stream, '%PDF-', 1024)) {
  8073. // Found the header, trim off any garbage before it.
  8074. stream.moveStart();
  8075. // Reading file format version
  8076. var MAX_VERSION_LENGTH = 12;
  8077. var version = '', ch;
  8078. while ((ch = stream.getByte()) > 0x20) { // SPACE
  8079. if (version.length >= MAX_VERSION_LENGTH) {
  8080. break;
  8081. }
  8082. version += String.fromCharCode(ch);
  8083. }
  8084. // removing "%PDF-"-prefix
  8085. this.pdfFormatVersion = version.substring(5);
  8086. return;
  8087. }
  8088. // May not be a PDF file, continue anyway.
  8089. },
  8090. parseStartXRef: function PDFDocument_parseStartXRef() {
  8091. var startXRef = this.startXRef;
  8092. this.xref.setStartXRef(startXRef);
  8093. },
  8094. setup: function PDFDocument_setup(recoveryMode) {
  8095. this.xref.parse(recoveryMode);
  8096. this.catalog = new Catalog(this.pdfManager, this.xref);
  8097. },
  8098. get numPages() {
  8099. var linearization = this.linearization;
  8100. var num = linearization ? linearization.numPages : this.catalog.numPages;
  8101. // shadow the prototype getter
  8102. return shadow(this, 'numPages', num);
  8103. },
  8104. get documentInfo() {
  8105. var docInfo = {
  8106. PDFFormatVersion: this.pdfFormatVersion,
  8107. IsAcroFormPresent: !!this.acroForm,
  8108. IsXFAPresent: !!this.xfa
  8109. };
  8110. var infoDict;
  8111. try {
  8112. infoDict = this.xref.trailer.get('Info');
  8113. } catch (err) {
  8114. info('The document information dictionary is invalid.');
  8115. }
  8116. if (infoDict) {
  8117. var validEntries = DocumentInfoValidators.entries;
  8118. // Only fill the document info with valid entries from the spec.
  8119. for (var key in validEntries) {
  8120. if (infoDict.has(key)) {
  8121. var value = infoDict.get(key);
  8122. // Make sure the value conforms to the spec.
  8123. if (validEntries[key](value)) {
  8124. docInfo[key] = (typeof value !== 'string' ?
  8125. value : stringToPDFString(value));
  8126. } else {
  8127. info('Bad value in document info for "' + key + '"');
  8128. }
  8129. }
  8130. }
  8131. }
  8132. return shadow(this, 'documentInfo', docInfo);
  8133. },
  8134. get fingerprint() {
  8135. var xref = this.xref, hash, fileID = '';
  8136. if (xref.trailer.has('ID') &&
  8137. xref.trailer.get('ID')[0] !== EMPTY_FINGERPRINT) {
  8138. hash = stringToBytes(xref.trailer.get('ID')[0]);
  8139. } else {
  8140. if (this.stream.ensureRange) {
  8141. this.stream.ensureRange(0,
  8142. Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
  8143. }
  8144. hash = calculateMD5(this.stream.bytes.subarray(0,
  8145. FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  8146. }
  8147. for (var i = 0, n = hash.length; i < n; i++) {
  8148. var hex = hash[i].toString(16);
  8149. fileID += hex.length === 1 ? '0' + hex : hex;
  8150. }
  8151. return shadow(this, 'fingerprint', fileID);
  8152. },
  8153. getPage: function PDFDocument_getPage(pageIndex) {
  8154. return this.catalog.getPage(pageIndex);
  8155. },
  8156. cleanup: function PDFDocument_cleanup() {
  8157. return this.catalog.cleanup();
  8158. }
  8159. };
  8160. return PDFDocument;
  8161. })();
  8162. var Name = (function NameClosure() {
  8163. function Name(name) {
  8164. this.name = name;
  8165. }
  8166. Name.prototype = {};
  8167. var nameCache = {};
  8168. Name.get = function Name_get(name) {
  8169. var nameValue = nameCache[name];
  8170. return (nameValue ? nameValue : (nameCache[name] = new Name(name)));
  8171. };
  8172. return Name;
  8173. })();
  8174. var Cmd = (function CmdClosure() {
  8175. function Cmd(cmd) {
  8176. this.cmd = cmd;
  8177. }
  8178. Cmd.prototype = {};
  8179. var cmdCache = {};
  8180. Cmd.get = function Cmd_get(cmd) {
  8181. var cmdValue = cmdCache[cmd];
  8182. return (cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd)));
  8183. };
  8184. return Cmd;
  8185. })();
  8186. var Dict = (function DictClosure() {
  8187. var nonSerializable = function nonSerializableClosure() {
  8188. return nonSerializable; // creating closure on some variable
  8189. };
  8190. var GETALL_DICTIONARY_TYPES_WHITELIST = {
  8191. 'Background': true,
  8192. 'ExtGState': true,
  8193. 'Halftone': true,
  8194. 'Layout': true,
  8195. 'Mask': true,
  8196. 'Pagination': true,
  8197. 'Printing': true
  8198. };
  8199. function isRecursionAllowedFor(dict) {
  8200. if (!isName(dict.Type)) {
  8201. return true;
  8202. }
  8203. var dictType = dict.Type.name;
  8204. return GETALL_DICTIONARY_TYPES_WHITELIST[dictType] === true;
  8205. }
  8206. // xref is optional
  8207. function Dict(xref) {
  8208. // Map should only be used internally, use functions below to access.
  8209. this.map = Object.create(null);
  8210. this.xref = xref;
  8211. this.objId = null;
  8212. this.__nonSerializable__ = nonSerializable; // disable cloning of the Dict
  8213. }
  8214. Dict.prototype = {
  8215. assignXref: function Dict_assignXref(newXref) {
  8216. this.xref = newXref;
  8217. },
  8218. // automatically dereferences Ref objects
  8219. get: function Dict_get(key1, key2, key3) {
  8220. var value;
  8221. var xref = this.xref;
  8222. if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
  8223. typeof key2 === 'undefined') {
  8224. return xref ? xref.fetchIfRef(value) : value;
  8225. }
  8226. if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
  8227. typeof key3 === 'undefined') {
  8228. return xref ? xref.fetchIfRef(value) : value;
  8229. }
  8230. value = this.map[key3] || null;
  8231. return xref ? xref.fetchIfRef(value) : value;
  8232. },
  8233. // Same as get(), but returns a promise and uses fetchIfRefAsync().
  8234. getAsync: function Dict_getAsync(key1, key2, key3) {
  8235. var value;
  8236. var xref = this.xref;
  8237. if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map ||
  8238. typeof key2 === 'undefined') {
  8239. if (xref) {
  8240. return xref.fetchIfRefAsync(value);
  8241. }
  8242. return Promise.resolve(value);
  8243. }
  8244. if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map ||
  8245. typeof key3 === 'undefined') {
  8246. if (xref) {
  8247. return xref.fetchIfRefAsync(value);
  8248. }
  8249. return Promise.resolve(value);
  8250. }
  8251. value = this.map[key3] || null;
  8252. if (xref) {
  8253. return xref.fetchIfRefAsync(value);
  8254. }
  8255. return Promise.resolve(value);
  8256. },
  8257. // no dereferencing
  8258. getRaw: function Dict_getRaw(key) {
  8259. return this.map[key];
  8260. },
  8261. // creates new map and dereferences all Refs
  8262. getAll: function Dict_getAll() {
  8263. var all = Object.create(null);
  8264. var queue = null;
  8265. var key, obj;
  8266. for (key in this.map) {
  8267. obj = this.get(key);
  8268. if (obj instanceof Dict) {
  8269. if (isRecursionAllowedFor(obj)) {
  8270. (queue || (queue = [])).push({target: all, key: key, obj: obj});
  8271. } else {
  8272. all[key] = this.getRaw(key);
  8273. }
  8274. } else {
  8275. all[key] = obj;
  8276. }
  8277. }
  8278. if (!queue) {
  8279. return all;
  8280. }
  8281. // trying to take cyclic references into the account
  8282. var processed = Object.create(null);
  8283. while (queue.length > 0) {
  8284. var item = queue.shift();
  8285. var itemObj = item.obj;
  8286. var objId = itemObj.objId;
  8287. if (objId && objId in processed) {
  8288. item.target[item.key] = processed[objId];
  8289. continue;
  8290. }
  8291. var dereferenced = Object.create(null);
  8292. for (key in itemObj.map) {
  8293. obj = itemObj.get(key);
  8294. if (obj instanceof Dict) {
  8295. if (isRecursionAllowedFor(obj)) {
  8296. queue.push({target: dereferenced, key: key, obj: obj});
  8297. } else {
  8298. dereferenced[key] = itemObj.getRaw(key);
  8299. }
  8300. } else {
  8301. dereferenced[key] = obj;
  8302. }
  8303. }
  8304. if (objId) {
  8305. processed[objId] = dereferenced;
  8306. }
  8307. item.target[item.key] = dereferenced;
  8308. }
  8309. return all;
  8310. },
  8311. set: function Dict_set(key, value) {
  8312. this.map[key] = value;
  8313. },
  8314. has: function Dict_has(key) {
  8315. return key in this.map;
  8316. },
  8317. forEach: function Dict_forEach(callback) {
  8318. for (var key in this.map) {
  8319. callback(key, this.get(key));
  8320. }
  8321. }
  8322. };
  8323. Dict.empty = new Dict(null);
  8324. return Dict;
  8325. })();
  8326. var Ref = (function RefClosure() {
  8327. function Ref(num, gen) {
  8328. this.num = num;
  8329. this.gen = gen;
  8330. }
  8331. Ref.prototype = {
  8332. toString: function Ref_toString() {
  8333. // This function is hot, so we make the string as compact as possible.
  8334. // |this.gen| is almost always zero, so we treat that case specially.
  8335. var str = this.num + 'R';
  8336. if (this.gen !== 0) {
  8337. str += this.gen;
  8338. }
  8339. return str;
  8340. }
  8341. };
  8342. return Ref;
  8343. })();
  8344. // The reference is identified by number and generation.
  8345. // This structure stores only one instance of the reference.
  8346. var RefSet = (function RefSetClosure() {
  8347. function RefSet() {
  8348. this.dict = {};
  8349. }
  8350. RefSet.prototype = {
  8351. has: function RefSet_has(ref) {
  8352. return ref.toString() in this.dict;
  8353. },
  8354. put: function RefSet_put(ref) {
  8355. this.dict[ref.toString()] = true;
  8356. },
  8357. remove: function RefSet_remove(ref) {
  8358. delete this.dict[ref.toString()];
  8359. }
  8360. };
  8361. return RefSet;
  8362. })();
  8363. var RefSetCache = (function RefSetCacheClosure() {
  8364. function RefSetCache() {
  8365. this.dict = Object.create(null);
  8366. }
  8367. RefSetCache.prototype = {
  8368. get: function RefSetCache_get(ref) {
  8369. return this.dict[ref.toString()];
  8370. },
  8371. has: function RefSetCache_has(ref) {
  8372. return ref.toString() in this.dict;
  8373. },
  8374. put: function RefSetCache_put(ref, obj) {
  8375. this.dict[ref.toString()] = obj;
  8376. },
  8377. putAlias: function RefSetCache_putAlias(ref, aliasRef) {
  8378. this.dict[ref.toString()] = this.get(aliasRef);
  8379. },
  8380. forEach: function RefSetCache_forEach(fn, thisArg) {
  8381. for (var i in this.dict) {
  8382. fn.call(thisArg, this.dict[i]);
  8383. }
  8384. },
  8385. clear: function RefSetCache_clear() {
  8386. this.dict = Object.create(null);
  8387. }
  8388. };
  8389. return RefSetCache;
  8390. })();
  8391. var Catalog = (function CatalogClosure() {
  8392. function Catalog(pdfManager, xref) {
  8393. this.pdfManager = pdfManager;
  8394. this.xref = xref;
  8395. this.catDict = xref.getCatalogObj();
  8396. this.fontCache = new RefSetCache();
  8397. assert(isDict(this.catDict),
  8398. 'catalog object is not a dictionary');
  8399. this.pagePromises = [];
  8400. }
  8401. Catalog.prototype = {
  8402. get metadata() {
  8403. var streamRef = this.catDict.getRaw('Metadata');
  8404. if (!isRef(streamRef)) {
  8405. return shadow(this, 'metadata', null);
  8406. }
  8407. var encryptMetadata = (!this.xref.encrypt ? false :
  8408. this.xref.encrypt.encryptMetadata);
  8409. var stream = this.xref.fetch(streamRef, !encryptMetadata);
  8410. var metadata;
  8411. if (stream && isDict(stream.dict)) {
  8412. var type = stream.dict.get('Type');
  8413. var subtype = stream.dict.get('Subtype');
  8414. if (isName(type) && isName(subtype) &&
  8415. type.name === 'Metadata' && subtype.name === 'XML') {
  8416. // XXX: This should examine the charset the XML document defines,
  8417. // however since there are currently no real means to decode
  8418. // arbitrary charsets, let's just hope that the author of the PDF
  8419. // was reasonable enough to stick with the XML default charset,
  8420. // which is UTF-8.
  8421. try {
  8422. metadata = stringToUTF8String(bytesToString(stream.getBytes()));
  8423. } catch (e) {
  8424. info('Skipping invalid metadata.');
  8425. }
  8426. }
  8427. }
  8428. return shadow(this, 'metadata', metadata);
  8429. },
  8430. get toplevelPagesDict() {
  8431. var pagesObj = this.catDict.get('Pages');
  8432. assert(isDict(pagesObj), 'invalid top-level pages dictionary');
  8433. // shadow the prototype getter
  8434. return shadow(this, 'toplevelPagesDict', pagesObj);
  8435. },
  8436. get documentOutline() {
  8437. var obj = null;
  8438. try {
  8439. obj = this.readDocumentOutline();
  8440. } catch (ex) {
  8441. if (ex instanceof MissingDataException) {
  8442. throw ex;
  8443. }
  8444. warn('Unable to read document outline');
  8445. }
  8446. return shadow(this, 'documentOutline', obj);
  8447. },
  8448. readDocumentOutline: function Catalog_readDocumentOutline() {
  8449. var xref = this.xref;
  8450. var obj = this.catDict.get('Outlines');
  8451. var root = { items: [] };
  8452. if (isDict(obj)) {
  8453. obj = obj.getRaw('First');
  8454. var processed = new RefSet();
  8455. if (isRef(obj)) {
  8456. var queue = [{obj: obj, parent: root}];
  8457. // to avoid recursion keeping track of the items
  8458. // in the processed dictionary
  8459. processed.put(obj);
  8460. while (queue.length > 0) {
  8461. var i = queue.shift();
  8462. var outlineDict = xref.fetchIfRef(i.obj);
  8463. if (outlineDict === null) {
  8464. continue;
  8465. }
  8466. if (!outlineDict.has('Title')) {
  8467. error('Invalid outline item');
  8468. }
  8469. var dest = outlineDict.get('A');
  8470. if (dest) {
  8471. dest = dest.get('D');
  8472. } else if (outlineDict.has('Dest')) {
  8473. dest = outlineDict.getRaw('Dest');
  8474. if (isName(dest)) {
  8475. dest = dest.name;
  8476. }
  8477. }
  8478. var title = outlineDict.get('Title');
  8479. var outlineItem = {
  8480. dest: dest,
  8481. title: stringToPDFString(title),
  8482. color: outlineDict.get('C') || [0, 0, 0],
  8483. count: outlineDict.get('Count'),
  8484. bold: !!(outlineDict.get('F') & 2),
  8485. italic: !!(outlineDict.get('F') & 1),
  8486. items: []
  8487. };
  8488. i.parent.items.push(outlineItem);
  8489. obj = outlineDict.getRaw('First');
  8490. if (isRef(obj) && !processed.has(obj)) {
  8491. queue.push({obj: obj, parent: outlineItem});
  8492. processed.put(obj);
  8493. }
  8494. obj = outlineDict.getRaw('Next');
  8495. if (isRef(obj) && !processed.has(obj)) {
  8496. queue.push({obj: obj, parent: i.parent});
  8497. processed.put(obj);
  8498. }
  8499. }
  8500. }
  8501. }
  8502. return (root.items.length > 0 ? root.items : null);
  8503. },
  8504. get numPages() {
  8505. var obj = this.toplevelPagesDict.get('Count');
  8506. assert(
  8507. isInt(obj),
  8508. 'page count in top level pages object is not an integer'
  8509. );
  8510. // shadow the prototype getter
  8511. return shadow(this, 'num', obj);
  8512. },
  8513. get destinations() {
  8514. function fetchDestination(dest) {
  8515. return isDict(dest) ? dest.get('D') : dest;
  8516. }
  8517. var xref = this.xref;
  8518. var dests = {}, nameTreeRef, nameDictionaryRef;
  8519. var obj = this.catDict.get('Names');
  8520. if (obj && obj.has('Dests')) {
  8521. nameTreeRef = obj.getRaw('Dests');
  8522. } else if (this.catDict.has('Dests')) {
  8523. nameDictionaryRef = this.catDict.get('Dests');
  8524. }
  8525. if (nameDictionaryRef) {
  8526. // reading simple destination dictionary
  8527. obj = nameDictionaryRef;
  8528. obj.forEach(function catalogForEach(key, value) {
  8529. if (!value) {
  8530. return;
  8531. }
  8532. dests[key] = fetchDestination(value);
  8533. });
  8534. }
  8535. if (nameTreeRef) {
  8536. var nameTree = new NameTree(nameTreeRef, xref);
  8537. var names = nameTree.getAll();
  8538. for (var name in names) {
  8539. if (!names.hasOwnProperty(name)) {
  8540. continue;
  8541. }
  8542. dests[name] = fetchDestination(names[name]);
  8543. }
  8544. }
  8545. return shadow(this, 'destinations', dests);
  8546. },
  8547. getDestination: function Catalog_getDestination(destinationId) {
  8548. function fetchDestination(dest) {
  8549. return isDict(dest) ? dest.get('D') : dest;
  8550. }
  8551. var xref = this.xref;
  8552. var dest, nameTreeRef, nameDictionaryRef;
  8553. var obj = this.catDict.get('Names');
  8554. if (obj && obj.has('Dests')) {
  8555. nameTreeRef = obj.getRaw('Dests');
  8556. } else if (this.catDict.has('Dests')) {
  8557. nameDictionaryRef = this.catDict.get('Dests');
  8558. }
  8559. if (nameDictionaryRef) {
  8560. // reading simple destination dictionary
  8561. obj = nameDictionaryRef;
  8562. obj.forEach(function catalogForEach(key, value) {
  8563. if (!value) {
  8564. return;
  8565. }
  8566. if (key === destinationId) {
  8567. dest = fetchDestination(value);
  8568. }
  8569. });
  8570. }
  8571. if (nameTreeRef) {
  8572. var nameTree = new NameTree(nameTreeRef, xref);
  8573. dest = fetchDestination(nameTree.get(destinationId));
  8574. }
  8575. return dest;
  8576. },
  8577. get attachments() {
  8578. var xref = this.xref;
  8579. var attachments = null, nameTreeRef;
  8580. var obj = this.catDict.get('Names');
  8581. if (obj) {
  8582. nameTreeRef = obj.getRaw('EmbeddedFiles');
  8583. }
  8584. if (nameTreeRef) {
  8585. var nameTree = new NameTree(nameTreeRef, xref);
  8586. var names = nameTree.getAll();
  8587. for (var name in names) {
  8588. if (!names.hasOwnProperty(name)) {
  8589. continue;
  8590. }
  8591. var fs = new FileSpec(names[name], xref);
  8592. if (!attachments) {
  8593. attachments = {};
  8594. }
  8595. attachments[stringToPDFString(name)] = fs.serializable;
  8596. }
  8597. }
  8598. return shadow(this, 'attachments', attachments);
  8599. },
  8600. get javaScript() {
  8601. var xref = this.xref;
  8602. var obj = this.catDict.get('Names');
  8603. var javaScript = [];
  8604. if (obj && obj.has('JavaScript')) {
  8605. var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);
  8606. var names = nameTree.getAll();
  8607. for (var name in names) {
  8608. if (!names.hasOwnProperty(name)) {
  8609. continue;
  8610. }
  8611. // We don't really use the JavaScript right now. This code is
  8612. // defensive so we don't cause errors on document load.
  8613. var jsDict = names[name];
  8614. if (!isDict(jsDict)) {
  8615. continue;
  8616. }
  8617. var type = jsDict.get('S');
  8618. if (!isName(type) || type.name !== 'JavaScript') {
  8619. continue;
  8620. }
  8621. var js = jsDict.get('JS');
  8622. if (!isString(js) && !isStream(js)) {
  8623. continue;
  8624. }
  8625. if (isStream(js)) {
  8626. js = bytesToString(js.getBytes());
  8627. }
  8628. javaScript.push(stringToPDFString(js));
  8629. }
  8630. }
  8631. // Append OpenAction actions to javaScript array
  8632. var openactionDict = this.catDict.get('OpenAction');
  8633. if (isDict(openactionDict)) {
  8634. var objType = openactionDict.get('Type');
  8635. var actionType = openactionDict.get('S');
  8636. var action = openactionDict.get('N');
  8637. var isPrintAction = (isName(objType) && objType.name === 'Action' &&
  8638. isName(actionType) && actionType.name === 'Named' &&
  8639. isName(action) && action.name === 'Print');
  8640. if (isPrintAction) {
  8641. javaScript.push('print(true);');
  8642. }
  8643. }
  8644. return shadow(this, 'javaScript', javaScript);
  8645. },
  8646. cleanup: function Catalog_cleanup() {
  8647. var promises = [];
  8648. this.fontCache.forEach(function (promise) {
  8649. promises.push(promise);
  8650. });
  8651. return Promise.all(promises).then(function (translatedFonts) {
  8652. for (var i = 0, ii = translatedFonts.length; i < ii; i++) {
  8653. var font = translatedFonts[i].dict;
  8654. delete font.translated;
  8655. }
  8656. this.fontCache.clear();
  8657. }.bind(this));
  8658. },
  8659. getPage: function Catalog_getPage(pageIndex) {
  8660. if (!(pageIndex in this.pagePromises)) {
  8661. this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(
  8662. function (a) {
  8663. var dict = a[0];
  8664. var ref = a[1];
  8665. return new Page(this.pdfManager, this.xref, pageIndex, dict, ref,
  8666. this.fontCache);
  8667. }.bind(this)
  8668. );
  8669. }
  8670. return this.pagePromises[pageIndex];
  8671. },
  8672. getPageDict: function Catalog_getPageDict(pageIndex) {
  8673. var capability = createPromiseCapability();
  8674. var nodesToVisit = [this.catDict.getRaw('Pages')];
  8675. var currentPageIndex = 0;
  8676. var xref = this.xref;
  8677. function next() {
  8678. while (nodesToVisit.length) {
  8679. var currentNode = nodesToVisit.pop();
  8680. if (isRef(currentNode)) {
  8681. xref.fetchAsync(currentNode).then(function (obj) {
  8682. if ((isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids')))) {
  8683. if (pageIndex === currentPageIndex) {
  8684. capability.resolve([obj, currentNode]);
  8685. } else {
  8686. currentPageIndex++;
  8687. next();
  8688. }
  8689. return;
  8690. }
  8691. nodesToVisit.push(obj);
  8692. next();
  8693. }, capability.reject);
  8694. return;
  8695. }
  8696. // must be a child page dictionary
  8697. assert(
  8698. isDict(currentNode),
  8699. 'page dictionary kid reference points to wrong type of object'
  8700. );
  8701. var count = currentNode.get('Count');
  8702. // Skip nodes where the page can't be.
  8703. if (currentPageIndex + count <= pageIndex) {
  8704. currentPageIndex += count;
  8705. continue;
  8706. }
  8707. var kids = currentNode.get('Kids');
  8708. assert(isArray(kids), 'page dictionary kids object is not an array');
  8709. if (count === kids.length) {
  8710. // Nodes that don't have the page have been skipped and this is the
  8711. // bottom of the tree which means the page requested must be a
  8712. // descendant of this pages node. Ideally we would just resolve the
  8713. // promise with the page ref here, but there is the case where more
  8714. // pages nodes could link to single a page (see issue 3666 pdf). To
  8715. // handle this push it back on the queue so if it is a pages node it
  8716. // will be descended into.
  8717. nodesToVisit = [kids[pageIndex - currentPageIndex]];
  8718. currentPageIndex = pageIndex;
  8719. continue;
  8720. } else {
  8721. for (var last = kids.length - 1; last >= 0; last--) {
  8722. nodesToVisit.push(kids[last]);
  8723. }
  8724. }
  8725. }
  8726. capability.reject('Page index ' + pageIndex + ' not found.');
  8727. }
  8728. next();
  8729. return capability.promise;
  8730. },
  8731. getPageIndex: function Catalog_getPageIndex(ref) {
  8732. // The page tree nodes have the count of all the leaves below them. To get
  8733. // how many pages are before we just have to walk up the tree and keep
  8734. // adding the count of siblings to the left of the node.
  8735. var xref = this.xref;
  8736. function pagesBeforeRef(kidRef) {
  8737. var total = 0;
  8738. var parentRef;
  8739. return xref.fetchAsync(kidRef).then(function (node) {
  8740. if (!node) {
  8741. return null;
  8742. }
  8743. parentRef = node.getRaw('Parent');
  8744. return node.getAsync('Parent');
  8745. }).then(function (parent) {
  8746. if (!parent) {
  8747. return null;
  8748. }
  8749. return parent.getAsync('Kids');
  8750. }).then(function (kids) {
  8751. if (!kids) {
  8752. return null;
  8753. }
  8754. var kidPromises = [];
  8755. var found = false;
  8756. for (var i = 0; i < kids.length; i++) {
  8757. var kid = kids[i];
  8758. assert(isRef(kid), 'kids must be a ref');
  8759. if (kid.num === kidRef.num) {
  8760. found = true;
  8761. break;
  8762. }
  8763. kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
  8764. if (kid.has('Count')) {
  8765. var count = kid.get('Count');
  8766. total += count;
  8767. } else { // page leaf node
  8768. total++;
  8769. }
  8770. }));
  8771. }
  8772. if (!found) {
  8773. error('kid ref not found in parents kids');
  8774. }
  8775. return Promise.all(kidPromises).then(function () {
  8776. return [total, parentRef];
  8777. });
  8778. });
  8779. }
  8780. var total = 0;
  8781. function next(ref) {
  8782. return pagesBeforeRef(ref).then(function (args) {
  8783. if (!args) {
  8784. return total;
  8785. }
  8786. var count = args[0];
  8787. var parentRef = args[1];
  8788. total += count;
  8789. return next(parentRef);
  8790. });
  8791. }
  8792. return next(ref);
  8793. }
  8794. };
  8795. return Catalog;
  8796. })();
  8797. var XRef = (function XRefClosure() {
  8798. function XRef(stream, password) {
  8799. this.stream = stream;
  8800. this.entries = [];
  8801. this.xrefstms = {};
  8802. // prepare the XRef cache
  8803. this.cache = [];
  8804. this.password = password;
  8805. this.stats = {
  8806. streamTypes: [],
  8807. fontTypes: []
  8808. };
  8809. }
  8810. XRef.prototype = {
  8811. setStartXRef: function XRef_setStartXRef(startXRef) {
  8812. // Store the starting positions of xref tables as we process them
  8813. // so we can recover from missing data errors
  8814. this.startXRefQueue = [startXRef];
  8815. },
  8816. parse: function XRef_parse(recoveryMode) {
  8817. var trailerDict;
  8818. if (!recoveryMode) {
  8819. trailerDict = this.readXRef();
  8820. } else {
  8821. warn('Indexing all PDF objects');
  8822. trailerDict = this.indexObjects();
  8823. }
  8824. trailerDict.assignXref(this);
  8825. this.trailer = trailerDict;
  8826. var encrypt = trailerDict.get('Encrypt');
  8827. if (encrypt) {
  8828. var ids = trailerDict.get('ID');
  8829. var fileId = (ids && ids.length) ? ids[0] : '';
  8830. this.encrypt = new CipherTransformFactory(encrypt, fileId,
  8831. this.password);
  8832. }
  8833. // get the root dictionary (catalog) object
  8834. if (!(this.root = trailerDict.get('Root'))) {
  8835. error('Invalid root reference');
  8836. }
  8837. },
  8838. processXRefTable: function XRef_processXRefTable(parser) {
  8839. if (!('tableState' in this)) {
  8840. // Stores state of the table as we process it so we can resume
  8841. // from middle of table in case of missing data error
  8842. this.tableState = {
  8843. entryNum: 0,
  8844. streamPos: parser.lexer.stream.pos,
  8845. parserBuf1: parser.buf1,
  8846. parserBuf2: parser.buf2
  8847. };
  8848. }
  8849. var obj = this.readXRefTable(parser);
  8850. // Sanity check
  8851. if (!isCmd(obj, 'trailer')) {
  8852. error('Invalid XRef table: could not find trailer dictionary');
  8853. }
  8854. // Read trailer dictionary, e.g.
  8855. // trailer
  8856. // << /Size 22
  8857. // /Root 20R
  8858. // /Info 10R
  8859. // /ID [ <81b14aafa313db63dbd6f981e49f94f4> ]
  8860. // >>
  8861. // The parser goes through the entire stream << ... >> and provides
  8862. // a getter interface for the key-value table
  8863. var dict = parser.getObj();
  8864. // The pdflib PDF generator can generate a nested trailer dictionary
  8865. if (!isDict(dict) && dict.dict) {
  8866. dict = dict.dict;
  8867. }
  8868. if (!isDict(dict)) {
  8869. error('Invalid XRef table: could not parse trailer dictionary');
  8870. }
  8871. delete this.tableState;
  8872. return dict;
  8873. },
  8874. readXRefTable: function XRef_readXRefTable(parser) {
  8875. // Example of cross-reference table:
  8876. // xref
  8877. // 0 1 <-- subsection header (first obj #, obj count)
  8878. // 0000000000 65535 f <-- actual object (offset, generation #, f/n)
  8879. // 23 2 <-- subsection header ... and so on ...
  8880. // 0000025518 00002 n
  8881. // 0000025635 00000 n
  8882. // trailer
  8883. // ...
  8884. var stream = parser.lexer.stream;
  8885. var tableState = this.tableState;
  8886. stream.pos = tableState.streamPos;
  8887. parser.buf1 = tableState.parserBuf1;
  8888. parser.buf2 = tableState.parserBuf2;
  8889. // Outer loop is over subsection headers
  8890. var obj;
  8891. while (true) {
  8892. if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {
  8893. if (isCmd(obj = parser.getObj(), 'trailer')) {
  8894. break;
  8895. }
  8896. tableState.firstEntryNum = obj;
  8897. tableState.entryCount = parser.getObj();
  8898. }
  8899. var first = tableState.firstEntryNum;
  8900. var count = tableState.entryCount;
  8901. if (!isInt(first) || !isInt(count)) {
  8902. error('Invalid XRef table: wrong types in subsection header');
  8903. }
  8904. // Inner loop is over objects themselves
  8905. for (var i = tableState.entryNum; i < count; i++) {
  8906. tableState.streamPos = stream.pos;
  8907. tableState.entryNum = i;
  8908. tableState.parserBuf1 = parser.buf1;
  8909. tableState.parserBuf2 = parser.buf2;
  8910. var entry = {};
  8911. entry.offset = parser.getObj();
  8912. entry.gen = parser.getObj();
  8913. var type = parser.getObj();
  8914. if (isCmd(type, 'f')) {
  8915. entry.free = true;
  8916. } else if (isCmd(type, 'n')) {
  8917. entry.uncompressed = true;
  8918. }
  8919. // Validate entry obj
  8920. if (!isInt(entry.offset) || !isInt(entry.gen) ||
  8921. !(entry.free || entry.uncompressed)) {
  8922. error('Invalid entry in XRef subsection: ' + first + ', ' + count);
  8923. }
  8924. if (!this.entries[i + first]) {
  8925. this.entries[i + first] = entry;
  8926. }
  8927. }
  8928. tableState.entryNum = 0;
  8929. tableState.streamPos = stream.pos;
  8930. tableState.parserBuf1 = parser.buf1;
  8931. tableState.parserBuf2 = parser.buf2;
  8932. delete tableState.firstEntryNum;
  8933. delete tableState.entryCount;
  8934. }
  8935. // Per issue 3248: hp scanners generate bad XRef
  8936. if (first === 1 && this.entries[1] && this.entries[1].free) {
  8937. // shifting the entries
  8938. this.entries.shift();
  8939. }
  8940. // Sanity check: as per spec, first object must be free
  8941. if (this.entries[0] && !this.entries[0].free) {
  8942. error('Invalid XRef table: unexpected first object');
  8943. }
  8944. return obj;
  8945. },
  8946. processXRefStream: function XRef_processXRefStream(stream) {
  8947. if (!('streamState' in this)) {
  8948. // Stores state of the stream as we process it so we can resume
  8949. // from middle of stream in case of missing data error
  8950. var streamParameters = stream.dict;
  8951. var byteWidths = streamParameters.get('W');
  8952. var range = streamParameters.get('Index');
  8953. if (!range) {
  8954. range = [0, streamParameters.get('Size')];
  8955. }
  8956. this.streamState = {
  8957. entryRanges: range,
  8958. byteWidths: byteWidths,
  8959. entryNum: 0,
  8960. streamPos: stream.pos
  8961. };
  8962. }
  8963. this.readXRefStream(stream);
  8964. delete this.streamState;
  8965. return stream.dict;
  8966. },
  8967. readXRefStream: function XRef_readXRefStream(stream) {
  8968. var i, j;
  8969. var streamState = this.streamState;
  8970. stream.pos = streamState.streamPos;
  8971. var byteWidths = streamState.byteWidths;
  8972. var typeFieldWidth = byteWidths[0];
  8973. var offsetFieldWidth = byteWidths[1];
  8974. var generationFieldWidth = byteWidths[2];
  8975. var entryRanges = streamState.entryRanges;
  8976. while (entryRanges.length > 0) {
  8977. var first = entryRanges[0];
  8978. var n = entryRanges[1];
  8979. if (!isInt(first) || !isInt(n)) {
  8980. error('Invalid XRef range fields: ' + first + ', ' + n);
  8981. }
  8982. if (!isInt(typeFieldWidth) || !isInt(offsetFieldWidth) ||
  8983. !isInt(generationFieldWidth)) {
  8984. error('Invalid XRef entry fields length: ' + first + ', ' + n);
  8985. }
  8986. for (i = streamState.entryNum; i < n; ++i) {
  8987. streamState.entryNum = i;
  8988. streamState.streamPos = stream.pos;
  8989. var type = 0, offset = 0, generation = 0;
  8990. for (j = 0; j < typeFieldWidth; ++j) {
  8991. type = (type << 8) | stream.getByte();
  8992. }
  8993. // if type field is absent, its default value is 1
  8994. if (typeFieldWidth === 0) {
  8995. type = 1;
  8996. }
  8997. for (j = 0; j < offsetFieldWidth; ++j) {
  8998. offset = (offset << 8) | stream.getByte();
  8999. }
  9000. for (j = 0; j < generationFieldWidth; ++j) {
  9001. generation = (generation << 8) | stream.getByte();
  9002. }
  9003. var entry = {};
  9004. entry.offset = offset;
  9005. entry.gen = generation;
  9006. switch (type) {
  9007. case 0:
  9008. entry.free = true;
  9009. break;
  9010. case 1:
  9011. entry.uncompressed = true;
  9012. break;
  9013. case 2:
  9014. break;
  9015. default:
  9016. error('Invalid XRef entry type: ' + type);
  9017. }
  9018. if (!this.entries[first + i]) {
  9019. this.entries[first + i] = entry;
  9020. }
  9021. }
  9022. streamState.entryNum = 0;
  9023. streamState.streamPos = stream.pos;
  9024. entryRanges.splice(0, 2);
  9025. }
  9026. },
  9027. indexObjects: function XRef_indexObjects() {
  9028. // Simple scan through the PDF content to find objects,
  9029. // trailers and XRef streams.
  9030. function readToken(data, offset) {
  9031. var token = '', ch = data[offset];
  9032. while (ch !== 13 && ch !== 10) {
  9033. if (++offset >= data.length) {
  9034. break;
  9035. }
  9036. token += String.fromCharCode(ch);
  9037. ch = data[offset];
  9038. }
  9039. return token;
  9040. }
  9041. function skipUntil(data, offset, what) {
  9042. var length = what.length, dataLength = data.length;
  9043. var skipped = 0;
  9044. // finding byte sequence
  9045. while (offset < dataLength) {
  9046. var i = 0;
  9047. while (i < length && data[offset + i] === what[i]) {
  9048. ++i;
  9049. }
  9050. if (i >= length) {
  9051. break; // sequence found
  9052. }
  9053. offset++;
  9054. skipped++;
  9055. }
  9056. return skipped;
  9057. }
  9058. var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
  9059. var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114,
  9060. 101, 102]);
  9061. var endobjBytes = new Uint8Array([101, 110, 100, 111, 98, 106]);
  9062. var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
  9063. var stream = this.stream;
  9064. stream.pos = 0;
  9065. var buffer = stream.getBytes();
  9066. var position = stream.start, length = buffer.length;
  9067. var trailers = [], xrefStms = [];
  9068. while (position < length) {
  9069. var ch = buffer[position];
  9070. if (ch === 32 || ch === 9 || ch === 13 || ch === 10) {
  9071. ++position;
  9072. continue;
  9073. }
  9074. if (ch === 37) { // %-comment
  9075. do {
  9076. ++position;
  9077. if (position >= length) {
  9078. break;
  9079. }
  9080. ch = buffer[position];
  9081. } while (ch !== 13 && ch !== 10);
  9082. continue;
  9083. }
  9084. var token = readToken(buffer, position);
  9085. var m;
  9086. if (token === 'xref') {
  9087. position += skipUntil(buffer, position, trailerBytes);
  9088. trailers.push(position);
  9089. position += skipUntil(buffer, position, startxrefBytes);
  9090. } else if ((m = /^(\d+)\s+(\d+)\s+obj\b/.exec(token))) {
  9091. this.entries[m[1]] = {
  9092. offset: position,
  9093. gen: m[2] | 0,
  9094. uncompressed: true
  9095. };
  9096. var contentLength = skipUntil(buffer, position, endobjBytes) + 7;
  9097. var content = buffer.subarray(position, position + contentLength);
  9098. // checking XRef stream suspect
  9099. // (it shall have '/XRef' and next char is not a letter)
  9100. var xrefTagOffset = skipUntil(content, 0, xrefBytes);
  9101. if (xrefTagOffset < contentLength &&
  9102. content[xrefTagOffset + 5] < 64) {
  9103. xrefStms.push(position);
  9104. this.xrefstms[position] = 1; // don't read it recursively
  9105. }
  9106. position += contentLength;
  9107. } else {
  9108. position += token.length + 1;
  9109. }
  9110. }
  9111. // reading XRef streams
  9112. var i, ii;
  9113. for (i = 0, ii = xrefStms.length; i < ii; ++i) {
  9114. this.startXRefQueue.push(xrefStms[i]);
  9115. this.readXRef(/* recoveryMode */ true);
  9116. }
  9117. // finding main trailer
  9118. var dict;
  9119. for (i = 0, ii = trailers.length; i < ii; ++i) {
  9120. stream.pos = trailers[i];
  9121. var parser = new Parser(new Lexer(stream), true, this);
  9122. var obj = parser.getObj();
  9123. if (!isCmd(obj, 'trailer')) {
  9124. continue;
  9125. }
  9126. // read the trailer dictionary
  9127. if (!isDict(dict = parser.getObj())) {
  9128. continue;
  9129. }
  9130. // taking the first one with 'ID'
  9131. if (dict.has('ID')) {
  9132. return dict;
  9133. }
  9134. }
  9135. // no tailer with 'ID', taking last one (if exists)
  9136. if (dict) {
  9137. return dict;
  9138. }
  9139. // nothing helps
  9140. // calling error() would reject worker with an UnknownErrorException.
  9141. throw new InvalidPDFException('Invalid PDF structure');
  9142. },
  9143. readXRef: function XRef_readXRef(recoveryMode) {
  9144. var stream = this.stream;
  9145. try {
  9146. while (this.startXRefQueue.length) {
  9147. var startXRef = this.startXRefQueue[0];
  9148. stream.pos = startXRef + stream.start;
  9149. var parser = new Parser(new Lexer(stream), true, this);
  9150. var obj = parser.getObj();
  9151. var dict;
  9152. // Get dictionary
  9153. if (isCmd(obj, 'xref')) {
  9154. // Parse end-of-file XRef
  9155. dict = this.processXRefTable(parser);
  9156. if (!this.topDict) {
  9157. this.topDict = dict;
  9158. }
  9159. // Recursively get other XRefs 'XRefStm', if any
  9160. obj = dict.get('XRefStm');
  9161. if (isInt(obj)) {
  9162. var pos = obj;
  9163. // ignore previously loaded xref streams
  9164. // (possible infinite recursion)
  9165. if (!(pos in this.xrefstms)) {
  9166. this.xrefstms[pos] = 1;
  9167. this.startXRefQueue.push(pos);
  9168. }
  9169. }
  9170. } else if (isInt(obj)) {
  9171. // Parse in-stream XRef
  9172. if (!isInt(parser.getObj()) ||
  9173. !isCmd(parser.getObj(), 'obj') ||
  9174. !isStream(obj = parser.getObj())) {
  9175. error('Invalid XRef stream');
  9176. }
  9177. dict = this.processXRefStream(obj);
  9178. if (!this.topDict) {
  9179. this.topDict = dict;
  9180. }
  9181. if (!dict) {
  9182. error('Failed to read XRef stream');
  9183. }
  9184. } else {
  9185. error('Invalid XRef stream header');
  9186. }
  9187. // Recursively get previous dictionary, if any
  9188. obj = dict.get('Prev');
  9189. if (isInt(obj)) {
  9190. this.startXRefQueue.push(obj);
  9191. } else if (isRef(obj)) {
  9192. // The spec says Prev must not be a reference, i.e. "/Prev NNN"
  9193. // This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R"
  9194. this.startXRefQueue.push(obj.num);
  9195. }
  9196. this.startXRefQueue.shift();
  9197. }
  9198. return this.topDict;
  9199. } catch (e) {
  9200. if (e instanceof MissingDataException) {
  9201. throw e;
  9202. }
  9203. info('(while reading XRef): ' + e);
  9204. }
  9205. if (recoveryMode) {
  9206. return;
  9207. }
  9208. throw new XRefParseException();
  9209. },
  9210. getEntry: function XRef_getEntry(i) {
  9211. var xrefEntry = this.entries[i];
  9212. if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
  9213. return xrefEntry;
  9214. }
  9215. return null;
  9216. },
  9217. fetchIfRef: function XRef_fetchIfRef(obj) {
  9218. if (!isRef(obj)) {
  9219. return obj;
  9220. }
  9221. return this.fetch(obj);
  9222. },
  9223. fetch: function XRef_fetch(ref, suppressEncryption) {
  9224. assert(isRef(ref), 'ref object is not a reference');
  9225. var num = ref.num;
  9226. if (num in this.cache) {
  9227. var cacheEntry = this.cache[num];
  9228. return cacheEntry;
  9229. }
  9230. var xrefEntry = this.getEntry(num);
  9231. // the referenced entry can be free
  9232. if (xrefEntry === null) {
  9233. return (this.cache[num] = null);
  9234. }
  9235. if (xrefEntry.uncompressed) {
  9236. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  9237. } else {
  9238. xrefEntry = this.fetchCompressed(xrefEntry, suppressEncryption);
  9239. }
  9240. if (isDict(xrefEntry)){
  9241. xrefEntry.objId = ref.toString();
  9242. } else if (isStream(xrefEntry)) {
  9243. xrefEntry.dict.objId = ref.toString();
  9244. }
  9245. return xrefEntry;
  9246. },
  9247. fetchUncompressed: function XRef_fetchUncompressed(ref, xrefEntry,
  9248. suppressEncryption) {
  9249. var gen = ref.gen;
  9250. var num = ref.num;
  9251. if (xrefEntry.gen !== gen) {
  9252. error('inconsistent generation in XRef');
  9253. }
  9254. var stream = this.stream.makeSubStream(xrefEntry.offset +
  9255. this.stream.start);
  9256. var parser = new Parser(new Lexer(stream), true, this);
  9257. var obj1 = parser.getObj();
  9258. var obj2 = parser.getObj();
  9259. var obj3 = parser.getObj();
  9260. if (!isInt(obj1) || parseInt(obj1, 10) !== num ||
  9261. !isInt(obj2) || parseInt(obj2, 10) !== gen ||
  9262. !isCmd(obj3)) {
  9263. error('bad XRef entry');
  9264. }
  9265. if (!isCmd(obj3, 'obj')) {
  9266. // some bad PDFs use "obj1234" and really mean 1234
  9267. if (obj3.cmd.indexOf('obj') === 0) {
  9268. num = parseInt(obj3.cmd.substring(3), 10);
  9269. if (!isNaN(num)) {
  9270. return num;
  9271. }
  9272. }
  9273. error('bad XRef entry');
  9274. }
  9275. if (this.encrypt && !suppressEncryption) {
  9276. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  9277. } else {
  9278. xrefEntry = parser.getObj();
  9279. }
  9280. if (!isStream(xrefEntry)) {
  9281. this.cache[num] = xrefEntry;
  9282. }
  9283. return xrefEntry;
  9284. },
  9285. fetchCompressed: function XRef_fetchCompressed(xrefEntry,
  9286. suppressEncryption) {
  9287. var tableOffset = xrefEntry.offset;
  9288. var stream = this.fetch(new Ref(tableOffset, 0));
  9289. if (!isStream(stream)) {
  9290. error('bad ObjStm stream');
  9291. }
  9292. var first = stream.dict.get('First');
  9293. var n = stream.dict.get('N');
  9294. if (!isInt(first) || !isInt(n)) {
  9295. error('invalid first and n parameters for ObjStm stream');
  9296. }
  9297. var parser = new Parser(new Lexer(stream), false, this);
  9298. parser.allowStreams = true;
  9299. var i, entries = [], num, nums = [];
  9300. // read the object numbers to populate cache
  9301. for (i = 0; i < n; ++i) {
  9302. num = parser.getObj();
  9303. if (!isInt(num)) {
  9304. error('invalid object number in the ObjStm stream: ' + num);
  9305. }
  9306. nums.push(num);
  9307. var offset = parser.getObj();
  9308. if (!isInt(offset)) {
  9309. error('invalid object offset in the ObjStm stream: ' + offset);
  9310. }
  9311. }
  9312. // read stream objects for cache
  9313. for (i = 0; i < n; ++i) {
  9314. entries.push(parser.getObj());
  9315. num = nums[i];
  9316. var entry = this.entries[num];
  9317. if (entry && entry.offset === tableOffset && entry.gen === i) {
  9318. this.cache[num] = entries[i];
  9319. }
  9320. }
  9321. xrefEntry = entries[xrefEntry.gen];
  9322. if (xrefEntry === undefined) {
  9323. error('bad XRef entry for compressed object');
  9324. }
  9325. return xrefEntry;
  9326. },
  9327. fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) {
  9328. if (!isRef(obj)) {
  9329. return Promise.resolve(obj);
  9330. }
  9331. return this.fetchAsync(obj);
  9332. },
  9333. fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
  9334. var streamManager = this.stream.manager;
  9335. var xref = this;
  9336. return new Promise(function tryFetch(resolve, reject) {
  9337. try {
  9338. resolve(xref.fetch(ref, suppressEncryption));
  9339. } catch (e) {
  9340. if (e instanceof MissingDataException) {
  9341. streamManager.requestRange(e.begin, e.end, function () {
  9342. tryFetch(resolve, reject);
  9343. });
  9344. return;
  9345. }
  9346. reject(e);
  9347. }
  9348. });
  9349. },
  9350. getCatalogObj: function XRef_getCatalogObj() {
  9351. return this.root;
  9352. }
  9353. };
  9354. return XRef;
  9355. })();
  9356. /**
  9357. * A NameTree is like a Dict but has some advantageous properties, see the
  9358. * spec (7.9.6) for more details.
  9359. * TODO: implement all the Dict functions and make this more efficent.
  9360. */
  9361. var NameTree = (function NameTreeClosure() {
  9362. function NameTree(root, xref) {
  9363. this.root = root;
  9364. this.xref = xref;
  9365. }
  9366. NameTree.prototype = {
  9367. getAll: function NameTree_getAll() {
  9368. var dict = {};
  9369. if (!this.root) {
  9370. return dict;
  9371. }
  9372. var xref = this.xref;
  9373. // reading name tree
  9374. var processed = new RefSet();
  9375. processed.put(this.root);
  9376. var queue = [this.root];
  9377. while (queue.length > 0) {
  9378. var i, n;
  9379. var obj = xref.fetchIfRef(queue.shift());
  9380. if (!isDict(obj)) {
  9381. continue;
  9382. }
  9383. if (obj.has('Kids')) {
  9384. var kids = obj.get('Kids');
  9385. for (i = 0, n = kids.length; i < n; i++) {
  9386. var kid = kids[i];
  9387. if (processed.has(kid)) {
  9388. error('invalid destinations');
  9389. }
  9390. queue.push(kid);
  9391. processed.put(kid);
  9392. }
  9393. continue;
  9394. }
  9395. var names = obj.get('Names');
  9396. if (names) {
  9397. for (i = 0, n = names.length; i < n; i += 2) {
  9398. dict[names[i]] = xref.fetchIfRef(names[i + 1]);
  9399. }
  9400. }
  9401. }
  9402. return dict;
  9403. },
  9404. get: function NameTree_get(destinationId) {
  9405. if (!this.root) {
  9406. return null;
  9407. }
  9408. var xref = this.xref;
  9409. var kidsOrNames = xref.fetchIfRef(this.root);
  9410. var loopCount = 0;
  9411. var MAX_NAMES_LEVELS = 10;
  9412. var l, r, m;
  9413. // Perform a binary search to quickly find the entry that
  9414. // contains the named destination we are looking for.
  9415. while (kidsOrNames.has('Kids')) {
  9416. loopCount++;
  9417. if (loopCount > MAX_NAMES_LEVELS) {
  9418. warn('Search depth limit for named destionations has been reached.');
  9419. return null;
  9420. }
  9421. var kids = kidsOrNames.get('Kids');
  9422. if (!isArray(kids)) {
  9423. return null;
  9424. }
  9425. l = 0;
  9426. r = kids.length - 1;
  9427. while (l <= r) {
  9428. m = (l + r) >> 1;
  9429. var kid = xref.fetchIfRef(kids[m]);
  9430. var limits = kid.get('Limits');
  9431. if (destinationId < limits[0]) {
  9432. r = m - 1;
  9433. } else if (destinationId > limits[1]) {
  9434. l = m + 1;
  9435. } else {
  9436. kidsOrNames = xref.fetchIfRef(kids[m]);
  9437. break;
  9438. }
  9439. }
  9440. if (l > r) {
  9441. return null;
  9442. }
  9443. }
  9444. // If we get here, then we have found the right entry. Now
  9445. // go through the named destinations in the Named dictionary
  9446. // until we find the exact destination we're looking for.
  9447. var names = kidsOrNames.get('Names');
  9448. if (isArray(names)) {
  9449. // Perform a binary search to reduce the lookup time.
  9450. l = 0;
  9451. r = names.length - 2;
  9452. while (l <= r) {
  9453. // Check only even indices (0, 2, 4, ...) because the
  9454. // odd indices contain the actual D array.
  9455. m = (l + r) & ~1;
  9456. if (destinationId < names[m]) {
  9457. r = m - 2;
  9458. } else if (destinationId > names[m]) {
  9459. l = m + 2;
  9460. } else {
  9461. return xref.fetchIfRef(names[m + 1]);
  9462. }
  9463. }
  9464. }
  9465. return null;
  9466. }
  9467. };
  9468. return NameTree;
  9469. })();
  9470. /**
  9471. * "A PDF file can refer to the contents of another file by using a File
  9472. * Specification (PDF 1.1)", see the spec (7.11) for more details.
  9473. * NOTE: Only embedded files are supported (as part of the attachments support)
  9474. * TODO: support the 'URL' file system (with caching if !/V), portable
  9475. * collections attributes and related files (/RF)
  9476. */
  9477. var FileSpec = (function FileSpecClosure() {
  9478. function FileSpec(root, xref) {
  9479. if (!root || !isDict(root)) {
  9480. return;
  9481. }
  9482. this.xref = xref;
  9483. this.root = root;
  9484. if (root.has('FS')) {
  9485. this.fs = root.get('FS');
  9486. }
  9487. this.description = root.has('Desc') ?
  9488. stringToPDFString(root.get('Desc')) :
  9489. '';
  9490. if (root.has('RF')) {
  9491. warn('Related file specifications are not supported');
  9492. }
  9493. this.contentAvailable = true;
  9494. if (!root.has('EF')) {
  9495. this.contentAvailable = false;
  9496. warn('Non-embedded file specifications are not supported');
  9497. }
  9498. }
  9499. function pickPlatformItem(dict) {
  9500. // Look for the filename in this order:
  9501. // UF, F, Unix, Mac, DOS
  9502. if (dict.has('UF')) {
  9503. return dict.get('UF');
  9504. } else if (dict.has('F')) {
  9505. return dict.get('F');
  9506. } else if (dict.has('Unix')) {
  9507. return dict.get('Unix');
  9508. } else if (dict.has('Mac')) {
  9509. return dict.get('Mac');
  9510. } else if (dict.has('DOS')) {
  9511. return dict.get('DOS');
  9512. } else {
  9513. return null;
  9514. }
  9515. }
  9516. FileSpec.prototype = {
  9517. get filename() {
  9518. if (!this._filename && this.root) {
  9519. var filename = pickPlatformItem(this.root) || 'unnamed';
  9520. this._filename = stringToPDFString(filename).
  9521. replace(/\\\\/g, '\\').
  9522. replace(/\\\//g, '/').
  9523. replace(/\\/g, '/');
  9524. }
  9525. return this._filename;
  9526. },
  9527. get content() {
  9528. if (!this.contentAvailable) {
  9529. return null;
  9530. }
  9531. if (!this.contentRef && this.root) {
  9532. this.contentRef = pickPlatformItem(this.root.get('EF'));
  9533. }
  9534. var content = null;
  9535. if (this.contentRef) {
  9536. var xref = this.xref;
  9537. var fileObj = xref.fetchIfRef(this.contentRef);
  9538. if (fileObj && isStream(fileObj)) {
  9539. content = fileObj.getBytes();
  9540. } else {
  9541. warn('Embedded file specification points to non-existing/invalid ' +
  9542. 'content');
  9543. }
  9544. } else {
  9545. warn('Embedded file specification does not have a content');
  9546. }
  9547. return content;
  9548. },
  9549. get serializable() {
  9550. return {
  9551. filename: this.filename,
  9552. content: this.content
  9553. };
  9554. }
  9555. };
  9556. return FileSpec;
  9557. })();
  9558. /**
  9559. * A helper for loading missing data in object graphs. It traverses the graph
  9560. * depth first and queues up any objects that have missing data. Once it has
  9561. * has traversed as many objects that are available it attempts to bundle the
  9562. * missing data requests and then resume from the nodes that weren't ready.
  9563. *
  9564. * NOTE: It provides protection from circular references by keeping track of
  9565. * of loaded references. However, you must be careful not to load any graphs
  9566. * that have references to the catalog or other pages since that will cause the
  9567. * entire PDF document object graph to be traversed.
  9568. */
  9569. var ObjectLoader = (function() {
  9570. function mayHaveChildren(value) {
  9571. return isRef(value) || isDict(value) || isArray(value) || isStream(value);
  9572. }
  9573. function addChildren(node, nodesToVisit) {
  9574. var value;
  9575. if (isDict(node) || isStream(node)) {
  9576. var map;
  9577. if (isDict(node)) {
  9578. map = node.map;
  9579. } else {
  9580. map = node.dict.map;
  9581. }
  9582. for (var key in map) {
  9583. value = map[key];
  9584. if (mayHaveChildren(value)) {
  9585. nodesToVisit.push(value);
  9586. }
  9587. }
  9588. } else if (isArray(node)) {
  9589. for (var i = 0, ii = node.length; i < ii; i++) {
  9590. value = node[i];
  9591. if (mayHaveChildren(value)) {
  9592. nodesToVisit.push(value);
  9593. }
  9594. }
  9595. }
  9596. }
  9597. function ObjectLoader(obj, keys, xref) {
  9598. this.obj = obj;
  9599. this.keys = keys;
  9600. this.xref = xref;
  9601. this.refSet = null;
  9602. }
  9603. ObjectLoader.prototype = {
  9604. load: function ObjectLoader_load() {
  9605. var keys = this.keys;
  9606. this.capability = createPromiseCapability();
  9607. // Don't walk the graph if all the data is already loaded.
  9608. if (!(this.xref.stream instanceof ChunkedStream) ||
  9609. this.xref.stream.getMissingChunks().length === 0) {
  9610. this.capability.resolve();
  9611. return this.capability.promise;
  9612. }
  9613. this.refSet = new RefSet();
  9614. // Setup the initial nodes to visit.
  9615. var nodesToVisit = [];
  9616. for (var i = 0; i < keys.length; i++) {
  9617. nodesToVisit.push(this.obj[keys[i]]);
  9618. }
  9619. this.walk(nodesToVisit);
  9620. return this.capability.promise;
  9621. },
  9622. walk: function ObjectLoader_walk(nodesToVisit) {
  9623. var nodesToRevisit = [];
  9624. var pendingRequests = [];
  9625. // DFS walk of the object graph.
  9626. while (nodesToVisit.length) {
  9627. var currentNode = nodesToVisit.pop();
  9628. // Only references or chunked streams can cause missing data exceptions.
  9629. if (isRef(currentNode)) {
  9630. // Skip nodes that have already been visited.
  9631. if (this.refSet.has(currentNode)) {
  9632. continue;
  9633. }
  9634. try {
  9635. var ref = currentNode;
  9636. this.refSet.put(ref);
  9637. currentNode = this.xref.fetch(currentNode);
  9638. } catch (e) {
  9639. if (!(e instanceof MissingDataException)) {
  9640. throw e;
  9641. }
  9642. nodesToRevisit.push(currentNode);
  9643. pendingRequests.push({ begin: e.begin, end: e.end });
  9644. }
  9645. }
  9646. if (currentNode && currentNode.getBaseStreams) {
  9647. var baseStreams = currentNode.getBaseStreams();
  9648. var foundMissingData = false;
  9649. for (var i = 0; i < baseStreams.length; i++) {
  9650. var stream = baseStreams[i];
  9651. if (stream.getMissingChunks && stream.getMissingChunks().length) {
  9652. foundMissingData = true;
  9653. pendingRequests.push({
  9654. begin: stream.start,
  9655. end: stream.end
  9656. });
  9657. }
  9658. }
  9659. if (foundMissingData) {
  9660. nodesToRevisit.push(currentNode);
  9661. }
  9662. }
  9663. addChildren(currentNode, nodesToVisit);
  9664. }
  9665. if (pendingRequests.length) {
  9666. this.xref.stream.manager.requestRanges(pendingRequests,
  9667. function pendingRequestCallback() {
  9668. nodesToVisit = nodesToRevisit;
  9669. for (var i = 0; i < nodesToRevisit.length; i++) {
  9670. var node = nodesToRevisit[i];
  9671. // Remove any reference nodes from the currrent refset so they
  9672. // aren't skipped when we revist them.
  9673. if (isRef(node)) {
  9674. this.refSet.remove(node);
  9675. }
  9676. }
  9677. this.walk(nodesToVisit);
  9678. }.bind(this));
  9679. return;
  9680. }
  9681. // Everything is loaded.
  9682. this.refSet = null;
  9683. this.capability.resolve();
  9684. }
  9685. };
  9686. return ObjectLoader;
  9687. })();
  9688. var ISOAdobeCharset = [
  9689. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar',
  9690. 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright',
  9691. 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero',
  9692. 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
  9693. 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question',
  9694. 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  9695. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  9696. 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
  9697. 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  9698. 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  9699. 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
  9700. 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  9701. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  9702. 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
  9703. 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase',
  9704. 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
  9705. 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde',
  9706. 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla',
  9707. 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine',
  9708. 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash',
  9709. 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu',
  9710. 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter',
  9711. 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior',
  9712. 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright',
  9713. 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde',
  9714. 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute',
  9715. 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex',
  9716. 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex',
  9717. 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute',
  9718. 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla',
  9719. 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex',
  9720. 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis',
  9721. 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis',
  9722. 'ugrave', 'yacute', 'ydieresis', 'zcaron'
  9723. ];
  9724. var ExpertCharset = [
  9725. '.notdef', 'space', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle',
  9726. 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
  9727. 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
  9728. 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
  9729. 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
  9730. 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle',
  9731. 'colon', 'semicolon', 'commasuperior', 'threequartersemdash',
  9732. 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior',
  9733. 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  9734. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  9735. 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
  9736. 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
  9737. 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
  9738. 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
  9739. 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
  9740. 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
  9741. 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle',
  9742. 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall',
  9743. 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall',
  9744. 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall',
  9745. 'Cedillasmall', 'onequarter', 'onehalf', 'threequarters',
  9746. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
  9747. 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
  9748. 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  9749. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  9750. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
  9751. 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
  9752. 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
  9753. 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall',
  9754. 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall',
  9755. 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
  9756. 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  9757. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
  9758. 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
  9759. 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  9760. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
  9761. 'Ydieresissmall'
  9762. ];
  9763. var ExpertSubsetCharset = [
  9764. '.notdef', 'space', 'dollaroldstyle', 'dollarsuperior',
  9765. 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  9766. 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction',
  9767. 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle',
  9768. 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle',
  9769. 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior',
  9770. 'threequartersemdash', 'periodsuperior', 'asuperior', 'bsuperior',
  9771. 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
  9772. 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  9773. 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior',
  9774. 'parenrightinferior', 'hyphensuperior', 'colonmonetary', 'onefitted',
  9775. 'rupiah', 'centoldstyle', 'figuredash', 'hypheninferior', 'onequarter',
  9776. 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
  9777. 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior',
  9778. 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
  9779. 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
  9780. 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior',
  9781. 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior',
  9782. 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior',
  9783. 'periodinferior', 'commainferior'
  9784. ];
  9785. var DEFAULT_ICON_SIZE = 22; // px
  9786. var SUPPORTED_TYPES = ['Link', 'Text', 'Widget'];
  9787. var Annotation = (function AnnotationClosure() {
  9788. // 12.5.5: Algorithm: Appearance streams
  9789. function getTransformMatrix(rect, bbox, matrix) {
  9790. var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);
  9791. var minX = bounds[0];
  9792. var minY = bounds[1];
  9793. var maxX = bounds[2];
  9794. var maxY = bounds[3];
  9795. if (minX === maxX || minY === maxY) {
  9796. // From real-life file, bbox was [0, 0, 0, 0]. In this case,
  9797. // just apply the transform for rect
  9798. return [1, 0, 0, 1, rect[0], rect[1]];
  9799. }
  9800. var xRatio = (rect[2] - rect[0]) / (maxX - minX);
  9801. var yRatio = (rect[3] - rect[1]) / (maxY - minY);
  9802. return [
  9803. xRatio,
  9804. 0,
  9805. 0,
  9806. yRatio,
  9807. rect[0] - minX * xRatio,
  9808. rect[1] - minY * yRatio
  9809. ];
  9810. }
  9811. function getDefaultAppearance(dict) {
  9812. var appearanceState = dict.get('AP');
  9813. if (!isDict(appearanceState)) {
  9814. return;
  9815. }
  9816. var appearance;
  9817. var appearances = appearanceState.get('N');
  9818. if (isDict(appearances)) {
  9819. var as = dict.get('AS');
  9820. if (as && appearances.has(as.name)) {
  9821. appearance = appearances.get(as.name);
  9822. }
  9823. } else {
  9824. appearance = appearances;
  9825. }
  9826. return appearance;
  9827. }
  9828. function Annotation(params) {
  9829. var dict = params.dict;
  9830. var data = this.data = {};
  9831. data.subtype = dict.get('Subtype').name;
  9832. var rect = dict.get('Rect') || [0, 0, 0, 0];
  9833. data.rect = Util.normalizeRect(rect);
  9834. data.annotationFlags = dict.get('F');
  9835. var color = dict.get('C');
  9836. if (!color) {
  9837. // The PDF spec does not mention how a missing color array is interpreted.
  9838. // Adobe Reader seems to default to black in this case.
  9839. data.color = [0, 0, 0];
  9840. } else if (isArray(color)) {
  9841. switch (color.length) {
  9842. case 0:
  9843. // Empty array denotes transparent border.
  9844. data.color = null;
  9845. break;
  9846. case 1:
  9847. // TODO: implement DeviceGray
  9848. break;
  9849. case 3:
  9850. data.color = color;
  9851. break;
  9852. case 4:
  9853. // TODO: implement DeviceCMYK
  9854. break;
  9855. }
  9856. }
  9857. // Some types of annotations have border style dict which has more
  9858. // info than the border array
  9859. if (dict.has('BS')) {
  9860. var borderStyle = dict.get('BS');
  9861. data.borderWidth = borderStyle.has('W') ? borderStyle.get('W') : 1;
  9862. } else {
  9863. var borderArray = dict.get('Border') || [0, 0, 1];
  9864. data.borderWidth = borderArray[2] || 0;
  9865. // TODO: implement proper support for annotations with line dash patterns.
  9866. var dashArray = borderArray[3];
  9867. if (data.borderWidth > 0 && dashArray) {
  9868. if (!isArray(dashArray)) {
  9869. // Ignore the border if dashArray is not actually an array,
  9870. // this is consistent with the behaviour in Adobe Reader.
  9871. data.borderWidth = 0;
  9872. } else {
  9873. var dashArrayLength = dashArray.length;
  9874. if (dashArrayLength > 0) {
  9875. // According to the PDF specification: the elements in a dashArray
  9876. // shall be numbers that are nonnegative and not all equal to zero.
  9877. var isInvalid = false;
  9878. var numPositive = 0;
  9879. for (var i = 0; i < dashArrayLength; i++) {
  9880. var validNumber = (+dashArray[i] >= 0);
  9881. if (!validNumber) {
  9882. isInvalid = true;
  9883. break;
  9884. } else if (dashArray[i] > 0) {
  9885. numPositive++;
  9886. }
  9887. }
  9888. if (isInvalid || numPositive === 0) {
  9889. data.borderWidth = 0;
  9890. }
  9891. }
  9892. }
  9893. }
  9894. }
  9895. this.appearance = getDefaultAppearance(dict);
  9896. data.hasAppearance = !!this.appearance;
  9897. data.id = params.ref.num;
  9898. }
  9899. Annotation.prototype = {
  9900. getData: function Annotation_getData() {
  9901. return this.data;
  9902. },
  9903. isInvisible: function Annotation_isInvisible() {
  9904. var data = this.data;
  9905. if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) {
  9906. return false;
  9907. } else {
  9908. return !!(data &&
  9909. data.annotationFlags && // Default: not invisible
  9910. data.annotationFlags & 0x1); // Invisible
  9911. }
  9912. },
  9913. isViewable: function Annotation_isViewable() {
  9914. var data = this.data;
  9915. return !!(!this.isInvisible() &&
  9916. data &&
  9917. (!data.annotationFlags ||
  9918. !(data.annotationFlags & 0x22)) && // Hidden or NoView
  9919. data.rect); // rectangle is necessary
  9920. },
  9921. isPrintable: function Annotation_isPrintable() {
  9922. var data = this.data;
  9923. return !!(!this.isInvisible() &&
  9924. data &&
  9925. data.annotationFlags && // Default: not printable
  9926. data.annotationFlags & 0x4 && // Print
  9927. !(data.annotationFlags & 0x2) && // Hidden
  9928. data.rect); // rectangle is necessary
  9929. },
  9930. loadResources: function Annotation_loadResources(keys) {
  9931. return new Promise(function (resolve, reject) {
  9932. this.appearance.dict.getAsync('Resources').then(function (resources) {
  9933. if (!resources) {
  9934. resolve();
  9935. return;
  9936. }
  9937. var objectLoader = new ObjectLoader(resources.map,
  9938. keys,
  9939. resources.xref);
  9940. objectLoader.load().then(function() {
  9941. resolve(resources);
  9942. }, reject);
  9943. }, reject);
  9944. }.bind(this));
  9945. },
  9946. getOperatorList: function Annotation_getOperatorList(evaluator) {
  9947. if (!this.appearance) {
  9948. return Promise.resolve(new OperatorList());
  9949. }
  9950. var data = this.data;
  9951. var appearanceDict = this.appearance.dict;
  9952. var resourcesPromise = this.loadResources([
  9953. 'ExtGState',
  9954. 'ColorSpace',
  9955. 'Pattern',
  9956. 'Shading',
  9957. 'XObject',
  9958. 'Font'
  9959. // ProcSet
  9960. // Properties
  9961. ]);
  9962. var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];
  9963. var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];
  9964. var transform = getTransformMatrix(data.rect, bbox, matrix);
  9965. var self = this;
  9966. return resourcesPromise.then(function(resources) {
  9967. var opList = new OperatorList();
  9968. opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
  9969. return evaluator.getOperatorList(self.appearance, resources, opList).
  9970. then(function () {
  9971. opList.addOp(OPS.endAnnotation, []);
  9972. self.appearance.reset();
  9973. return opList;
  9974. });
  9975. });
  9976. }
  9977. };
  9978. Annotation.getConstructor =
  9979. function Annotation_getConstructor(subtype, fieldType) {
  9980. if (!subtype) {
  9981. return;
  9982. }
  9983. // TODO(mack): Implement FreeText annotations
  9984. if (subtype === 'Link') {
  9985. return LinkAnnotation;
  9986. } else if (subtype === 'Text') {
  9987. return TextAnnotation;
  9988. } else if (subtype === 'Widget') {
  9989. if (!fieldType) {
  9990. return;
  9991. }
  9992. if (fieldType === 'Tx') {
  9993. return TextWidgetAnnotation;
  9994. } else {
  9995. return WidgetAnnotation;
  9996. }
  9997. } else {
  9998. return Annotation;
  9999. }
  10000. };
  10001. Annotation.fromRef = function Annotation_fromRef(xref, ref) {
  10002. var dict = xref.fetchIfRef(ref);
  10003. if (!isDict(dict)) {
  10004. return;
  10005. }
  10006. var subtype = dict.get('Subtype');
  10007. subtype = isName(subtype) ? subtype.name : '';
  10008. if (!subtype) {
  10009. return;
  10010. }
  10011. var fieldType = Util.getInheritableProperty(dict, 'FT');
  10012. fieldType = isName(fieldType) ? fieldType.name : '';
  10013. var Constructor = Annotation.getConstructor(subtype, fieldType);
  10014. if (!Constructor) {
  10015. return;
  10016. }
  10017. var params = {
  10018. dict: dict,
  10019. ref: ref,
  10020. };
  10021. var annotation = new Constructor(params);
  10022. if (annotation.isViewable() || annotation.isPrintable()) {
  10023. return annotation;
  10024. } else {
  10025. if (SUPPORTED_TYPES.indexOf(subtype) === -1) {
  10026. warn('unimplemented annotation type: ' + subtype);
  10027. }
  10028. }
  10029. };
  10030. Annotation.appendToOperatorList = function Annotation_appendToOperatorList(
  10031. annotations, opList, pdfManager, partialEvaluator, intent) {
  10032. function reject(e) {
  10033. annotationsReadyCapability.reject(e);
  10034. }
  10035. var annotationsReadyCapability = createPromiseCapability();
  10036. var annotationPromises = [];
  10037. for (var i = 0, n = annotations.length; i < n; ++i) {
  10038. if (intent === 'display' && annotations[i].isViewable() ||
  10039. intent === 'print' && annotations[i].isPrintable()) {
  10040. annotationPromises.push(
  10041. annotations[i].getOperatorList(partialEvaluator));
  10042. }
  10043. }
  10044. Promise.all(annotationPromises).then(function(datas) {
  10045. opList.addOp(OPS.beginAnnotations, []);
  10046. for (var i = 0, n = datas.length; i < n; ++i) {
  10047. var annotOpList = datas[i];
  10048. opList.addOpList(annotOpList);
  10049. }
  10050. opList.addOp(OPS.endAnnotations, []);
  10051. annotationsReadyCapability.resolve();
  10052. }, reject);
  10053. return annotationsReadyCapability.promise;
  10054. };
  10055. return Annotation;
  10056. })();
  10057. var WidgetAnnotation = (function WidgetAnnotationClosure() {
  10058. function WidgetAnnotation(params) {
  10059. Annotation.call(this, params);
  10060. var dict = params.dict;
  10061. var data = this.data;
  10062. data.fieldValue = stringToPDFString(
  10063. Util.getInheritableProperty(dict, 'V') || '');
  10064. data.alternativeText = stringToPDFString(dict.get('TU') || '');
  10065. data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';
  10066. var fieldType = Util.getInheritableProperty(dict, 'FT');
  10067. data.fieldType = isName(fieldType) ? fieldType.name : '';
  10068. data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;
  10069. this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;
  10070. // Building the full field name by collecting the field and
  10071. // its ancestors 'T' data and joining them using '.'.
  10072. var fieldName = [];
  10073. var namedItem = dict;
  10074. var ref = params.ref;
  10075. while (namedItem) {
  10076. var parent = namedItem.get('Parent');
  10077. var parentRef = namedItem.getRaw('Parent');
  10078. var name = namedItem.get('T');
  10079. if (name) {
  10080. fieldName.unshift(stringToPDFString(name));
  10081. } else if (parent && ref) {
  10082. // The field name is absent, that means more than one field
  10083. // with the same name may exist. Replacing the empty name
  10084. // with the '`' plus index in the parent's 'Kids' array.
  10085. // This is not in the PDF spec but necessary to id the
  10086. // the input controls.
  10087. var kids = parent.get('Kids');
  10088. var j, jj;
  10089. for (j = 0, jj = kids.length; j < jj; j++) {
  10090. var kidRef = kids[j];
  10091. if (kidRef.num === ref.num && kidRef.gen === ref.gen) {
  10092. break;
  10093. }
  10094. }
  10095. fieldName.unshift('`' + j);
  10096. }
  10097. namedItem = parent;
  10098. ref = parentRef;
  10099. }
  10100. data.fullName = fieldName.join('.');
  10101. }
  10102. var parent = Annotation.prototype;
  10103. Util.inherit(WidgetAnnotation, Annotation, {
  10104. isViewable: function WidgetAnnotation_isViewable() {
  10105. if (this.data.fieldType === 'Sig') {
  10106. warn('unimplemented annotation type: Widget signature');
  10107. return false;
  10108. }
  10109. return parent.isViewable.call(this);
  10110. }
  10111. });
  10112. return WidgetAnnotation;
  10113. })();
  10114. var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
  10115. function TextWidgetAnnotation(params) {
  10116. WidgetAnnotation.call(this, params);
  10117. this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');
  10118. this.data.annotationType = AnnotationType.WIDGET;
  10119. this.data.hasHtml = !this.data.hasAppearance && !!this.data.fieldValue;
  10120. }
  10121. Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
  10122. getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {
  10123. if (this.appearance) {
  10124. return Annotation.prototype.getOperatorList.call(this, evaluator);
  10125. }
  10126. var opList = new OperatorList();
  10127. var data = this.data;
  10128. // Even if there is an appearance stream, ignore it. This is the
  10129. // behaviour used by Adobe Reader.
  10130. if (!data.defaultAppearance) {
  10131. return Promise.resolve(opList);
  10132. }
  10133. var stream = new Stream(stringToBytes(data.defaultAppearance));
  10134. return evaluator.getOperatorList(stream, this.fieldResources, opList).
  10135. then(function () {
  10136. return opList;
  10137. });
  10138. }
  10139. });
  10140. return TextWidgetAnnotation;
  10141. })();
  10142. var InteractiveAnnotation = (function InteractiveAnnotationClosure() {
  10143. function InteractiveAnnotation(params) {
  10144. Annotation.call(this, params);
  10145. this.data.hasHtml = true;
  10146. }
  10147. Util.inherit(InteractiveAnnotation, Annotation, { });
  10148. return InteractiveAnnotation;
  10149. })();
  10150. var TextAnnotation = (function TextAnnotationClosure() {
  10151. function TextAnnotation(params) {
  10152. InteractiveAnnotation.call(this, params);
  10153. var dict = params.dict;
  10154. var data = this.data;
  10155. var content = dict.get('Contents');
  10156. var title = dict.get('T');
  10157. data.annotationType = AnnotationType.TEXT;
  10158. data.content = stringToPDFString(content || '');
  10159. data.title = stringToPDFString(title || '');
  10160. if (data.hasAppearance) {
  10161. data.name = 'NoIcon';
  10162. } else {
  10163. data.rect[1] = data.rect[3] - DEFAULT_ICON_SIZE;
  10164. data.rect[2] = data.rect[0] + DEFAULT_ICON_SIZE;
  10165. data.name = dict.has('Name') ? dict.get('Name').name : 'Note';
  10166. }
  10167. if (dict.has('C')) {
  10168. data.hasBgColor = true;
  10169. }
  10170. }
  10171. Util.inherit(TextAnnotation, InteractiveAnnotation, { });
  10172. return TextAnnotation;
  10173. })();
  10174. var LinkAnnotation = (function LinkAnnotationClosure() {
  10175. function LinkAnnotation(params) {
  10176. InteractiveAnnotation.call(this, params);
  10177. var dict = params.dict;
  10178. var data = this.data;
  10179. data.annotationType = AnnotationType.LINK;
  10180. var action = dict.get('A');
  10181. if (action) {
  10182. var linkType = action.get('S').name;
  10183. if (linkType === 'URI') {
  10184. var url = action.get('URI');
  10185. if (isName(url)) {
  10186. // Some bad PDFs do not put parentheses around relative URLs.
  10187. url = '/' + url.name;
  10188. } else if (url) {
  10189. url = addDefaultProtocolToUrl(url);
  10190. }
  10191. // TODO: pdf spec mentions urls can be relative to a Base
  10192. // entry in the dictionary.
  10193. if (!isValidUrl(url, false)) {
  10194. url = '';
  10195. }
  10196. data.url = url;
  10197. } else if (linkType === 'GoTo') {
  10198. data.dest = action.get('D');
  10199. } else if (linkType === 'GoToR') {
  10200. var urlDict = action.get('F');
  10201. if (isDict(urlDict)) {
  10202. // We assume that the 'url' is a Filspec dictionary
  10203. // and fetch the url without checking any further
  10204. url = urlDict.get('F') || '';
  10205. }
  10206. // TODO: pdf reference says that GoToR
  10207. // can also have 'NewWindow' attribute
  10208. if (!isValidUrl(url, false)) {
  10209. url = '';
  10210. }
  10211. data.url = url;
  10212. data.dest = action.get('D');
  10213. } else if (linkType === 'Named') {
  10214. data.action = action.get('N').name;
  10215. } else {
  10216. warn('unrecognized link type: ' + linkType);
  10217. }
  10218. } else if (dict.has('Dest')) {
  10219. // simple destination link
  10220. var dest = dict.get('Dest');
  10221. data.dest = isName(dest) ? dest.name : dest;
  10222. }
  10223. }
  10224. // Lets URLs beginning with 'www.' default to using the 'http://' protocol.
  10225. function addDefaultProtocolToUrl(url) {
  10226. if (url && url.indexOf('www.') === 0) {
  10227. return ('http://' + url);
  10228. }
  10229. return url;
  10230. }
  10231. Util.inherit(LinkAnnotation, InteractiveAnnotation, { });
  10232. return LinkAnnotation;
  10233. })();
  10234. var PDFFunction = (function PDFFunctionClosure() {
  10235. var CONSTRUCT_SAMPLED = 0;
  10236. var CONSTRUCT_INTERPOLATED = 2;
  10237. var CONSTRUCT_STICHED = 3;
  10238. var CONSTRUCT_POSTSCRIPT = 4;
  10239. return {
  10240. getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,
  10241. str) {
  10242. var i, ii;
  10243. var length = 1;
  10244. for (i = 0, ii = size.length; i < ii; i++) {
  10245. length *= size[i];
  10246. }
  10247. length *= outputSize;
  10248. var array = new Array(length);
  10249. var codeSize = 0;
  10250. var codeBuf = 0;
  10251. // 32 is a valid bps so shifting won't work
  10252. var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);
  10253. var strBytes = str.getBytes((length * bps + 7) / 8);
  10254. var strIdx = 0;
  10255. for (i = 0; i < length; i++) {
  10256. while (codeSize < bps) {
  10257. codeBuf <<= 8;
  10258. codeBuf |= strBytes[strIdx++];
  10259. codeSize += 8;
  10260. }
  10261. codeSize -= bps;
  10262. array[i] = (codeBuf >> codeSize) * sampleMul;
  10263. codeBuf &= (1 << codeSize) - 1;
  10264. }
  10265. return array;
  10266. },
  10267. getIR: function PDFFunction_getIR(xref, fn) {
  10268. var dict = fn.dict;
  10269. if (!dict) {
  10270. dict = fn;
  10271. }
  10272. var types = [this.constructSampled,
  10273. null,
  10274. this.constructInterpolated,
  10275. this.constructStiched,
  10276. this.constructPostScript];
  10277. var typeNum = dict.get('FunctionType');
  10278. var typeFn = types[typeNum];
  10279. if (!typeFn) {
  10280. error('Unknown type of function');
  10281. }
  10282. return typeFn.call(this, fn, dict, xref);
  10283. },
  10284. fromIR: function PDFFunction_fromIR(IR) {
  10285. var type = IR[0];
  10286. switch (type) {
  10287. case CONSTRUCT_SAMPLED:
  10288. return this.constructSampledFromIR(IR);
  10289. case CONSTRUCT_INTERPOLATED:
  10290. return this.constructInterpolatedFromIR(IR);
  10291. case CONSTRUCT_STICHED:
  10292. return this.constructStichedFromIR(IR);
  10293. //case CONSTRUCT_POSTSCRIPT:
  10294. default:
  10295. return this.constructPostScriptFromIR(IR);
  10296. }
  10297. },
  10298. parse: function PDFFunction_parse(xref, fn) {
  10299. var IR = this.getIR(xref, fn);
  10300. return this.fromIR(IR);
  10301. },
  10302. parseArray: function PDFFunction_parseArray(xref, fnObj) {
  10303. if (!isArray(fnObj)) {
  10304. // not an array -- parsing as regular function
  10305. return this.parse(xref, fnObj);
  10306. }
  10307. var fnArray = [];
  10308. for (var j = 0, jj = fnObj.length; j < jj; j++) {
  10309. var obj = xref.fetchIfRef(fnObj[j]);
  10310. fnArray.push(PDFFunction.parse(xref, obj));
  10311. }
  10312. return function (src, srcOffset, dest, destOffset) {
  10313. for (var i = 0, ii = fnArray.length; i < ii; i++) {
  10314. fnArray[i](src, srcOffset, dest, destOffset + i);
  10315. }
  10316. };
  10317. },
  10318. constructSampled: function PDFFunction_constructSampled(str, dict) {
  10319. function toMultiArray(arr) {
  10320. var inputLength = arr.length;
  10321. var out = [];
  10322. var index = 0;
  10323. for (var i = 0; i < inputLength; i += 2) {
  10324. out[index] = [arr[i], arr[i + 1]];
  10325. ++index;
  10326. }
  10327. return out;
  10328. }
  10329. var domain = dict.get('Domain');
  10330. var range = dict.get('Range');
  10331. if (!domain || !range) {
  10332. error('No domain or range');
  10333. }
  10334. var inputSize = domain.length / 2;
  10335. var outputSize = range.length / 2;
  10336. domain = toMultiArray(domain);
  10337. range = toMultiArray(range);
  10338. var size = dict.get('Size');
  10339. var bps = dict.get('BitsPerSample');
  10340. var order = dict.get('Order') || 1;
  10341. if (order !== 1) {
  10342. // No description how cubic spline interpolation works in PDF32000:2008
  10343. // As in poppler, ignoring order, linear interpolation may work as good
  10344. info('No support for cubic spline interpolation: ' + order);
  10345. }
  10346. var encode = dict.get('Encode');
  10347. if (!encode) {
  10348. encode = [];
  10349. for (var i = 0; i < inputSize; ++i) {
  10350. encode.push(0);
  10351. encode.push(size[i] - 1);
  10352. }
  10353. }
  10354. encode = toMultiArray(encode);
  10355. var decode = dict.get('Decode');
  10356. if (!decode) {
  10357. decode = range;
  10358. } else {
  10359. decode = toMultiArray(decode);
  10360. }
  10361. var samples = this.getSampleArray(size, outputSize, bps, str);
  10362. return [
  10363. CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,
  10364. outputSize, Math.pow(2, bps) - 1, range
  10365. ];
  10366. },
  10367. constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {
  10368. // See chapter 3, page 109 of the PDF reference
  10369. function interpolate(x, xmin, xmax, ymin, ymax) {
  10370. return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));
  10371. }
  10372. return function constructSampledFromIRResult(src, srcOffset,
  10373. dest, destOffset) {
  10374. // See chapter 3, page 110 of the PDF reference.
  10375. var m = IR[1];
  10376. var domain = IR[2];
  10377. var encode = IR[3];
  10378. var decode = IR[4];
  10379. var samples = IR[5];
  10380. var size = IR[6];
  10381. var n = IR[7];
  10382. //var mask = IR[8];
  10383. var range = IR[9];
  10384. // Building the cube vertices: its part and sample index
  10385. // http://rjwagner49.com/Mathematics/Interpolation.pdf
  10386. var cubeVertices = 1 << m;
  10387. var cubeN = new Float64Array(cubeVertices);
  10388. var cubeVertex = new Uint32Array(cubeVertices);
  10389. var i, j;
  10390. for (j = 0; j < cubeVertices; j++) {
  10391. cubeN[j] = 1;
  10392. }
  10393. var k = n, pos = 1;
  10394. // Map x_i to y_j for 0 <= i < m using the sampled function.
  10395. for (i = 0; i < m; ++i) {
  10396. // x_i' = min(max(x_i, Domain_2i), Domain_2i+1)
  10397. var domain_2i = domain[i][0];
  10398. var domain_2i_1 = domain[i][1];
  10399. var xi = Math.min(Math.max(src[srcOffset +i], domain_2i),
  10400. domain_2i_1);
  10401. // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,
  10402. // Encode_2i, Encode_2i+1)
  10403. var e = interpolate(xi, domain_2i, domain_2i_1,
  10404. encode[i][0], encode[i][1]);
  10405. // e_i' = min(max(e_i, 0), Size_i - 1)
  10406. var size_i = size[i];
  10407. e = Math.min(Math.max(e, 0), size_i - 1);
  10408. // Adjusting the cube: N and vertex sample index
  10409. var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;
  10410. var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);
  10411. var n1 = e - e0; // (e - e0) / (e1 - e0);
  10412. var offset0 = e0 * k;
  10413. var offset1 = offset0 + k; // e1 * k
  10414. for (j = 0; j < cubeVertices; j++) {
  10415. if (j & pos) {
  10416. cubeN[j] *= n1;
  10417. cubeVertex[j] += offset1;
  10418. } else {
  10419. cubeN[j] *= n0;
  10420. cubeVertex[j] += offset0;
  10421. }
  10422. }
  10423. k *= size_i;
  10424. pos <<= 1;
  10425. }
  10426. for (j = 0; j < n; ++j) {
  10427. // Sum all cube vertices' samples portions
  10428. var rj = 0;
  10429. for (i = 0; i < cubeVertices; i++) {
  10430. rj += samples[cubeVertex[i] + j] * cubeN[i];
  10431. }
  10432. // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,
  10433. // Decode_2j, Decode_2j+1)
  10434. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  10435. // y_j = min(max(r_j, range_2j), range_2j+1)
  10436. dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]),
  10437. range[j][1]);
  10438. }
  10439. };
  10440. },
  10441. constructInterpolated: function PDFFunction_constructInterpolated(str,
  10442. dict) {
  10443. var c0 = dict.get('C0') || [0];
  10444. var c1 = dict.get('C1') || [1];
  10445. var n = dict.get('N');
  10446. if (!isArray(c0) || !isArray(c1)) {
  10447. error('Illegal dictionary for interpolated function');
  10448. }
  10449. var length = c0.length;
  10450. var diff = [];
  10451. for (var i = 0; i < length; ++i) {
  10452. diff.push(c1[i] - c0[i]);
  10453. }
  10454. return [CONSTRUCT_INTERPOLATED, c0, diff, n];
  10455. },
  10456. constructInterpolatedFromIR:
  10457. function PDFFunction_constructInterpolatedFromIR(IR) {
  10458. var c0 = IR[1];
  10459. var diff = IR[2];
  10460. var n = IR[3];
  10461. var length = diff.length;
  10462. return function constructInterpolatedFromIRResult(src, srcOffset,
  10463. dest, destOffset) {
  10464. var x = n === 1 ? src[srcOffset] : Math.pow(src[srcOffset], n);
  10465. for (var j = 0; j < length; ++j) {
  10466. dest[destOffset + j] = c0[j] + (x * diff[j]);
  10467. }
  10468. };
  10469. },
  10470. constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {
  10471. var domain = dict.get('Domain');
  10472. if (!domain) {
  10473. error('No domain');
  10474. }
  10475. var inputSize = domain.length / 2;
  10476. if (inputSize !== 1) {
  10477. error('Bad domain for stiched function');
  10478. }
  10479. var fnRefs = dict.get('Functions');
  10480. var fns = [];
  10481. for (var i = 0, ii = fnRefs.length; i < ii; ++i) {
  10482. fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));
  10483. }
  10484. var bounds = dict.get('Bounds');
  10485. var encode = dict.get('Encode');
  10486. return [CONSTRUCT_STICHED, domain, bounds, encode, fns];
  10487. },
  10488. constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {
  10489. var domain = IR[1];
  10490. var bounds = IR[2];
  10491. var encode = IR[3];
  10492. var fnsIR = IR[4];
  10493. var fns = [];
  10494. var tmpBuf = new Float32Array(1);
  10495. for (var i = 0, ii = fnsIR.length; i < ii; i++) {
  10496. fns.push(PDFFunction.fromIR(fnsIR[i]));
  10497. }
  10498. return function constructStichedFromIRResult(src, srcOffset,
  10499. dest, destOffset) {
  10500. var clip = function constructStichedFromIRClip(v, min, max) {
  10501. if (v > max) {
  10502. v = max;
  10503. } else if (v < min) {
  10504. v = min;
  10505. }
  10506. return v;
  10507. };
  10508. // clip to domain
  10509. var v = clip(src[srcOffset], domain[0], domain[1]);
  10510. // calulate which bound the value is in
  10511. for (var i = 0, ii = bounds.length; i < ii; ++i) {
  10512. if (v < bounds[i]) {
  10513. break;
  10514. }
  10515. }
  10516. // encode value into domain of function
  10517. var dmin = domain[0];
  10518. if (i > 0) {
  10519. dmin = bounds[i - 1];
  10520. }
  10521. var dmax = domain[1];
  10522. if (i < bounds.length) {
  10523. dmax = bounds[i];
  10524. }
  10525. var rmin = encode[2 * i];
  10526. var rmax = encode[2 * i + 1];
  10527. tmpBuf[0] = rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  10528. // call the appropriate function
  10529. fns[i](tmpBuf, 0, dest, destOffset);
  10530. };
  10531. },
  10532. constructPostScript: function PDFFunction_constructPostScript(fn, dict,
  10533. xref) {
  10534. var domain = dict.get('Domain');
  10535. var range = dict.get('Range');
  10536. if (!domain) {
  10537. error('No domain.');
  10538. }
  10539. if (!range) {
  10540. error('No range.');
  10541. }
  10542. var lexer = new PostScriptLexer(fn);
  10543. var parser = new PostScriptParser(lexer);
  10544. var code = parser.parse();
  10545. return [CONSTRUCT_POSTSCRIPT, domain, range, code];
  10546. },
  10547. constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(
  10548. IR) {
  10549. var domain = IR[1];
  10550. var range = IR[2];
  10551. var code = IR[3];
  10552. var compiled = (new PostScriptCompiler()).compile(code, domain, range);
  10553. if (compiled) {
  10554. // Compiled function consists of simple expressions such as addition,
  10555. // subtraction, Math.max, and also contains 'var' and 'return'
  10556. // statements. See the generation in the PostScriptCompiler below.
  10557. /*jshint -W054 */
  10558. return new Function('src', 'srcOffset', 'dest', 'destOffset', compiled);
  10559. }
  10560. info('Unable to compile PS function');
  10561. var numOutputs = range.length >> 1;
  10562. var numInputs = domain.length >> 1;
  10563. var evaluator = new PostScriptEvaluator(code);
  10564. // Cache the values for a big speed up, the cache size is limited though
  10565. // since the number of possible values can be huge from a PS function.
  10566. var cache = {};
  10567. // The MAX_CACHE_SIZE is set to ~4x the maximum number of distinct values
  10568. // seen in our tests.
  10569. var MAX_CACHE_SIZE = 2048 * 4;
  10570. var cache_available = MAX_CACHE_SIZE;
  10571. var tmpBuf = new Float32Array(numInputs);
  10572. return function constructPostScriptFromIRResult(src, srcOffset,
  10573. dest, destOffset) {
  10574. var i, value;
  10575. var key = '';
  10576. var input = tmpBuf;
  10577. for (i = 0; i < numInputs; i++) {
  10578. value = src[srcOffset + i];
  10579. input[i] = value;
  10580. key += value + '_';
  10581. }
  10582. var cachedValue = cache[key];
  10583. if (cachedValue !== undefined) {
  10584. dest.set(cachedValue, destOffset);
  10585. return;
  10586. }
  10587. var output = new Float32Array(numOutputs);
  10588. var stack = evaluator.execute(input);
  10589. var stackIndex = stack.length - numOutputs;
  10590. for (i = 0; i < numOutputs; i++) {
  10591. value = stack[stackIndex + i];
  10592. var bound = range[i * 2];
  10593. if (value < bound) {
  10594. value = bound;
  10595. } else {
  10596. bound = range[i * 2 +1];
  10597. if (value > bound) {
  10598. value = bound;
  10599. }
  10600. }
  10601. output[i] = value;
  10602. }
  10603. if (cache_available > 0) {
  10604. cache_available--;
  10605. cache[key] = output;
  10606. }
  10607. dest.set(output, destOffset);
  10608. };
  10609. }
  10610. };
  10611. })();
  10612. function isPDFFunction(v) {
  10613. var fnDict;
  10614. if (typeof v !== 'object') {
  10615. return false;
  10616. } else if (isDict(v)) {
  10617. fnDict = v;
  10618. } else if (isStream(v)) {
  10619. fnDict = v.dict;
  10620. } else {
  10621. return false;
  10622. }
  10623. return fnDict.has('FunctionType');
  10624. }
  10625. var PostScriptStack = (function PostScriptStackClosure() {
  10626. var MAX_STACK_SIZE = 100;
  10627. function PostScriptStack(initialStack) {
  10628. this.stack = !initialStack ? [] :
  10629. Array.prototype.slice.call(initialStack, 0);
  10630. }
  10631. PostScriptStack.prototype = {
  10632. push: function PostScriptStack_push(value) {
  10633. if (this.stack.length >= MAX_STACK_SIZE) {
  10634. error('PostScript function stack overflow.');
  10635. }
  10636. this.stack.push(value);
  10637. },
  10638. pop: function PostScriptStack_pop() {
  10639. if (this.stack.length <= 0) {
  10640. error('PostScript function stack underflow.');
  10641. }
  10642. return this.stack.pop();
  10643. },
  10644. copy: function PostScriptStack_copy(n) {
  10645. if (this.stack.length + n >= MAX_STACK_SIZE) {
  10646. error('PostScript function stack overflow.');
  10647. }
  10648. var stack = this.stack;
  10649. for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  10650. stack.push(stack[i]);
  10651. }
  10652. },
  10653. index: function PostScriptStack_index(n) {
  10654. this.push(this.stack[this.stack.length - n - 1]);
  10655. },
  10656. // rotate the last n stack elements p times
  10657. roll: function PostScriptStack_roll(n, p) {
  10658. var stack = this.stack;
  10659. var l = stack.length - n;
  10660. var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;
  10661. for (i = l, j = r; i < j; i++, j--) {
  10662. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  10663. }
  10664. for (i = l, j = c - 1; i < j; i++, j--) {
  10665. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  10666. }
  10667. for (i = c, j = r; i < j; i++, j--) {
  10668. t = stack[i]; stack[i] = stack[j]; stack[j] = t;
  10669. }
  10670. }
  10671. };
  10672. return PostScriptStack;
  10673. })();
  10674. var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {
  10675. function PostScriptEvaluator(operators) {
  10676. this.operators = operators;
  10677. }
  10678. PostScriptEvaluator.prototype = {
  10679. execute: function PostScriptEvaluator_execute(initialStack) {
  10680. var stack = new PostScriptStack(initialStack);
  10681. var counter = 0;
  10682. var operators = this.operators;
  10683. var length = operators.length;
  10684. var operator, a, b;
  10685. while (counter < length) {
  10686. operator = operators[counter++];
  10687. if (typeof operator === 'number') {
  10688. // Operator is really an operand and should be pushed to the stack.
  10689. stack.push(operator);
  10690. continue;
  10691. }
  10692. switch (operator) {
  10693. // non standard ps operators
  10694. case 'jz': // jump if false
  10695. b = stack.pop();
  10696. a = stack.pop();
  10697. if (!a) {
  10698. counter = b;
  10699. }
  10700. break;
  10701. case 'j': // jump
  10702. a = stack.pop();
  10703. counter = a;
  10704. break;
  10705. // all ps operators in alphabetical order (excluding if/ifelse)
  10706. case 'abs':
  10707. a = stack.pop();
  10708. stack.push(Math.abs(a));
  10709. break;
  10710. case 'add':
  10711. b = stack.pop();
  10712. a = stack.pop();
  10713. stack.push(a + b);
  10714. break;
  10715. case 'and':
  10716. b = stack.pop();
  10717. a = stack.pop();
  10718. if (isBool(a) && isBool(b)) {
  10719. stack.push(a && b);
  10720. } else {
  10721. stack.push(a & b);
  10722. }
  10723. break;
  10724. case 'atan':
  10725. a = stack.pop();
  10726. stack.push(Math.atan(a));
  10727. break;
  10728. case 'bitshift':
  10729. b = stack.pop();
  10730. a = stack.pop();
  10731. if (a > 0) {
  10732. stack.push(a << b);
  10733. } else {
  10734. stack.push(a >> b);
  10735. }
  10736. break;
  10737. case 'ceiling':
  10738. a = stack.pop();
  10739. stack.push(Math.ceil(a));
  10740. break;
  10741. case 'copy':
  10742. a = stack.pop();
  10743. stack.copy(a);
  10744. break;
  10745. case 'cos':
  10746. a = stack.pop();
  10747. stack.push(Math.cos(a));
  10748. break;
  10749. case 'cvi':
  10750. a = stack.pop() | 0;
  10751. stack.push(a);
  10752. break;
  10753. case 'cvr':
  10754. // noop
  10755. break;
  10756. case 'div':
  10757. b = stack.pop();
  10758. a = stack.pop();
  10759. stack.push(a / b);
  10760. break;
  10761. case 'dup':
  10762. stack.copy(1);
  10763. break;
  10764. case 'eq':
  10765. b = stack.pop();
  10766. a = stack.pop();
  10767. stack.push(a === b);
  10768. break;
  10769. case 'exch':
  10770. stack.roll(2, 1);
  10771. break;
  10772. case 'exp':
  10773. b = stack.pop();
  10774. a = stack.pop();
  10775. stack.push(Math.pow(a, b));
  10776. break;
  10777. case 'false':
  10778. stack.push(false);
  10779. break;
  10780. case 'floor':
  10781. a = stack.pop();
  10782. stack.push(Math.floor(a));
  10783. break;
  10784. case 'ge':
  10785. b = stack.pop();
  10786. a = stack.pop();
  10787. stack.push(a >= b);
  10788. break;
  10789. case 'gt':
  10790. b = stack.pop();
  10791. a = stack.pop();
  10792. stack.push(a > b);
  10793. break;
  10794. case 'idiv':
  10795. b = stack.pop();
  10796. a = stack.pop();
  10797. stack.push((a / b) | 0);
  10798. break;
  10799. case 'index':
  10800. a = stack.pop();
  10801. stack.index(a);
  10802. break;
  10803. case 'le':
  10804. b = stack.pop();
  10805. a = stack.pop();
  10806. stack.push(a <= b);
  10807. break;
  10808. case 'ln':
  10809. a = stack.pop();
  10810. stack.push(Math.log(a));
  10811. break;
  10812. case 'log':
  10813. a = stack.pop();
  10814. stack.push(Math.log(a) / Math.LN10);
  10815. break;
  10816. case 'lt':
  10817. b = stack.pop();
  10818. a = stack.pop();
  10819. stack.push(a < b);
  10820. break;
  10821. case 'mod':
  10822. b = stack.pop();
  10823. a = stack.pop();
  10824. stack.push(a % b);
  10825. break;
  10826. case 'mul':
  10827. b = stack.pop();
  10828. a = stack.pop();
  10829. stack.push(a * b);
  10830. break;
  10831. case 'ne':
  10832. b = stack.pop();
  10833. a = stack.pop();
  10834. stack.push(a !== b);
  10835. break;
  10836. case 'neg':
  10837. a = stack.pop();
  10838. stack.push(-a);
  10839. break;
  10840. case 'not':
  10841. a = stack.pop();
  10842. if (isBool(a)) {
  10843. stack.push(!a);
  10844. } else {
  10845. stack.push(~a);
  10846. }
  10847. break;
  10848. case 'or':
  10849. b = stack.pop();
  10850. a = stack.pop();
  10851. if (isBool(a) && isBool(b)) {
  10852. stack.push(a || b);
  10853. } else {
  10854. stack.push(a | b);
  10855. }
  10856. break;
  10857. case 'pop':
  10858. stack.pop();
  10859. break;
  10860. case 'roll':
  10861. b = stack.pop();
  10862. a = stack.pop();
  10863. stack.roll(a, b);
  10864. break;
  10865. case 'round':
  10866. a = stack.pop();
  10867. stack.push(Math.round(a));
  10868. break;
  10869. case 'sin':
  10870. a = stack.pop();
  10871. stack.push(Math.sin(a));
  10872. break;
  10873. case 'sqrt':
  10874. a = stack.pop();
  10875. stack.push(Math.sqrt(a));
  10876. break;
  10877. case 'sub':
  10878. b = stack.pop();
  10879. a = stack.pop();
  10880. stack.push(a - b);
  10881. break;
  10882. case 'true':
  10883. stack.push(true);
  10884. break;
  10885. case 'truncate':
  10886. a = stack.pop();
  10887. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  10888. stack.push(a);
  10889. break;
  10890. case 'xor':
  10891. b = stack.pop();
  10892. a = stack.pop();
  10893. if (isBool(a) && isBool(b)) {
  10894. stack.push(a !== b);
  10895. } else {
  10896. stack.push(a ^ b);
  10897. }
  10898. break;
  10899. default:
  10900. error('Unknown operator ' + operator);
  10901. break;
  10902. }
  10903. }
  10904. return stack.stack;
  10905. }
  10906. };
  10907. return PostScriptEvaluator;
  10908. })();
  10909. // Most of the PDFs functions consist of simple operations such as:
  10910. // roll, exch, sub, cvr, pop, index, dup, mul, if, gt, add.
  10911. //
  10912. // We can compile most of such programs, and at the same moment, we can
  10913. // optimize some expressions using basic math properties. Keeping track of
  10914. // min/max values will allow us to avoid extra Math.min/Math.max calls.
  10915. var PostScriptCompiler = (function PostScriptCompilerClosure() {
  10916. function AstNode(type) {
  10917. this.type = type;
  10918. }
  10919. AstNode.prototype.visit = function (visitor) {
  10920. throw new Error('abstract method');
  10921. };
  10922. function AstArgument(index, min, max) {
  10923. AstNode.call(this, 'args');
  10924. this.index = index;
  10925. this.min = min;
  10926. this.max = max;
  10927. }
  10928. AstArgument.prototype = Object.create(AstNode.prototype);
  10929. AstArgument.prototype.visit = function (visitor) {
  10930. visitor.visitArgument(this);
  10931. };
  10932. function AstLiteral(number) {
  10933. AstNode.call(this, 'literal');
  10934. this.number = number;
  10935. this.min = number;
  10936. this.max = number;
  10937. }
  10938. AstLiteral.prototype = Object.create(AstNode.prototype);
  10939. AstLiteral.prototype.visit = function (visitor) {
  10940. visitor.visitLiteral(this);
  10941. };
  10942. function AstBinaryOperation(op, arg1, arg2, min, max) {
  10943. AstNode.call(this, 'binary');
  10944. this.op = op;
  10945. this.arg1 = arg1;
  10946. this.arg2 = arg2;
  10947. this.min = min;
  10948. this.max = max;
  10949. }
  10950. AstBinaryOperation.prototype = Object.create(AstNode.prototype);
  10951. AstBinaryOperation.prototype.visit = function (visitor) {
  10952. visitor.visitBinaryOperation(this);
  10953. };
  10954. function AstMin(arg, max) {
  10955. AstNode.call(this, 'max');
  10956. this.arg = arg;
  10957. this.min = arg.min;
  10958. this.max = max;
  10959. }
  10960. AstMin.prototype = Object.create(AstNode.prototype);
  10961. AstMin.prototype.visit = function (visitor) {
  10962. visitor.visitMin(this);
  10963. };
  10964. function AstVariable(index, min, max) {
  10965. AstNode.call(this, 'var');
  10966. this.index = index;
  10967. this.min = min;
  10968. this.max = max;
  10969. }
  10970. AstVariable.prototype = Object.create(AstNode.prototype);
  10971. AstVariable.prototype.visit = function (visitor) {
  10972. visitor.visitVariable(this);
  10973. };
  10974. function AstVariableDefinition(variable, arg) {
  10975. AstNode.call(this, 'definition');
  10976. this.variable = variable;
  10977. this.arg = arg;
  10978. }
  10979. AstVariableDefinition.prototype = Object.create(AstNode.prototype);
  10980. AstVariableDefinition.prototype.visit = function (visitor) {
  10981. visitor.visitVariableDefinition(this);
  10982. };
  10983. function ExpressionBuilderVisitor() {
  10984. this.parts = [];
  10985. }
  10986. ExpressionBuilderVisitor.prototype = {
  10987. visitArgument: function (arg) {
  10988. this.parts.push('Math.max(', arg.min, ', Math.min(',
  10989. arg.max, ', src[srcOffset + ', arg.index, ']))');
  10990. },
  10991. visitVariable: function (variable) {
  10992. this.parts.push('v', variable.index);
  10993. },
  10994. visitLiteral: function (literal) {
  10995. this.parts.push(literal.number);
  10996. },
  10997. visitBinaryOperation: function (operation) {
  10998. this.parts.push('(');
  10999. operation.arg1.visit(this);
  11000. this.parts.push(' ', operation.op, ' ');
  11001. operation.arg2.visit(this);
  11002. this.parts.push(')');
  11003. },
  11004. visitVariableDefinition: function (definition) {
  11005. this.parts.push('var ');
  11006. definition.variable.visit(this);
  11007. this.parts.push(' = ');
  11008. definition.arg.visit(this);
  11009. this.parts.push(';');
  11010. },
  11011. visitMin: function (max) {
  11012. this.parts.push('Math.min(');
  11013. max.arg.visit(this);
  11014. this.parts.push(', ', max.max, ')');
  11015. },
  11016. toString: function () {
  11017. return this.parts.join('');
  11018. }
  11019. };
  11020. function buildAddOperation(num1, num2) {
  11021. if (num2.type === 'literal' && num2.number === 0) {
  11022. // optimization: second operand is 0
  11023. return num1;
  11024. }
  11025. if (num1.type === 'literal' && num1.number === 0) {
  11026. // optimization: first operand is 0
  11027. return num2;
  11028. }
  11029. if (num2.type === 'literal' && num1.type === 'literal') {
  11030. // optimization: operands operand are literals
  11031. return new AstLiteral(num1.number + num2.number);
  11032. }
  11033. return new AstBinaryOperation('+', num1, num2,
  11034. num1.min + num2.min, num1.max + num2.max);
  11035. }
  11036. function buildMulOperation(num1, num2) {
  11037. if (num2.type === 'literal') {
  11038. // optimization: second operands is a literal...
  11039. if (num2.number === 0) {
  11040. return new AstLiteral(0); // and it's 0
  11041. } else if (num2.number === 1) {
  11042. return num1; // and it's 1
  11043. } else if (num1.type === 'literal') {
  11044. // ... and first operands is a literal too
  11045. return new AstLiteral(num1.number * num2.number);
  11046. }
  11047. }
  11048. if (num1.type === 'literal') {
  11049. // optimization: first operands is a literal...
  11050. if (num1.number === 0) {
  11051. return new AstLiteral(0); // and it's 0
  11052. } else if (num1.number === 1) {
  11053. return num2; // and it's 1
  11054. }
  11055. }
  11056. var min = Math.min(num1.min * num2.min, num1.min * num2.max,
  11057. num1.max * num2.min, num1.max * num2.max);
  11058. var max = Math.max(num1.min * num2.min, num1.min * num2.max,
  11059. num1.max * num2.min, num1.max * num2.max);
  11060. return new AstBinaryOperation('*', num1, num2, min, max);
  11061. }
  11062. function buildSubOperation(num1, num2) {
  11063. if (num2.type === 'literal') {
  11064. // optimization: second operands is a literal...
  11065. if (num2.number === 0) {
  11066. return num1; // ... and it's 0
  11067. } else if (num1.type === 'literal') {
  11068. // ... and first operands is a literal too
  11069. return new AstLiteral(num1.number - num2.number);
  11070. }
  11071. }
  11072. if (num2.type === 'binary' && num2.op === '-' &&
  11073. num1.type === 'literal' && num1.number === 1 &&
  11074. num2.arg1.type === 'literal' && num2.arg1.number === 1) {
  11075. // optimization for case: 1 - (1 - x)
  11076. return num2.arg2;
  11077. }
  11078. return new AstBinaryOperation('-', num1, num2,
  11079. num1.min - num2.max, num1.max - num2.min);
  11080. }
  11081. function buildMinOperation(num1, max) {
  11082. if (num1.min >= max) {
  11083. // optimization: num1 min value is not less than required max
  11084. return new AstLiteral(max); // just returning max
  11085. } else if (num1.max <= max) {
  11086. // optimization: num1 max value is not greater than required max
  11087. return num1; // just returning an argument
  11088. }
  11089. return new AstMin(num1, max);
  11090. }
  11091. function PostScriptCompiler() {}
  11092. PostScriptCompiler.prototype = {
  11093. compile: function PostScriptCompiler_compile(code, domain, range) {
  11094. var stack = [];
  11095. var i, ii;
  11096. var instructions = [];
  11097. var inputSize = domain.length >> 1, outputSize = range.length >> 1;
  11098. var lastRegister = 0;
  11099. var n, j, min, max;
  11100. var num1, num2, ast1, ast2, tmpVar, item;
  11101. for (i = 0; i < inputSize; i++) {
  11102. stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
  11103. }
  11104. for (i = 0, ii = code.length; i < ii; i++) {
  11105. item = code[i];
  11106. if (typeof item === 'number') {
  11107. stack.push(new AstLiteral(item));
  11108. continue;
  11109. }
  11110. switch (item) {
  11111. case 'add':
  11112. if (stack.length < 2) {
  11113. return null;
  11114. }
  11115. num2 = stack.pop();
  11116. num1 = stack.pop();
  11117. stack.push(buildAddOperation(num1, num2));
  11118. break;
  11119. case 'cvr':
  11120. if (stack.length < 1) {
  11121. return null;
  11122. }
  11123. break;
  11124. case 'mul':
  11125. if (stack.length < 2) {
  11126. return null;
  11127. }
  11128. num2 = stack.pop();
  11129. num1 = stack.pop();
  11130. stack.push(buildMulOperation(num1, num2));
  11131. break;
  11132. case 'sub':
  11133. if (stack.length < 2) {
  11134. return null;
  11135. }
  11136. num2 = stack.pop();
  11137. num1 = stack.pop();
  11138. stack.push(buildSubOperation(num1, num2));
  11139. break;
  11140. case 'exch':
  11141. if (stack.length < 2) {
  11142. return null;
  11143. }
  11144. ast1 = stack.pop(); ast2 = stack.pop();
  11145. stack.push(ast1, ast2);
  11146. break;
  11147. case 'pop':
  11148. if (stack.length < 1) {
  11149. return null;
  11150. }
  11151. stack.pop();
  11152. break;
  11153. case 'index':
  11154. if (stack.length < 1) {
  11155. return null;
  11156. }
  11157. num1 = stack.pop();
  11158. if (num1.type !== 'literal') {
  11159. return null;
  11160. }
  11161. n = num1.number;
  11162. if (n < 0 || (n|0) !== n || stack.length < n) {
  11163. return null;
  11164. }
  11165. ast1 = stack[stack.length - n - 1];
  11166. if (ast1.type === 'literal' || ast1.type === 'var') {
  11167. stack.push(ast1);
  11168. break;
  11169. }
  11170. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  11171. stack[stack.length - n - 1] = tmpVar;
  11172. stack.push(tmpVar);
  11173. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  11174. break;
  11175. case 'dup':
  11176. if (stack.length < 1) {
  11177. return null;
  11178. }
  11179. if (typeof code[i + 1] === 'number' && code[i + 2] === 'gt' &&
  11180. code[i + 3] === i + 7 && code[i + 4] === 'jz' &&
  11181. code[i + 5] === 'pop' && code[i + 6] === code[i + 1]) {
  11182. // special case of the commands sequence for the min operation
  11183. num1 = stack.pop();
  11184. stack.push(buildMinOperation(num1, code[i + 1]));
  11185. i += 6;
  11186. break;
  11187. }
  11188. ast1 = stack[stack.length - 1];
  11189. if (ast1.type === 'literal' || ast1.type === 'var') {
  11190. // we don't have to save into intermediate variable a literal or
  11191. // variable.
  11192. stack.push(ast1);
  11193. break;
  11194. }
  11195. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  11196. stack[stack.length - 1] = tmpVar;
  11197. stack.push(tmpVar);
  11198. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  11199. break;
  11200. case 'roll':
  11201. if (stack.length < 2) {
  11202. return null;
  11203. }
  11204. num2 = stack.pop();
  11205. num1 = stack.pop();
  11206. if (num2.type !== 'literal' || num1.type !== 'literal') {
  11207. // both roll operands must be numbers
  11208. return null;
  11209. }
  11210. j = num2.number;
  11211. n = num1.number;
  11212. if (n <= 0 || (n|0) !== n || (j|0) !== j || stack.length < n) {
  11213. // ... and integers
  11214. return null;
  11215. }
  11216. j = ((j % n) + n) % n;
  11217. if (j === 0) {
  11218. break; // just skipping -- there are nothing to rotate
  11219. }
  11220. Array.prototype.push.apply(stack,
  11221. stack.splice(stack.length - n, n - j));
  11222. break;
  11223. default:
  11224. return null; // unsupported operator
  11225. }
  11226. }
  11227. if (stack.length !== outputSize) {
  11228. return null;
  11229. }
  11230. var result = [];
  11231. instructions.forEach(function (instruction) {
  11232. var statementBuilder = new ExpressionBuilderVisitor();
  11233. instruction.visit(statementBuilder);
  11234. result.push(statementBuilder.toString());
  11235. });
  11236. stack.forEach(function (expr, i) {
  11237. var statementBuilder = new ExpressionBuilderVisitor();
  11238. expr.visit(statementBuilder);
  11239. var min = range[i * 2], max = range[i * 2 + 1];
  11240. var out = [statementBuilder.toString()];
  11241. if (min > expr.min) {
  11242. out.unshift('Math.max(', min, ', ');
  11243. out.push(')');
  11244. }
  11245. if (max < expr.max) {
  11246. out.unshift('Math.min(', max, ', ');
  11247. out.push(')');
  11248. }
  11249. out.unshift('dest[destOffset + ', i, '] = ');
  11250. out.push(';');
  11251. result.push(out.join(''));
  11252. });
  11253. return result.join('\n');
  11254. }
  11255. };
  11256. return PostScriptCompiler;
  11257. })();
  11258. var ColorSpace = (function ColorSpaceClosure() {
  11259. // Constructor should define this.numComps, this.defaultColor, this.name
  11260. function ColorSpace() {
  11261. error('should not call ColorSpace constructor');
  11262. }
  11263. ColorSpace.prototype = {
  11264. /**
  11265. * Converts the color value to the RGB color. The color components are
  11266. * located in the src array starting from the srcOffset. Returns the array
  11267. * of the rgb components, each value ranging from [0,255].
  11268. */
  11269. getRgb: function ColorSpace_getRgb(src, srcOffset) {
  11270. var rgb = new Uint8Array(3);
  11271. this.getRgbItem(src, srcOffset, rgb, 0);
  11272. return rgb;
  11273. },
  11274. /**
  11275. * Converts the color value to the RGB color, similar to the getRgb method.
  11276. * The result placed into the dest array starting from the destOffset.
  11277. */
  11278. getRgbItem: function ColorSpace_getRgbItem(src, srcOffset,
  11279. dest, destOffset) {
  11280. error('Should not call ColorSpace.getRgbItem');
  11281. },
  11282. /**
  11283. * Converts the specified number of the color values to the RGB colors.
  11284. * The colors are located in the src array starting from the srcOffset.
  11285. * The result is placed into the dest array starting from the destOffset.
  11286. * The src array items shall be in [0,2^bits) range, the dest array items
  11287. * will be in [0,255] range. alpha01 indicates how many alpha components
  11288. * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA
  11289. * array).
  11290. */
  11291. getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,
  11292. dest, destOffset, bits,
  11293. alpha01) {
  11294. error('Should not call ColorSpace.getRgbBuffer');
  11295. },
  11296. /**
  11297. * Determines the number of bytes required to store the result of the
  11298. * conversion done by the getRgbBuffer method. As in getRgbBuffer,
  11299. * |alpha01| is either 0 (RGB output) or 1 (RGBA output).
  11300. */
  11301. getOutputLength: function ColorSpace_getOutputLength(inputLength,
  11302. alpha01) {
  11303. error('Should not call ColorSpace.getOutputLength');
  11304. },
  11305. /**
  11306. * Returns true if source data will be equal the result/output data.
  11307. */
  11308. isPassthrough: function ColorSpace_isPassthrough(bits) {
  11309. return false;
  11310. },
  11311. /**
  11312. * Fills in the RGB colors in the destination buffer. alpha01 indicates
  11313. * how many alpha components there are in the dest array; it will be either
  11314. * 0 (RGB array) or 1 (RGBA array).
  11315. */
  11316. fillRgb: function ColorSpace_fillRgb(dest, originalWidth,
  11317. originalHeight, width, height,
  11318. actualHeight, bpc, comps, alpha01) {
  11319. var count = originalWidth * originalHeight;
  11320. var rgbBuf = null;
  11321. var numComponentColors = 1 << bpc;
  11322. var needsResizing = originalHeight !== height || originalWidth !== width;
  11323. var i, ii;
  11324. if (this.isPassthrough(bpc)) {
  11325. rgbBuf = comps;
  11326. } else if (this.numComps === 1 && count > numComponentColors &&
  11327. this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {
  11328. // Optimization: create a color map when there is just one component and
  11329. // we are converting more colors than the size of the color map. We
  11330. // don't build the map if the colorspace is gray or rgb since those
  11331. // methods are faster than building a map. This mainly offers big speed
  11332. // ups for indexed and alternate colorspaces.
  11333. //
  11334. // TODO it may be worth while to cache the color map. While running
  11335. // testing I never hit a cache so I will leave that out for now (perhaps
  11336. // we are reparsing colorspaces too much?).
  11337. var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) :
  11338. new Uint16Array(numComponentColors);
  11339. var key;
  11340. for (i = 0; i < numComponentColors; i++) {
  11341. allColors[i] = i;
  11342. }
  11343. var colorMap = new Uint8Array(numComponentColors * 3);
  11344. this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,
  11345. /* alpha01 = */ 0);
  11346. var destPos, rgbPos;
  11347. if (!needsResizing) {
  11348. // Fill in the RGB values directly into |dest|.
  11349. destPos = 0;
  11350. for (i = 0; i < count; ++i) {
  11351. key = comps[i] * 3;
  11352. dest[destPos++] = colorMap[key];
  11353. dest[destPos++] = colorMap[key + 1];
  11354. dest[destPos++] = colorMap[key + 2];
  11355. destPos += alpha01;
  11356. }
  11357. } else {
  11358. rgbBuf = new Uint8Array(count * 3);
  11359. rgbPos = 0;
  11360. for (i = 0; i < count; ++i) {
  11361. key = comps[i] * 3;
  11362. rgbBuf[rgbPos++] = colorMap[key];
  11363. rgbBuf[rgbPos++] = colorMap[key + 1];
  11364. rgbBuf[rgbPos++] = colorMap[key + 2];
  11365. }
  11366. }
  11367. } else {
  11368. if (!needsResizing) {
  11369. // Fill in the RGB values directly into |dest|.
  11370. this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc,
  11371. alpha01);
  11372. } else {
  11373. rgbBuf = new Uint8Array(count * 3);
  11374. this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc,
  11375. /* alpha01 = */ 0);
  11376. }
  11377. }
  11378. if (rgbBuf) {
  11379. if (needsResizing) {
  11380. PDFImage.resize(rgbBuf, bpc, 3, originalWidth, originalHeight, width,
  11381. height, dest, alpha01);
  11382. } else {
  11383. rgbPos = 0;
  11384. destPos = 0;
  11385. for (i = 0, ii = width * actualHeight; i < ii; i++) {
  11386. dest[destPos++] = rgbBuf[rgbPos++];
  11387. dest[destPos++] = rgbBuf[rgbPos++];
  11388. dest[destPos++] = rgbBuf[rgbPos++];
  11389. destPos += alpha01;
  11390. }
  11391. }
  11392. }
  11393. },
  11394. /**
  11395. * True if the colorspace has components in the default range of [0, 1].
  11396. * This should be true for all colorspaces except for lab color spaces
  11397. * which are [0,100], [-128, 127], [-128, 127].
  11398. */
  11399. usesZeroToOneRange: true
  11400. };
  11401. ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {
  11402. var IR = ColorSpace.parseToIR(cs, xref, res);
  11403. if (IR instanceof AlternateCS) {
  11404. return IR;
  11405. }
  11406. return ColorSpace.fromIR(IR);
  11407. };
  11408. ColorSpace.fromIR = function ColorSpace_fromIR(IR) {
  11409. var name = isArray(IR) ? IR[0] : IR;
  11410. var whitePoint, blackPoint, gamma;
  11411. switch (name) {
  11412. case 'DeviceGrayCS':
  11413. return this.singletons.gray;
  11414. case 'DeviceRgbCS':
  11415. return this.singletons.rgb;
  11416. case 'DeviceCmykCS':
  11417. return this.singletons.cmyk;
  11418. case 'CalGrayCS':
  11419. whitePoint = IR[1].WhitePoint;
  11420. blackPoint = IR[1].BlackPoint;
  11421. gamma = IR[1].Gamma;
  11422. return new CalGrayCS(whitePoint, blackPoint, gamma);
  11423. case 'CalRGBCS':
  11424. whitePoint = IR[1].WhitePoint;
  11425. blackPoint = IR[1].BlackPoint;
  11426. gamma = IR[1].Gamma;
  11427. var matrix = IR[1].Matrix;
  11428. return new CalRGBCS(whitePoint, blackPoint, gamma, matrix);
  11429. case 'PatternCS':
  11430. var basePatternCS = IR[1];
  11431. if (basePatternCS) {
  11432. basePatternCS = ColorSpace.fromIR(basePatternCS);
  11433. }
  11434. return new PatternCS(basePatternCS);
  11435. case 'IndexedCS':
  11436. var baseIndexedCS = IR[1];
  11437. var hiVal = IR[2];
  11438. var lookup = IR[3];
  11439. return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);
  11440. case 'AlternateCS':
  11441. var numComps = IR[1];
  11442. var alt = IR[2];
  11443. var tintFnIR = IR[3];
  11444. return new AlternateCS(numComps, ColorSpace.fromIR(alt),
  11445. PDFFunction.fromIR(tintFnIR));
  11446. case 'LabCS':
  11447. whitePoint = IR[1].WhitePoint;
  11448. blackPoint = IR[1].BlackPoint;
  11449. var range = IR[1].Range;
  11450. return new LabCS(whitePoint, blackPoint, range);
  11451. default:
  11452. error('Unknown name ' + name);
  11453. }
  11454. return null;
  11455. };
  11456. ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
  11457. if (isName(cs)) {
  11458. var colorSpaces = res.get('ColorSpace');
  11459. if (isDict(colorSpaces)) {
  11460. var refcs = colorSpaces.get(cs.name);
  11461. if (refcs) {
  11462. cs = refcs;
  11463. }
  11464. }
  11465. }
  11466. cs = xref.fetchIfRef(cs);
  11467. var mode;
  11468. if (isName(cs)) {
  11469. mode = cs.name;
  11470. this.mode = mode;
  11471. switch (mode) {
  11472. case 'DeviceGray':
  11473. case 'G':
  11474. return 'DeviceGrayCS';
  11475. case 'DeviceRGB':
  11476. case 'RGB':
  11477. return 'DeviceRgbCS';
  11478. case 'DeviceCMYK':
  11479. case 'CMYK':
  11480. return 'DeviceCmykCS';
  11481. case 'Pattern':
  11482. return ['PatternCS', null];
  11483. default:
  11484. error('unrecognized colorspace ' + mode);
  11485. }
  11486. } else if (isArray(cs)) {
  11487. mode = cs[0].name;
  11488. this.mode = mode;
  11489. var numComps, params;
  11490. switch (mode) {
  11491. case 'DeviceGray':
  11492. case 'G':
  11493. return 'DeviceGrayCS';
  11494. case 'DeviceRGB':
  11495. case 'RGB':
  11496. return 'DeviceRgbCS';
  11497. case 'DeviceCMYK':
  11498. case 'CMYK':
  11499. return 'DeviceCmykCS';
  11500. case 'CalGray':
  11501. params = cs[1].getAll();
  11502. return ['CalGrayCS', params];
  11503. case 'CalRGB':
  11504. params = cs[1].getAll();
  11505. return ['CalRGBCS', params];
  11506. case 'ICCBased':
  11507. var stream = xref.fetchIfRef(cs[1]);
  11508. var dict = stream.dict;
  11509. numComps = dict.get('N');
  11510. if (numComps === 1) {
  11511. return 'DeviceGrayCS';
  11512. } else if (numComps === 3) {
  11513. return 'DeviceRgbCS';
  11514. } else if (numComps === 4) {
  11515. return 'DeviceCmykCS';
  11516. }
  11517. break;
  11518. case 'Pattern':
  11519. var basePatternCS = cs[1];
  11520. if (basePatternCS) {
  11521. basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);
  11522. }
  11523. return ['PatternCS', basePatternCS];
  11524. case 'Indexed':
  11525. case 'I':
  11526. var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);
  11527. var hiVal = cs[2] + 1;
  11528. var lookup = xref.fetchIfRef(cs[3]);
  11529. if (isStream(lookup)) {
  11530. lookup = lookup.getBytes();
  11531. }
  11532. return ['IndexedCS', baseIndexedCS, hiVal, lookup];
  11533. case 'Separation':
  11534. case 'DeviceN':
  11535. var name = cs[1];
  11536. numComps = 1;
  11537. if (isName(name)) {
  11538. numComps = 1;
  11539. } else if (isArray(name)) {
  11540. numComps = name.length;
  11541. }
  11542. var alt = ColorSpace.parseToIR(cs[2], xref, res);
  11543. var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));
  11544. return ['AlternateCS', numComps, alt, tintFnIR];
  11545. case 'Lab':
  11546. params = cs[1].getAll();
  11547. return ['LabCS', params];
  11548. default:
  11549. error('unimplemented color space object "' + mode + '"');
  11550. }
  11551. } else {
  11552. error('unrecognized color space object: "' + cs + '"');
  11553. }
  11554. return null;
  11555. };
  11556. /**
  11557. * Checks if a decode map matches the default decode map for a color space.
  11558. * This handles the general decode maps where there are two values per
  11559. * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color.
  11560. * This does not handle Lab, Indexed, or Pattern decode maps since they are
  11561. * slightly different.
  11562. * @param {Array} decode Decode map (usually from an image).
  11563. * @param {Number} n Number of components the color space has.
  11564. */
  11565. ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {
  11566. if (!decode) {
  11567. return true;
  11568. }
  11569. if (n * 2 !== decode.length) {
  11570. warn('The decode map is not the correct length');
  11571. return true;
  11572. }
  11573. for (var i = 0, ii = decode.length; i < ii; i += 2) {
  11574. if (decode[i] !== 0 || decode[i + 1] !== 1) {
  11575. return false;
  11576. }
  11577. }
  11578. return true;
  11579. };
  11580. ColorSpace.singletons = {
  11581. get gray() {
  11582. return shadow(this, 'gray', new DeviceGrayCS());
  11583. },
  11584. get rgb() {
  11585. return shadow(this, 'rgb', new DeviceRgbCS());
  11586. },
  11587. get cmyk() {
  11588. return shadow(this, 'cmyk', new DeviceCmykCS());
  11589. }
  11590. };
  11591. return ColorSpace;
  11592. })();
  11593. /**
  11594. * Alternate color space handles both Separation and DeviceN color spaces. A
  11595. * Separation color space is actually just a DeviceN with one color component.
  11596. * Both color spaces use a tinting function to convert colors to a base color
  11597. * space.
  11598. */
  11599. var AlternateCS = (function AlternateCSClosure() {
  11600. function AlternateCS(numComps, base, tintFn) {
  11601. this.name = 'Alternate';
  11602. this.numComps = numComps;
  11603. this.defaultColor = new Float32Array(numComps);
  11604. for (var i = 0; i < numComps; ++i) {
  11605. this.defaultColor[i] = 1;
  11606. }
  11607. this.base = base;
  11608. this.tintFn = tintFn;
  11609. this.tmpBuf = new Float32Array(base.numComps);
  11610. }
  11611. AlternateCS.prototype = {
  11612. getRgb: ColorSpace.prototype.getRgb,
  11613. getRgbItem: function AlternateCS_getRgbItem(src, srcOffset,
  11614. dest, destOffset) {
  11615. var tmpBuf = this.tmpBuf;
  11616. this.tintFn(src, srcOffset, tmpBuf, 0);
  11617. this.base.getRgbItem(tmpBuf, 0, dest, destOffset);
  11618. },
  11619. getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count,
  11620. dest, destOffset, bits,
  11621. alpha01) {
  11622. var tintFn = this.tintFn;
  11623. var base = this.base;
  11624. var scale = 1 / ((1 << bits) - 1);
  11625. var baseNumComps = base.numComps;
  11626. var usesZeroToOneRange = base.usesZeroToOneRange;
  11627. var isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) &&
  11628. alpha01 === 0;
  11629. var pos = isPassthrough ? destOffset : 0;
  11630. var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count);
  11631. var numComps = this.numComps;
  11632. var scaled = new Float32Array(numComps);
  11633. var tinted = new Float32Array(baseNumComps);
  11634. var i, j;
  11635. if (usesZeroToOneRange) {
  11636. for (i = 0; i < count; i++) {
  11637. for (j = 0; j < numComps; j++) {
  11638. scaled[j] = src[srcOffset++] * scale;
  11639. }
  11640. tintFn(scaled, 0, tinted, 0);
  11641. for (j = 0; j < baseNumComps; j++) {
  11642. baseBuf[pos++] = tinted[j] * 255;
  11643. }
  11644. }
  11645. } else {
  11646. for (i = 0; i < count; i++) {
  11647. for (j = 0; j < numComps; j++) {
  11648. scaled[j] = src[srcOffset++] * scale;
  11649. }
  11650. tintFn(scaled, 0, tinted, 0);
  11651. base.getRgbItem(tinted, 0, baseBuf, pos);
  11652. pos += baseNumComps;
  11653. }
  11654. }
  11655. if (!isPassthrough) {
  11656. base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
  11657. }
  11658. },
  11659. getOutputLength: function AlternateCS_getOutputLength(inputLength,
  11660. alpha01) {
  11661. return this.base.getOutputLength(inputLength *
  11662. this.base.numComps / this.numComps,
  11663. alpha01);
  11664. },
  11665. isPassthrough: ColorSpace.prototype.isPassthrough,
  11666. fillRgb: ColorSpace.prototype.fillRgb,
  11667. isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {
  11668. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  11669. },
  11670. usesZeroToOneRange: true
  11671. };
  11672. return AlternateCS;
  11673. })();
  11674. var PatternCS = (function PatternCSClosure() {
  11675. function PatternCS(baseCS) {
  11676. this.name = 'Pattern';
  11677. this.base = baseCS;
  11678. }
  11679. PatternCS.prototype = {};
  11680. return PatternCS;
  11681. })();
  11682. var IndexedCS = (function IndexedCSClosure() {
  11683. function IndexedCS(base, highVal, lookup) {
  11684. this.name = 'Indexed';
  11685. this.numComps = 1;
  11686. this.defaultColor = new Uint8Array([0]);
  11687. this.base = base;
  11688. this.highVal = highVal;
  11689. var baseNumComps = base.numComps;
  11690. var length = baseNumComps * highVal;
  11691. var lookupArray;
  11692. if (isStream(lookup)) {
  11693. lookupArray = new Uint8Array(length);
  11694. var bytes = lookup.getBytes(length);
  11695. lookupArray.set(bytes);
  11696. } else if (isString(lookup)) {
  11697. lookupArray = new Uint8Array(length);
  11698. for (var i = 0; i < length; ++i) {
  11699. lookupArray[i] = lookup.charCodeAt(i);
  11700. }
  11701. } else if (lookup instanceof Uint8Array || lookup instanceof Array) {
  11702. lookupArray = lookup;
  11703. } else {
  11704. error('Unrecognized lookup table: ' + lookup);
  11705. }
  11706. this.lookup = lookupArray;
  11707. }
  11708. IndexedCS.prototype = {
  11709. getRgb: ColorSpace.prototype.getRgb,
  11710. getRgbItem: function IndexedCS_getRgbItem(src, srcOffset,
  11711. dest, destOffset) {
  11712. var numComps = this.base.numComps;
  11713. var start = src[srcOffset] * numComps;
  11714. this.base.getRgbItem(this.lookup, start, dest, destOffset);
  11715. },
  11716. getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count,
  11717. dest, destOffset, bits,
  11718. alpha01) {
  11719. var base = this.base;
  11720. var numComps = base.numComps;
  11721. var outputDelta = base.getOutputLength(numComps, alpha01);
  11722. var lookup = this.lookup;
  11723. for (var i = 0; i < count; ++i) {
  11724. var lookupPos = src[srcOffset++] * numComps;
  11725. base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);
  11726. destOffset += outputDelta;
  11727. }
  11728. },
  11729. getOutputLength: function IndexedCS_getOutputLength(inputLength, alpha01) {
  11730. return this.base.getOutputLength(inputLength * this.base.numComps,
  11731. alpha01);
  11732. },
  11733. isPassthrough: ColorSpace.prototype.isPassthrough,
  11734. fillRgb: ColorSpace.prototype.fillRgb,
  11735. isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {
  11736. // indexed color maps shouldn't be changed
  11737. return true;
  11738. },
  11739. usesZeroToOneRange: true
  11740. };
  11741. return IndexedCS;
  11742. })();
  11743. var DeviceGrayCS = (function DeviceGrayCSClosure() {
  11744. function DeviceGrayCS() {
  11745. this.name = 'DeviceGray';
  11746. this.numComps = 1;
  11747. this.defaultColor = new Float32Array([0]);
  11748. }
  11749. DeviceGrayCS.prototype = {
  11750. getRgb: ColorSpace.prototype.getRgb,
  11751. getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset,
  11752. dest, destOffset) {
  11753. var c = (src[srcOffset] * 255) | 0;
  11754. c = c < 0 ? 0 : c > 255 ? 255 : c;
  11755. dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;
  11756. },
  11757. getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count,
  11758. dest, destOffset, bits,
  11759. alpha01) {
  11760. var scale = 255 / ((1 << bits) - 1);
  11761. var j = srcOffset, q = destOffset;
  11762. for (var i = 0; i < count; ++i) {
  11763. var c = (scale * src[j++]) | 0;
  11764. dest[q++] = c;
  11765. dest[q++] = c;
  11766. dest[q++] = c;
  11767. q += alpha01;
  11768. }
  11769. },
  11770. getOutputLength: function DeviceGrayCS_getOutputLength(inputLength,
  11771. alpha01) {
  11772. return inputLength * (3 + alpha01);
  11773. },
  11774. isPassthrough: ColorSpace.prototype.isPassthrough,
  11775. fillRgb: ColorSpace.prototype.fillRgb,
  11776. isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {
  11777. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  11778. },
  11779. usesZeroToOneRange: true
  11780. };
  11781. return DeviceGrayCS;
  11782. })();
  11783. var DeviceRgbCS = (function DeviceRgbCSClosure() {
  11784. function DeviceRgbCS() {
  11785. this.name = 'DeviceRGB';
  11786. this.numComps = 3;
  11787. this.defaultColor = new Float32Array([0, 0, 0]);
  11788. }
  11789. DeviceRgbCS.prototype = {
  11790. getRgb: ColorSpace.prototype.getRgb,
  11791. getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset,
  11792. dest, destOffset) {
  11793. var r = (src[srcOffset] * 255) | 0;
  11794. var g = (src[srcOffset + 1] * 255) | 0;
  11795. var b = (src[srcOffset + 2] * 255) | 0;
  11796. dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r;
  11797. dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g;
  11798. dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b;
  11799. },
  11800. getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count,
  11801. dest, destOffset, bits,
  11802. alpha01) {
  11803. if (bits === 8 && alpha01 === 0) {
  11804. dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);
  11805. return;
  11806. }
  11807. var scale = 255 / ((1 << bits) - 1);
  11808. var j = srcOffset, q = destOffset;
  11809. for (var i = 0; i < count; ++i) {
  11810. dest[q++] = (scale * src[j++]) | 0;
  11811. dest[q++] = (scale * src[j++]) | 0;
  11812. dest[q++] = (scale * src[j++]) | 0;
  11813. q += alpha01;
  11814. }
  11815. },
  11816. getOutputLength: function DeviceRgbCS_getOutputLength(inputLength,
  11817. alpha01) {
  11818. return (inputLength * (3 + alpha01) / 3) | 0;
  11819. },
  11820. isPassthrough: function DeviceRgbCS_isPassthrough(bits) {
  11821. return bits === 8;
  11822. },
  11823. fillRgb: ColorSpace.prototype.fillRgb,
  11824. isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {
  11825. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  11826. },
  11827. usesZeroToOneRange: true
  11828. };
  11829. return DeviceRgbCS;
  11830. })();
  11831. var DeviceCmykCS = (function DeviceCmykCSClosure() {
  11832. // The coefficients below was found using numerical analysis: the method of
  11833. // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,
  11834. // where color_value is the tabular value from the table of sampled RGB colors
  11835. // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding
  11836. // CMYK color conversion using the estimation below:
  11837. // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255
  11838. function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {
  11839. var c = src[srcOffset + 0] * srcScale;
  11840. var m = src[srcOffset + 1] * srcScale;
  11841. var y = src[srcOffset + 2] * srcScale;
  11842. var k = src[srcOffset + 3] * srcScale;
  11843. var r =
  11844. (c * (-4.387332384609988 * c + 54.48615194189176 * m +
  11845. 18.82290502165302 * y + 212.25662451639585 * k +
  11846. -285.2331026137004) +
  11847. m * (1.7149763477362134 * m - 5.6096736904047315 * y +
  11848. -17.873870861415444 * k - 5.497006427196366) +
  11849. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  11850. 17.5119270841813) +
  11851. k * (-21.86122147463605 * k - 189.48180835922747) + 255) | 0;
  11852. var g =
  11853. (c * (8.841041422036149 * c + 60.118027045597366 * m +
  11854. 6.871425592049007 * y + 31.159100130055922 * k +
  11855. -79.2970844816548) +
  11856. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  11857. 131.35250912493976 * k - 190.9453302588951) +
  11858. y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +
  11859. k * (-20.737325471181034 * k - 187.80453709719578) + 255) | 0;
  11860. var b =
  11861. (c * (0.8842522430003296 * c + 8.078677503112928 * m +
  11862. 30.89978309703729 * y - 0.23883238689178934 * k +
  11863. -14.183576799673286) +
  11864. m * (10.49593273432072 * m + 63.02378494754052 * y +
  11865. 50.606957656360734 * k - 112.23884253719248) +
  11866. y * (0.03296041114873217 * y + 115.60384449646641 * k +
  11867. -193.58209356861505) +
  11868. k * (-22.33816807309886 * k - 180.12613974708367) + 255) | 0;
  11869. dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r;
  11870. dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;
  11871. dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;
  11872. }
  11873. function DeviceCmykCS() {
  11874. this.name = 'DeviceCMYK';
  11875. this.numComps = 4;
  11876. this.defaultColor = new Float32Array([0, 0, 0, 1]);
  11877. }
  11878. DeviceCmykCS.prototype = {
  11879. getRgb: ColorSpace.prototype.getRgb,
  11880. getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset,
  11881. dest, destOffset) {
  11882. convertToRgb(src, srcOffset, 1, dest, destOffset);
  11883. },
  11884. getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count,
  11885. dest, destOffset, bits,
  11886. alpha01) {
  11887. var scale = 1 / ((1 << bits) - 1);
  11888. for (var i = 0; i < count; i++) {
  11889. convertToRgb(src, srcOffset, scale, dest, destOffset);
  11890. srcOffset += 4;
  11891. destOffset += 3 + alpha01;
  11892. }
  11893. },
  11894. getOutputLength: function DeviceCmykCS_getOutputLength(inputLength,
  11895. alpha01) {
  11896. return (inputLength / 4 * (3 + alpha01)) | 0;
  11897. },
  11898. isPassthrough: ColorSpace.prototype.isPassthrough,
  11899. fillRgb: ColorSpace.prototype.fillRgb,
  11900. isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {
  11901. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  11902. },
  11903. usesZeroToOneRange: true
  11904. };
  11905. return DeviceCmykCS;
  11906. })();
  11907. //
  11908. // CalGrayCS: Based on "PDF Reference, Sixth Ed", p.245
  11909. //
  11910. var CalGrayCS = (function CalGrayCSClosure() {
  11911. function CalGrayCS(whitePoint, blackPoint, gamma) {
  11912. this.name = 'CalGray';
  11913. this.numComps = 1;
  11914. this.defaultColor = new Float32Array([0]);
  11915. if (!whitePoint) {
  11916. error('WhitePoint missing - required for color space CalGray');
  11917. }
  11918. blackPoint = blackPoint || [0, 0, 0];
  11919. gamma = gamma || 1;
  11920. // Translate arguments to spec variables.
  11921. this.XW = whitePoint[0];
  11922. this.YW = whitePoint[1];
  11923. this.ZW = whitePoint[2];
  11924. this.XB = blackPoint[0];
  11925. this.YB = blackPoint[1];
  11926. this.ZB = blackPoint[2];
  11927. this.G = gamma;
  11928. // Validate variables as per spec.
  11929. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  11930. error('Invalid WhitePoint components for ' + this.name +
  11931. ', no fallback available');
  11932. }
  11933. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  11934. info('Invalid BlackPoint for ' + this.name + ', falling back to default');
  11935. this.XB = this.YB = this.ZB = 0;
  11936. }
  11937. if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
  11938. warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB +
  11939. ', ZB: ' + this.ZB + ', only default values are supported.');
  11940. }
  11941. if (this.G < 1) {
  11942. info('Invalid Gamma: ' + this.G + ' for ' + this.name +
  11943. ', falling back to default');
  11944. this.G = 1;
  11945. }
  11946. }
  11947. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  11948. // A represents a gray component of a calibrated gray space.
  11949. // A <---> AG in the spec
  11950. var A = src[srcOffset] * scale;
  11951. var AG = Math.pow(A, cs.G);
  11952. // Computes L as per spec. ( = cs.YW * AG )
  11953. // Except if other than default BlackPoint values are used.
  11954. var L = cs.YW * AG;
  11955. // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4.
  11956. // Convert values to rgb range [0, 255].
  11957. var val = Math.max(295.8 * Math.pow(L, 0.333333333333333333) - 40.8, 0) | 0;
  11958. dest[destOffset] = val;
  11959. dest[destOffset + 1] = val;
  11960. dest[destOffset + 2] = val;
  11961. }
  11962. CalGrayCS.prototype = {
  11963. getRgb: ColorSpace.prototype.getRgb,
  11964. getRgbItem: function CalGrayCS_getRgbItem(src, srcOffset,
  11965. dest, destOffset) {
  11966. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  11967. },
  11968. getRgbBuffer: function CalGrayCS_getRgbBuffer(src, srcOffset, count,
  11969. dest, destOffset, bits,
  11970. alpha01) {
  11971. var scale = 1 / ((1 << bits) - 1);
  11972. for (var i = 0; i < count; ++i) {
  11973. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  11974. srcOffset += 1;
  11975. destOffset += 3 + alpha01;
  11976. }
  11977. },
  11978. getOutputLength: function CalGrayCS_getOutputLength(inputLength, alpha01) {
  11979. return inputLength * (3 + alpha01);
  11980. },
  11981. isPassthrough: ColorSpace.prototype.isPassthrough,
  11982. fillRgb: ColorSpace.prototype.fillRgb,
  11983. isDefaultDecode: function CalGrayCS_isDefaultDecode(decodeMap) {
  11984. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  11985. },
  11986. usesZeroToOneRange: true
  11987. };
  11988. return CalGrayCS;
  11989. })();
  11990. //
  11991. // CalRGBCS: Based on "PDF Reference, Sixth Ed", p.247
  11992. //
  11993. var CalRGBCS = (function CalRGBCSClosure() {
  11994. // See http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html for these
  11995. // matrices.
  11996. var BRADFORD_SCALE_MATRIX = new Float32Array([
  11997. 0.8951, 0.2664, -0.1614,
  11998. -0.7502, 1.7135, 0.0367,
  11999. 0.0389, -0.0685, 1.0296]);
  12000. var BRADFORD_SCALE_INVERSE_MATRIX = new Float32Array([
  12001. 0.9869929, -0.1470543, 0.1599627,
  12002. 0.4323053, 0.5183603, 0.0492912,
  12003. -0.0085287, 0.0400428, 0.9684867]);
  12004. // See http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html.
  12005. var SRGB_D65_XYZ_TO_RGB_MATRIX = new Float32Array([
  12006. 3.2404542, -1.5371385, -0.4985314,
  12007. -0.9692660, 1.8760108, 0.0415560,
  12008. 0.0556434, -0.2040259, 1.0572252]);
  12009. var FLAT_WHITEPOINT_MATRIX = new Float32Array([1, 1, 1]);
  12010. var tempNormalizeMatrix = new Float32Array(3);
  12011. var tempConvertMatrix1 = new Float32Array(3);
  12012. var tempConvertMatrix2 = new Float32Array(3);
  12013. var DECODE_L_CONSTANT = Math.pow(((8 + 16) / 116), 3) / 8.0;
  12014. function CalRGBCS(whitePoint, blackPoint, gamma, matrix) {
  12015. this.name = 'CalRGB';
  12016. this.numComps = 3;
  12017. this.defaultColor = new Float32Array(3);
  12018. if (!whitePoint) {
  12019. error('WhitePoint missing - required for color space CalRGB');
  12020. }
  12021. blackPoint = blackPoint || new Float32Array(3);
  12022. gamma = gamma || new Float32Array([1, 1, 1]);
  12023. matrix = matrix || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  12024. // Translate arguments to spec variables.
  12025. var XW = whitePoint[0];
  12026. var YW = whitePoint[1];
  12027. var ZW = whitePoint[2];
  12028. this.whitePoint = whitePoint;
  12029. var XB = blackPoint[0];
  12030. var YB = blackPoint[1];
  12031. var ZB = blackPoint[2];
  12032. this.blackPoint = blackPoint;
  12033. this.GR = gamma[0];
  12034. this.GG = gamma[1];
  12035. this.GB = gamma[2];
  12036. this.MXA = matrix[0];
  12037. this.MYA = matrix[1];
  12038. this.MZA = matrix[2];
  12039. this.MXB = matrix[3];
  12040. this.MYB = matrix[4];
  12041. this.MZB = matrix[5];
  12042. this.MXC = matrix[6];
  12043. this.MYC = matrix[7];
  12044. this.MZC = matrix[8];
  12045. // Validate variables as per spec.
  12046. if (XW < 0 || ZW < 0 || YW !== 1) {
  12047. error('Invalid WhitePoint components for ' + this.name +
  12048. ', no fallback available');
  12049. }
  12050. if (XB < 0 || YB < 0 || ZB < 0) {
  12051. info('Invalid BlackPoint for ' + this.name + ' [' + XB + ', ' + YB +
  12052. ', ' + ZB + '], falling back to default');
  12053. this.blackPoint = new Float32Array(3);
  12054. }
  12055. if (this.GR < 0 || this.GG < 0 || this.GB < 0) {
  12056. info('Invalid Gamma [' + this.GR + ', ' + this.GG + ', ' + this.GB +
  12057. '] for ' + this.name + ', falling back to default');
  12058. this.GR = this.GG = this.GB = 1;
  12059. }
  12060. if (this.MXA < 0 || this.MYA < 0 || this.MZA < 0 ||
  12061. this.MXB < 0 || this.MYB < 0 || this.MZB < 0 ||
  12062. this.MXC < 0 || this.MYC < 0 || this.MZC < 0) {
  12063. info('Invalid Matrix for ' + this.name + ' [' +
  12064. this.MXA + ', ' + this.MYA + ', ' + this.MZA +
  12065. this.MXB + ', ' + this.MYB + ', ' + this.MZB +
  12066. this.MXC + ', ' + this.MYC + ', ' + this.MZC +
  12067. '], falling back to default');
  12068. this.MXA = this.MYB = this.MZC = 1;
  12069. this.MXB = this.MYA = this.MZA = this.MXC = this.MYC = this.MZB = 0;
  12070. }
  12071. }
  12072. function matrixProduct(a, b, result) {
  12073. result[0] = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  12074. result[1] = a[3] * b[0] + a[4] * b[1] + a[5] * b[2];
  12075. result[2] = a[6] * b[0] + a[7] * b[1] + a[8] * b[2];
  12076. }
  12077. function convertToFlat(sourceWhitePoint, LMS, result) {
  12078. result[0] = LMS[0] * 1 / sourceWhitePoint[0];
  12079. result[1] = LMS[1] * 1 / sourceWhitePoint[1];
  12080. result[2] = LMS[2] * 1 / sourceWhitePoint[2];
  12081. }
  12082. function convertToD65(sourceWhitePoint, LMS, result) {
  12083. var D65X = 0.95047;
  12084. var D65Y = 1;
  12085. var D65Z = 1.08883;
  12086. result[0] = LMS[0] * D65X / sourceWhitePoint[0];
  12087. result[1] = LMS[1] * D65Y / sourceWhitePoint[1];
  12088. result[2] = LMS[2] * D65Z / sourceWhitePoint[2];
  12089. }
  12090. function sRGBTransferFunction(color) {
  12091. // See http://en.wikipedia.org/wiki/SRGB.
  12092. if (color <= 0.0031308){
  12093. return adjustToRange(0, 1, 12.92 * color);
  12094. }
  12095. return adjustToRange(0, 1, (1 + 0.055) * Math.pow(color, 1 / 2.4) - 0.055);
  12096. }
  12097. function adjustToRange(min, max, value) {
  12098. return Math.max(min, Math.min(max, value));
  12099. }
  12100. function decodeL(L) {
  12101. if (L < 0) {
  12102. return -decodeL(-L);
  12103. }
  12104. if (L > 8.0) {
  12105. return Math.pow(((L + 16) / 116), 3);
  12106. }
  12107. return L * DECODE_L_CONSTANT;
  12108. }
  12109. function compensateBlackPoint(sourceBlackPoint, XYZ_Flat, result) {
  12110. // In case the blackPoint is already the default blackPoint then there is
  12111. // no need to do compensation.
  12112. if (sourceBlackPoint[0] === 0 &&
  12113. sourceBlackPoint[1] === 0 &&
  12114. sourceBlackPoint[2] === 0) {
  12115. result[0] = XYZ_Flat[0];
  12116. result[1] = XYZ_Flat[1];
  12117. result[2] = XYZ_Flat[2];
  12118. return;
  12119. }
  12120. // For the blackPoint calculation details, please see
  12121. // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
  12122. // AdobeBPC.pdf.
  12123. // The destination blackPoint is the default blackPoint [0, 0, 0].
  12124. var zeroDecodeL = decodeL(0);
  12125. var X_DST = zeroDecodeL;
  12126. var X_SRC = decodeL(sourceBlackPoint[0]);
  12127. var Y_DST = zeroDecodeL;
  12128. var Y_SRC = decodeL(sourceBlackPoint[1]);
  12129. var Z_DST = zeroDecodeL;
  12130. var Z_SRC = decodeL(sourceBlackPoint[2]);
  12131. var X_Scale = (1 - X_DST) / (1 - X_SRC);
  12132. var X_Offset = 1 - X_Scale;
  12133. var Y_Scale = (1 - Y_DST) / (1 - Y_SRC);
  12134. var Y_Offset = 1 - Y_Scale;
  12135. var Z_Scale = (1 - Z_DST) / (1 - Z_SRC);
  12136. var Z_Offset = 1 - Z_Scale;
  12137. result[0] = XYZ_Flat[0] * X_Scale + X_Offset;
  12138. result[1] = XYZ_Flat[1] * Y_Scale + Y_Offset;
  12139. result[2] = XYZ_Flat[2] * Z_Scale + Z_Offset;
  12140. }
  12141. function normalizeWhitePointToFlat(sourceWhitePoint, XYZ_In, result) {
  12142. // In case the whitePoint is already flat then there is no need to do
  12143. // normalization.
  12144. if (sourceWhitePoint[0] === 1 && sourceWhitePoint[2] === 1) {
  12145. result[0] = XYZ_In[0];
  12146. result[1] = XYZ_In[1];
  12147. result[2] = XYZ_In[2];
  12148. return;
  12149. }
  12150. var LMS = result;
  12151. matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
  12152. var LMS_Flat = tempNormalizeMatrix;
  12153. convertToFlat(sourceWhitePoint, LMS, LMS_Flat);
  12154. matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_Flat, result);
  12155. }
  12156. function normalizeWhitePointToD65(sourceWhitePoint, XYZ_In, result) {
  12157. var LMS = result;
  12158. matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
  12159. var LMS_D65 = tempNormalizeMatrix;
  12160. convertToD65(sourceWhitePoint, LMS, LMS_D65);
  12161. matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_D65, result);
  12162. }
  12163. function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
  12164. // A, B and C represent a red, green and blue components of a calibrated
  12165. // rgb space.
  12166. var A = adjustToRange(0, 1, src[srcOffset] * scale);
  12167. var B = adjustToRange(0, 1, src[srcOffset + 1] * scale);
  12168. var C = adjustToRange(0, 1, src[srcOffset + 2] * scale);
  12169. // A <---> AGR in the spec
  12170. // B <---> BGG in the spec
  12171. // C <---> CGB in the spec
  12172. var AGR = Math.pow(A, cs.GR);
  12173. var BGG = Math.pow(B, cs.GG);
  12174. var CGB = Math.pow(C, cs.GB);
  12175. // Computes intermediate variables L, M, N as per spec.
  12176. // To decode X, Y, Z values map L, M, N directly to them.
  12177. var X = cs.MXA * AGR + cs.MXB * BGG + cs.MXC * CGB;
  12178. var Y = cs.MYA * AGR + cs.MYB * BGG + cs.MYC * CGB;
  12179. var Z = cs.MZA * AGR + cs.MZB * BGG + cs.MZC * CGB;
  12180. // The following calculations are based on this document:
  12181. // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
  12182. // AdobeBPC.pdf.
  12183. var XYZ = tempConvertMatrix1;
  12184. XYZ[0] = X;
  12185. XYZ[1] = Y;
  12186. XYZ[2] = Z;
  12187. var XYZ_Flat = tempConvertMatrix2;
  12188. normalizeWhitePointToFlat(cs.whitePoint, XYZ, XYZ_Flat);
  12189. var XYZ_Black = tempConvertMatrix1;
  12190. compensateBlackPoint(cs.blackPoint, XYZ_Flat, XYZ_Black);
  12191. var XYZ_D65 = tempConvertMatrix2;
  12192. normalizeWhitePointToD65(FLAT_WHITEPOINT_MATRIX, XYZ_Black, XYZ_D65);
  12193. var SRGB = tempConvertMatrix1;
  12194. matrixProduct(SRGB_D65_XYZ_TO_RGB_MATRIX, XYZ_D65, SRGB);
  12195. var sR = sRGBTransferFunction(SRGB[0]);
  12196. var sG = sRGBTransferFunction(SRGB[1]);
  12197. var sB = sRGBTransferFunction(SRGB[2]);
  12198. // Convert the values to rgb range [0, 255].
  12199. dest[destOffset] = Math.round(sR * 255);
  12200. dest[destOffset + 1] = Math.round(sG * 255);
  12201. dest[destOffset + 2] = Math.round(sB * 255);
  12202. }
  12203. CalRGBCS.prototype = {
  12204. getRgb: function CalRGBCS_getRgb(src, srcOffset) {
  12205. var rgb = new Uint8Array(3);
  12206. this.getRgbItem(src, srcOffset, rgb, 0);
  12207. return rgb;
  12208. },
  12209. getRgbItem: function CalRGBCS_getRgbItem(src, srcOffset,
  12210. dest, destOffset) {
  12211. convertToRgb(this, src, srcOffset, dest, destOffset, 1);
  12212. },
  12213. getRgbBuffer: function CalRGBCS_getRgbBuffer(src, srcOffset, count,
  12214. dest, destOffset, bits,
  12215. alpha01) {
  12216. var scale = 1 / ((1 << bits) - 1);
  12217. for (var i = 0; i < count; ++i) {
  12218. convertToRgb(this, src, srcOffset, dest, destOffset, scale);
  12219. srcOffset += 3;
  12220. destOffset += 3 + alpha01;
  12221. }
  12222. },
  12223. getOutputLength: function CalRGBCS_getOutputLength(inputLength, alpha01) {
  12224. return (inputLength * (3 + alpha01) / 3) | 0;
  12225. },
  12226. isPassthrough: ColorSpace.prototype.isPassthrough,
  12227. fillRgb: ColorSpace.prototype.fillRgb,
  12228. isDefaultDecode: function CalRGBCS_isDefaultDecode(decodeMap) {
  12229. return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  12230. },
  12231. usesZeroToOneRange: true
  12232. };
  12233. return CalRGBCS;
  12234. })();
  12235. //
  12236. // LabCS: Based on "PDF Reference, Sixth Ed", p.250
  12237. //
  12238. var LabCS = (function LabCSClosure() {
  12239. function LabCS(whitePoint, blackPoint, range) {
  12240. this.name = 'Lab';
  12241. this.numComps = 3;
  12242. this.defaultColor = new Float32Array([0, 0, 0]);
  12243. if (!whitePoint) {
  12244. error('WhitePoint missing - required for color space Lab');
  12245. }
  12246. blackPoint = blackPoint || [0, 0, 0];
  12247. range = range || [-100, 100, -100, 100];
  12248. // Translate args to spec variables
  12249. this.XW = whitePoint[0];
  12250. this.YW = whitePoint[1];
  12251. this.ZW = whitePoint[2];
  12252. this.amin = range[0];
  12253. this.amax = range[1];
  12254. this.bmin = range[2];
  12255. this.bmax = range[3];
  12256. // These are here just for completeness - the spec doesn't offer any
  12257. // formulas that use BlackPoint in Lab
  12258. this.XB = blackPoint[0];
  12259. this.YB = blackPoint[1];
  12260. this.ZB = blackPoint[2];
  12261. // Validate vars as per spec
  12262. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
  12263. error('Invalid WhitePoint components, no fallback available');
  12264. }
  12265. if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
  12266. info('Invalid BlackPoint, falling back to default');
  12267. this.XB = this.YB = this.ZB = 0;
  12268. }
  12269. if (this.amin > this.amax || this.bmin > this.bmax) {
  12270. info('Invalid Range, falling back to defaults');
  12271. this.amin = -100;
  12272. this.amax = 100;
  12273. this.bmin = -100;
  12274. this.bmax = 100;
  12275. }
  12276. }
  12277. // Function g(x) from spec
  12278. function fn_g(x) {
  12279. if (x >= 6 / 29) {
  12280. return x * x * x;
  12281. } else {
  12282. return (108 / 841) * (x - 4 / 29);
  12283. }
  12284. }
  12285. function decode(value, high1, low2, high2) {
  12286. return low2 + (value) * (high2 - low2) / (high1);
  12287. }
  12288. // If decoding is needed maxVal should be 2^bits per component - 1.
  12289. function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
  12290. // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]
  12291. // not the usual [0, 1]. If a command like setFillColor is used the src
  12292. // values will already be within the correct range. However, if we are
  12293. // converting an image we have to map the values to the correct range given
  12294. // above.
  12295. // Ls,as,bs <---> L*,a*,b* in the spec
  12296. var Ls = src[srcOffset];
  12297. var as = src[srcOffset + 1];
  12298. var bs = src[srcOffset + 2];
  12299. if (maxVal !== false) {
  12300. Ls = decode(Ls, maxVal, 0, 100);
  12301. as = decode(as, maxVal, cs.amin, cs.amax);
  12302. bs = decode(bs, maxVal, cs.bmin, cs.bmax);
  12303. }
  12304. // Adjust limits of 'as' and 'bs'
  12305. as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;
  12306. bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;
  12307. // Computes intermediate variables X,Y,Z as per spec
  12308. var M = (Ls + 16) / 116;
  12309. var L = M + (as / 500);
  12310. var N = M - (bs / 200);
  12311. var X = cs.XW * fn_g(L);
  12312. var Y = cs.YW * fn_g(M);
  12313. var Z = cs.ZW * fn_g(N);
  12314. var r, g, b;
  12315. // Using different conversions for D50 and D65 white points,
  12316. // per http://www.color.org/srgb.pdf
  12317. if (cs.ZW < 1) {
  12318. // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)
  12319. r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;
  12320. g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;
  12321. b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;
  12322. } else {
  12323. // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)
  12324. r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
  12325. g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
  12326. b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;
  12327. }
  12328. // clamp color values to [0,1] range then convert to [0,255] range.
  12329. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0;
  12330. dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0;
  12331. dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0;
  12332. }
  12333. LabCS.prototype = {
  12334. getRgb: ColorSpace.prototype.getRgb,
  12335. getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) {
  12336. convertToRgb(this, src, srcOffset, false, dest, destOffset);
  12337. },
  12338. getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count,
  12339. dest, destOffset, bits,
  12340. alpha01) {
  12341. var maxVal = (1 << bits) - 1;
  12342. for (var i = 0; i < count; i++) {
  12343. convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);
  12344. srcOffset += 3;
  12345. destOffset += 3 + alpha01;
  12346. }
  12347. },
  12348. getOutputLength: function LabCS_getOutputLength(inputLength, alpha01) {
  12349. return (inputLength * (3 + alpha01) / 3) | 0;
  12350. },
  12351. isPassthrough: ColorSpace.prototype.isPassthrough,
  12352. fillRgb: ColorSpace.prototype.fillRgb,
  12353. isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {
  12354. // XXX: Decoding is handled with the lab conversion because of the strange
  12355. // ranges that are used.
  12356. return true;
  12357. },
  12358. usesZeroToOneRange: false
  12359. };
  12360. return LabCS;
  12361. })();
  12362. var ARCFourCipher = (function ARCFourCipherClosure() {
  12363. function ARCFourCipher(key) {
  12364. this.a = 0;
  12365. this.b = 0;
  12366. var s = new Uint8Array(256);
  12367. var i, j = 0, tmp, keyLength = key.length;
  12368. for (i = 0; i < 256; ++i) {
  12369. s[i] = i;
  12370. }
  12371. for (i = 0; i < 256; ++i) {
  12372. tmp = s[i];
  12373. j = (j + tmp + key[i % keyLength]) & 0xFF;
  12374. s[i] = s[j];
  12375. s[j] = tmp;
  12376. }
  12377. this.s = s;
  12378. }
  12379. ARCFourCipher.prototype = {
  12380. encryptBlock: function ARCFourCipher_encryptBlock(data) {
  12381. var i, n = data.length, tmp, tmp2;
  12382. var a = this.a, b = this.b, s = this.s;
  12383. var output = new Uint8Array(n);
  12384. for (i = 0; i < n; ++i) {
  12385. a = (a + 1) & 0xFF;
  12386. tmp = s[a];
  12387. b = (b + tmp) & 0xFF;
  12388. tmp2 = s[b];
  12389. s[a] = tmp2;
  12390. s[b] = tmp;
  12391. output[i] = data[i] ^ s[(tmp + tmp2) & 0xFF];
  12392. }
  12393. this.a = a;
  12394. this.b = b;
  12395. return output;
  12396. }
  12397. };
  12398. ARCFourCipher.prototype.decryptBlock = ARCFourCipher.prototype.encryptBlock;
  12399. return ARCFourCipher;
  12400. })();
  12401. var calculateMD5 = (function calculateMD5Closure() {
  12402. var r = new Uint8Array([
  12403. 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  12404. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  12405. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  12406. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
  12407. var k = new Int32Array([
  12408. -680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426,
  12409. -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162,
  12410. 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632,
  12411. 643717713, -373897302, -701558691, 38016083, -660478335, -405537848,
  12412. 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784,
  12413. 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556,
  12414. -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222,
  12415. -722521979, 76029189, -640364487, -421815835, 530742520, -995338651,
  12416. -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606,
  12417. -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649,
  12418. -145523070, -1120210379, 718787259, -343485551]);
  12419. function hash(data, offset, length) {
  12420. var h0 = 1732584193, h1 = -271733879, h2 = -1732584194, h3 = 271733878;
  12421. // pre-processing
  12422. var paddedLength = (length + 72) & ~63; // data + 9 extra bytes
  12423. var padded = new Uint8Array(paddedLength);
  12424. var i, j, n;
  12425. for (i = 0; i < length; ++i) {
  12426. padded[i] = data[offset++];
  12427. }
  12428. padded[i++] = 0x80;
  12429. n = paddedLength - 8;
  12430. while (i < n) {
  12431. padded[i++] = 0;
  12432. }
  12433. padded[i++] = (length << 3) & 0xFF;
  12434. padded[i++] = (length >> 5) & 0xFF;
  12435. padded[i++] = (length >> 13) & 0xFF;
  12436. padded[i++] = (length >> 21) & 0xFF;
  12437. padded[i++] = (length >>> 29) & 0xFF;
  12438. padded[i++] = 0;
  12439. padded[i++] = 0;
  12440. padded[i++] = 0;
  12441. var w = new Int32Array(16);
  12442. for (i = 0; i < paddedLength;) {
  12443. for (j = 0; j < 16; ++j, i += 4) {
  12444. w[j] = (padded[i] | (padded[i + 1] << 8) |
  12445. (padded[i + 2] << 16) | (padded[i + 3] << 24));
  12446. }
  12447. var a = h0, b = h1, c = h2, d = h3, f, g;
  12448. for (j = 0; j < 64; ++j) {
  12449. if (j < 16) {
  12450. f = (b & c) | ((~b) & d);
  12451. g = j;
  12452. } else if (j < 32) {
  12453. f = (d & b) | ((~d) & c);
  12454. g = (5 * j + 1) & 15;
  12455. } else if (j < 48) {
  12456. f = b ^ c ^ d;
  12457. g = (3 * j + 5) & 15;
  12458. } else {
  12459. f = c ^ (b | (~d));
  12460. g = (7 * j) & 15;
  12461. }
  12462. var tmp = d, rotateArg = (a + f + k[j] + w[g]) | 0, rotate = r[j];
  12463. d = c;
  12464. c = b;
  12465. b = (b + ((rotateArg << rotate) | (rotateArg >>> (32 - rotate)))) | 0;
  12466. a = tmp;
  12467. }
  12468. h0 = (h0 + a) | 0;
  12469. h1 = (h1 + b) | 0;
  12470. h2 = (h2 + c) | 0;
  12471. h3 = (h3 + d) | 0;
  12472. }
  12473. return new Uint8Array([
  12474. h0 & 0xFF, (h0 >> 8) & 0xFF, (h0 >> 16) & 0xFF, (h0 >>> 24) & 0xFF,
  12475. h1 & 0xFF, (h1 >> 8) & 0xFF, (h1 >> 16) & 0xFF, (h1 >>> 24) & 0xFF,
  12476. h2 & 0xFF, (h2 >> 8) & 0xFF, (h2 >> 16) & 0xFF, (h2 >>> 24) & 0xFF,
  12477. h3 & 0xFF, (h3 >> 8) & 0xFF, (h3 >> 16) & 0xFF, (h3 >>> 24) & 0xFF
  12478. ]);
  12479. }
  12480. return hash;
  12481. })();
  12482. var Word64 = (function Word64Closure() {
  12483. function Word64(highInteger, lowInteger) {
  12484. this.high = highInteger | 0;
  12485. this.low = lowInteger | 0;
  12486. }
  12487. Word64.prototype = {
  12488. and: function Word64_and(word) {
  12489. this.high &= word.high;
  12490. this.low &= word.low;
  12491. },
  12492. xor: function Word64_xor(word) {
  12493. this.high ^= word.high;
  12494. this.low ^= word.low;
  12495. },
  12496. or: function Word64_or(word) {
  12497. this.high |= word.high;
  12498. this.low |= word.low;
  12499. },
  12500. shiftRight: function Word64_shiftRight(places) {
  12501. if (places >= 32) {
  12502. this.low = (this.high >>> (places - 32)) | 0;
  12503. this.high = 0;
  12504. } else {
  12505. this.low = (this.low >>> places) | (this.high << (32 - places));
  12506. this.high = (this.high >>> places) | 0;
  12507. }
  12508. },
  12509. shiftLeft: function Word64_shiftLeft(places) {
  12510. if (places >= 32) {
  12511. this.high = this.low << (places - 32);
  12512. this.low = 0;
  12513. } else {
  12514. this.high = (this.high << places) | (this.low >>> (32 - places));
  12515. this.low = this.low << places;
  12516. }
  12517. },
  12518. rotateRight: function Word64_rotateRight(places) {
  12519. var low, high;
  12520. if (places & 32) {
  12521. high = this.low;
  12522. low = this.high;
  12523. } else {
  12524. low = this.low;
  12525. high = this.high;
  12526. }
  12527. places &= 31;
  12528. this.low = (low >>> places) | (high << (32 - places));
  12529. this.high = (high >>> places) | (low << (32 - places));
  12530. },
  12531. not: function Word64_not() {
  12532. this.high = ~this.high;
  12533. this.low = ~this.low;
  12534. },
  12535. add: function Word64_add(word) {
  12536. var lowAdd = (this.low >>> 0) + (word.low >>> 0);
  12537. var highAdd = (this.high >>> 0) + (word.high >>> 0);
  12538. if (lowAdd > 0xFFFFFFFF) {
  12539. highAdd += 1;
  12540. }
  12541. this.low = lowAdd | 0;
  12542. this.high = highAdd | 0;
  12543. },
  12544. copyTo: function Word64_copyTo(bytes, offset) {
  12545. bytes[offset] = (this.high >>> 24) & 0xFF;
  12546. bytes[offset + 1] = (this.high >> 16) & 0xFF;
  12547. bytes[offset + 2] = (this.high >> 8) & 0xFF;
  12548. bytes[offset + 3] = this.high & 0xFF;
  12549. bytes[offset + 4] = (this.low >>> 24) & 0xFF;
  12550. bytes[offset + 5] = (this.low >> 16) & 0xFF;
  12551. bytes[offset + 6] = (this.low >> 8) & 0xFF;
  12552. bytes[offset + 7] = this.low & 0xFF;
  12553. },
  12554. assign: function Word64_assign(word) {
  12555. this.high = word.high;
  12556. this.low = word.low;
  12557. }
  12558. };
  12559. return Word64;
  12560. })();
  12561. var calculateSHA256 = (function calculateSHA256Closure() {
  12562. function rotr(x, n) {
  12563. return (x >>> n) | (x << 32 - n);
  12564. }
  12565. function ch(x, y, z) {
  12566. return (x & y) ^ (~x & z);
  12567. }
  12568. function maj(x, y, z) {
  12569. return (x & y) ^ (x & z) ^ (y & z);
  12570. }
  12571. function sigma(x) {
  12572. return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
  12573. }
  12574. function sigmaPrime(x) {
  12575. return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
  12576. }
  12577. function littleSigma(x) {
  12578. return rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3;
  12579. }
  12580. function littleSigmaPrime(x) {
  12581. return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10;
  12582. }
  12583. var k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  12584. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  12585. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  12586. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  12587. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  12588. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  12589. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  12590. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  12591. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  12592. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  12593. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  12594. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  12595. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  12596. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  12597. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  12598. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
  12599. function hash(data, offset, length) {
  12600. // initial hash values
  12601. var h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372,
  12602. h3 = 0xa54ff53a, h4 = 0x510e527f, h5 = 0x9b05688c,
  12603. h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
  12604. // pre-processing
  12605. var paddedLength = Math.ceil((length + 9) / 64) * 64;
  12606. var padded = new Uint8Array(paddedLength);
  12607. var i, j, n;
  12608. for (i = 0; i < length; ++i) {
  12609. padded[i] = data[offset++];
  12610. }
  12611. padded[i++] = 0x80;
  12612. n = paddedLength - 8;
  12613. while (i < n) {
  12614. padded[i++] = 0;
  12615. }
  12616. padded[i++] = 0;
  12617. padded[i++] = 0;
  12618. padded[i++] = 0;
  12619. padded[i++] = (length >>> 29) & 0xFF;
  12620. padded[i++] = (length >> 21) & 0xFF;
  12621. padded[i++] = (length >> 13) & 0xFF;
  12622. padded[i++] = (length >> 5) & 0xFF;
  12623. padded[i++] = (length << 3) & 0xFF;
  12624. var w = new Uint32Array(64);
  12625. // for each 512 bit block
  12626. for (i = 0; i < paddedLength;) {
  12627. for (j = 0; j < 16; ++j) {
  12628. w[j] = (padded[i] << 24 | (padded[i + 1] << 16) |
  12629. (padded[i + 2] << 8) | (padded[i + 3]));
  12630. i += 4;
  12631. }
  12632. for (j = 16; j < 64; ++j) {
  12633. w[j] = littleSigmaPrime(w[j - 2]) + w[j - 7] +
  12634. littleSigma(w[j - 15]) + w[j - 16] | 0;
  12635. }
  12636. var a = h0, b = h1, c = h2, d = h3, e = h4,
  12637. f = h5, g = h6, h = h7, t1, t2;
  12638. for (j = 0; j < 64; ++j) {
  12639. t1 = h + sigmaPrime(e) + ch(e, f, g) + k[j] + w[j];
  12640. t2 = sigma(a) + maj(a, b, c);
  12641. h = g;
  12642. g = f;
  12643. f = e;
  12644. e = (d + t1) | 0;
  12645. d = c;
  12646. c = b;
  12647. b = a;
  12648. a = (t1 + t2) | 0;
  12649. }
  12650. h0 = (h0 + a) | 0;
  12651. h1 = (h1 + b) | 0;
  12652. h2 = (h2 + c) | 0;
  12653. h3 = (h3 + d) | 0;
  12654. h4 = (h4 + e) | 0;
  12655. h5 = (h5 + f) | 0;
  12656. h6 = (h6 + g) | 0;
  12657. h7 = (h7 + h) | 0;
  12658. }
  12659. return new Uint8Array([
  12660. (h0 >> 24) & 0xFF, (h0 >> 16) & 0xFF, (h0 >> 8) & 0xFF, (h0) & 0xFF,
  12661. (h1 >> 24) & 0xFF, (h1 >> 16) & 0xFF, (h1 >> 8) & 0xFF, (h1) & 0xFF,
  12662. (h2 >> 24) & 0xFF, (h2 >> 16) & 0xFF, (h2 >> 8) & 0xFF, (h2) & 0xFF,
  12663. (h3 >> 24) & 0xFF, (h3 >> 16) & 0xFF, (h3 >> 8) & 0xFF, (h3) & 0xFF,
  12664. (h4 >> 24) & 0xFF, (h4 >> 16) & 0xFF, (h4 >> 8) & 0xFF, (h4) & 0xFF,
  12665. (h5 >> 24) & 0xFF, (h5 >> 16) & 0xFF, (h5 >> 8) & 0xFF, (h5) & 0xFF,
  12666. (h6 >> 24) & 0xFF, (h6 >> 16) & 0xFF, (h6 >> 8) & 0xFF, (h6) & 0xFF,
  12667. (h7 >> 24) & 0xFF, (h7 >> 16) & 0xFF, (h7 >> 8) & 0xFF, (h7) & 0xFF
  12668. ]);
  12669. }
  12670. return hash;
  12671. })();
  12672. var calculateSHA512 = (function calculateSHA512Closure() {
  12673. function ch(result, x, y, z, tmp) {
  12674. result.assign(x);
  12675. result.and(y);
  12676. tmp.assign(x);
  12677. tmp.not();
  12678. tmp.and(z);
  12679. result.xor(tmp);
  12680. }
  12681. function maj(result, x, y, z, tmp) {
  12682. result.assign(x);
  12683. result.and(y);
  12684. tmp.assign(x);
  12685. tmp.and(z);
  12686. result.xor(tmp);
  12687. tmp.assign(y);
  12688. tmp.and(z);
  12689. result.xor(tmp);
  12690. }
  12691. function sigma(result, x, tmp) {
  12692. result.assign(x);
  12693. result.rotateRight(28);
  12694. tmp.assign(x);
  12695. tmp.rotateRight(34);
  12696. result.xor(tmp);
  12697. tmp.assign(x);
  12698. tmp.rotateRight(39);
  12699. result.xor(tmp);
  12700. }
  12701. function sigmaPrime(result, x, tmp) {
  12702. result.assign(x);
  12703. result.rotateRight(14);
  12704. tmp.assign(x);
  12705. tmp.rotateRight(18);
  12706. result.xor(tmp);
  12707. tmp.assign(x);
  12708. tmp.rotateRight(41);
  12709. result.xor(tmp);
  12710. }
  12711. function littleSigma(result, x, tmp) {
  12712. result.assign(x);
  12713. result.rotateRight(1);
  12714. tmp.assign(x);
  12715. tmp.rotateRight(8);
  12716. result.xor(tmp);
  12717. tmp.assign(x);
  12718. tmp.shiftRight(7);
  12719. result.xor(tmp);
  12720. }
  12721. function littleSigmaPrime(result, x, tmp) {
  12722. result.assign(x);
  12723. result.rotateRight(19);
  12724. tmp.assign(x);
  12725. tmp.rotateRight(61);
  12726. result.xor(tmp);
  12727. tmp.assign(x);
  12728. tmp.shiftRight(6);
  12729. result.xor(tmp);
  12730. }
  12731. var k = [
  12732. new Word64(0x428a2f98, 0xd728ae22), new Word64(0x71374491, 0x23ef65cd),
  12733. new Word64(0xb5c0fbcf, 0xec4d3b2f), new Word64(0xe9b5dba5, 0x8189dbbc),
  12734. new Word64(0x3956c25b, 0xf348b538), new Word64(0x59f111f1, 0xb605d019),
  12735. new Word64(0x923f82a4, 0xaf194f9b), new Word64(0xab1c5ed5, 0xda6d8118),
  12736. new Word64(0xd807aa98, 0xa3030242), new Word64(0x12835b01, 0x45706fbe),
  12737. new Word64(0x243185be, 0x4ee4b28c), new Word64(0x550c7dc3, 0xd5ffb4e2),
  12738. new Word64(0x72be5d74, 0xf27b896f), new Word64(0x80deb1fe, 0x3b1696b1),
  12739. new Word64(0x9bdc06a7, 0x25c71235), new Word64(0xc19bf174, 0xcf692694),
  12740. new Word64(0xe49b69c1, 0x9ef14ad2), new Word64(0xefbe4786, 0x384f25e3),
  12741. new Word64(0x0fc19dc6, 0x8b8cd5b5), new Word64(0x240ca1cc, 0x77ac9c65),
  12742. new Word64(0x2de92c6f, 0x592b0275), new Word64(0x4a7484aa, 0x6ea6e483),
  12743. new Word64(0x5cb0a9dc, 0xbd41fbd4), new Word64(0x76f988da, 0x831153b5),
  12744. new Word64(0x983e5152, 0xee66dfab), new Word64(0xa831c66d, 0x2db43210),
  12745. new Word64(0xb00327c8, 0x98fb213f), new Word64(0xbf597fc7, 0xbeef0ee4),
  12746. new Word64(0xc6e00bf3, 0x3da88fc2), new Word64(0xd5a79147, 0x930aa725),
  12747. new Word64(0x06ca6351, 0xe003826f), new Word64(0x14292967, 0x0a0e6e70),
  12748. new Word64(0x27b70a85, 0x46d22ffc), new Word64(0x2e1b2138, 0x5c26c926),
  12749. new Word64(0x4d2c6dfc, 0x5ac42aed), new Word64(0x53380d13, 0x9d95b3df),
  12750. new Word64(0x650a7354, 0x8baf63de), new Word64(0x766a0abb, 0x3c77b2a8),
  12751. new Word64(0x81c2c92e, 0x47edaee6), new Word64(0x92722c85, 0x1482353b),
  12752. new Word64(0xa2bfe8a1, 0x4cf10364), new Word64(0xa81a664b, 0xbc423001),
  12753. new Word64(0xc24b8b70, 0xd0f89791), new Word64(0xc76c51a3, 0x0654be30),
  12754. new Word64(0xd192e819, 0xd6ef5218), new Word64(0xd6990624, 0x5565a910),
  12755. new Word64(0xf40e3585, 0x5771202a), new Word64(0x106aa070, 0x32bbd1b8),
  12756. new Word64(0x19a4c116, 0xb8d2d0c8), new Word64(0x1e376c08, 0x5141ab53),
  12757. new Word64(0x2748774c, 0xdf8eeb99), new Word64(0x34b0bcb5, 0xe19b48a8),
  12758. new Word64(0x391c0cb3, 0xc5c95a63), new Word64(0x4ed8aa4a, 0xe3418acb),
  12759. new Word64(0x5b9cca4f, 0x7763e373), new Word64(0x682e6ff3, 0xd6b2b8a3),
  12760. new Word64(0x748f82ee, 0x5defb2fc), new Word64(0x78a5636f, 0x43172f60),
  12761. new Word64(0x84c87814, 0xa1f0ab72), new Word64(0x8cc70208, 0x1a6439ec),
  12762. new Word64(0x90befffa, 0x23631e28), new Word64(0xa4506ceb, 0xde82bde9),
  12763. new Word64(0xbef9a3f7, 0xb2c67915), new Word64(0xc67178f2, 0xe372532b),
  12764. new Word64(0xca273ece, 0xea26619c), new Word64(0xd186b8c7, 0x21c0c207),
  12765. new Word64(0xeada7dd6, 0xcde0eb1e), new Word64(0xf57d4f7f, 0xee6ed178),
  12766. new Word64(0x06f067aa, 0x72176fba), new Word64(0x0a637dc5, 0xa2c898a6),
  12767. new Word64(0x113f9804, 0xbef90dae), new Word64(0x1b710b35, 0x131c471b),
  12768. new Word64(0x28db77f5, 0x23047d84), new Word64(0x32caab7b, 0x40c72493),
  12769. new Word64(0x3c9ebe0a, 0x15c9bebc), new Word64(0x431d67c4, 0x9c100d4c),
  12770. new Word64(0x4cc5d4be, 0xcb3e42b6), new Word64(0x597f299c, 0xfc657e2a),
  12771. new Word64(0x5fcb6fab, 0x3ad6faec), new Word64(0x6c44198c, 0x4a475817)];
  12772. function hash(data, offset, length, mode384) {
  12773. mode384 = !!mode384;
  12774. // initial hash values
  12775. var h0, h1, h2, h3, h4, h5, h6, h7;
  12776. if (!mode384) {
  12777. h0 = new Word64(0x6a09e667, 0xf3bcc908);
  12778. h1 = new Word64(0xbb67ae85, 0x84caa73b);
  12779. h2 = new Word64(0x3c6ef372, 0xfe94f82b);
  12780. h3 = new Word64(0xa54ff53a, 0x5f1d36f1);
  12781. h4 = new Word64(0x510e527f, 0xade682d1);
  12782. h5 = new Word64(0x9b05688c, 0x2b3e6c1f);
  12783. h6 = new Word64(0x1f83d9ab, 0xfb41bd6b);
  12784. h7 = new Word64(0x5be0cd19, 0x137e2179);
  12785. }
  12786. else {
  12787. // SHA384 is exactly the same
  12788. // except with different starting values and a trimmed result
  12789. h0 = new Word64(0xcbbb9d5d, 0xc1059ed8);
  12790. h1 = new Word64(0x629a292a, 0x367cd507);
  12791. h2 = new Word64(0x9159015a, 0x3070dd17);
  12792. h3 = new Word64(0x152fecd8, 0xf70e5939);
  12793. h4 = new Word64(0x67332667, 0xffc00b31);
  12794. h5 = new Word64(0x8eb44a87, 0x68581511);
  12795. h6 = new Word64(0xdb0c2e0d, 0x64f98fa7);
  12796. h7 = new Word64(0x47b5481d, 0xbefa4fa4);
  12797. }
  12798. // pre-processing
  12799. var paddedLength = Math.ceil((length + 17) / 128) * 128;
  12800. var padded = new Uint8Array(paddedLength);
  12801. var i, j, n;
  12802. for (i = 0; i < length; ++i) {
  12803. padded[i] = data[offset++];
  12804. }
  12805. padded[i++] = 0x80;
  12806. n = paddedLength - 16;
  12807. while (i < n) {
  12808. padded[i++] = 0;
  12809. }
  12810. padded[i++] = 0;
  12811. padded[i++] = 0;
  12812. padded[i++] = 0;
  12813. padded[i++] = 0;
  12814. padded[i++] = 0;
  12815. padded[i++] = 0;
  12816. padded[i++] = 0;
  12817. padded[i++] = 0;
  12818. padded[i++] = 0;
  12819. padded[i++] = 0;
  12820. padded[i++] = 0;
  12821. padded[i++] = (length >>> 29) & 0xFF;
  12822. padded[i++] = (length >> 21) & 0xFF;
  12823. padded[i++] = (length >> 13) & 0xFF;
  12824. padded[i++] = (length >> 5) & 0xFF;
  12825. padded[i++] = (length << 3) & 0xFF;
  12826. var w = new Array(80);
  12827. for (i = 0; i < 80; i++) {
  12828. w[i] = new Word64(0, 0);
  12829. }
  12830. var a = new Word64(0, 0), b = new Word64(0, 0), c = new Word64(0, 0);
  12831. var d = new Word64(0, 0), e = new Word64(0, 0), f = new Word64(0, 0);
  12832. var g = new Word64(0, 0), h = new Word64(0, 0);
  12833. var t1 = new Word64(0, 0), t2 = new Word64(0, 0);
  12834. var tmp1 = new Word64(0, 0), tmp2 = new Word64(0, 0), tmp3;
  12835. // for each 1024 bit block
  12836. for (i = 0; i < paddedLength;) {
  12837. for (j = 0; j < 16; ++j) {
  12838. w[j].high = (padded[i] << 24) | (padded[i + 1] << 16) |
  12839. (padded[i + 2] << 8) | (padded[i + 3]);
  12840. w[j].low = (padded[i + 4]) << 24 | (padded[i + 5]) << 16 |
  12841. (padded[i + 6]) << 8 | (padded[i + 7]);
  12842. i += 8;
  12843. }
  12844. for (j = 16; j < 80; ++j) {
  12845. tmp3 = w[j];
  12846. littleSigmaPrime(tmp3, w[j - 2], tmp2);
  12847. tmp3.add(w[j - 7]);
  12848. littleSigma(tmp1, w[j - 15], tmp2);
  12849. tmp3.add(tmp1);
  12850. tmp3.add(w[j - 16]);
  12851. }
  12852. a.assign(h0); b.assign(h1); c.assign(h2); d.assign(h3);
  12853. e.assign(h4); f.assign(h5); g.assign(h6); h.assign(h7);
  12854. for (j = 0; j < 80; ++j) {
  12855. t1.assign(h);
  12856. sigmaPrime(tmp1, e, tmp2);
  12857. t1.add(tmp1);
  12858. ch(tmp1, e, f, g, tmp2);
  12859. t1.add(tmp1);
  12860. t1.add(k[j]);
  12861. t1.add(w[j]);
  12862. sigma(t2, a, tmp2);
  12863. maj(tmp1, a, b, c, tmp2);
  12864. t2.add(tmp1);
  12865. tmp3 = h;
  12866. h = g;
  12867. g = f;
  12868. f = e;
  12869. d.add(t1);
  12870. e = d;
  12871. d = c;
  12872. c = b;
  12873. b = a;
  12874. tmp3.assign(t1);
  12875. tmp3.add(t2);
  12876. a = tmp3;
  12877. }
  12878. h0.add(a);
  12879. h1.add(b);
  12880. h2.add(c);
  12881. h3.add(d);
  12882. h4.add(e);
  12883. h5.add(f);
  12884. h6.add(g);
  12885. h7.add(h);
  12886. }
  12887. var result;
  12888. if (!mode384) {
  12889. result = new Uint8Array(64);
  12890. h0.copyTo(result,0);
  12891. h1.copyTo(result,8);
  12892. h2.copyTo(result,16);
  12893. h3.copyTo(result,24);
  12894. h4.copyTo(result,32);
  12895. h5.copyTo(result,40);
  12896. h6.copyTo(result,48);
  12897. h7.copyTo(result,56);
  12898. }
  12899. else {
  12900. result = new Uint8Array(48);
  12901. h0.copyTo(result,0);
  12902. h1.copyTo(result,8);
  12903. h2.copyTo(result,16);
  12904. h3.copyTo(result,24);
  12905. h4.copyTo(result,32);
  12906. h5.copyTo(result,40);
  12907. }
  12908. return result;
  12909. }
  12910. return hash;
  12911. })();
  12912. var calculateSHA384 = (function calculateSHA384Closure() {
  12913. function hash(data, offset, length) {
  12914. return calculateSHA512(data, offset, length, true);
  12915. }
  12916. return hash;
  12917. })();
  12918. var NullCipher = (function NullCipherClosure() {
  12919. function NullCipher() {
  12920. }
  12921. NullCipher.prototype = {
  12922. decryptBlock: function NullCipher_decryptBlock(data) {
  12923. return data;
  12924. }
  12925. };
  12926. return NullCipher;
  12927. })();
  12928. var AES128Cipher = (function AES128CipherClosure() {
  12929. var rcon = new Uint8Array([
  12930. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  12931. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  12932. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  12933. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  12934. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
  12935. 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,
  12936. 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  12937. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  12938. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10,
  12939. 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e,
  12940. 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  12941. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
  12942. 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
  12943. 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  12944. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  12945. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
  12946. 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb,
  12947. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  12948. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  12949. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  12950. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  12951. 0x74, 0xe8, 0xcb, 0x8d]);
  12952. var s = new Uint8Array([
  12953. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
  12954. 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
  12955. 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
  12956. 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  12957. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
  12958. 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
  12959. 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
  12960. 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  12961. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
  12962. 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
  12963. 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  12964. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  12965. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
  12966. 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
  12967. 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
  12968. 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  12969. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
  12970. 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
  12971. 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
  12972. 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  12973. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
  12974. 0xb0, 0x54, 0xbb, 0x16]);
  12975. var inv_s = new Uint8Array([
  12976. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
  12977. 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
  12978. 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
  12979. 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  12980. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
  12981. 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
  12982. 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
  12983. 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  12984. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
  12985. 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
  12986. 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  12987. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  12988. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
  12989. 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
  12990. 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
  12991. 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  12992. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
  12993. 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
  12994. 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
  12995. 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  12996. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
  12997. 0x55, 0x21, 0x0c, 0x7d]);
  12998. var mixCol = new Uint8Array(256);
  12999. for (var i = 0; i < 256; i++) {
  13000. if (i < 128) {
  13001. mixCol[i] = i << 1;
  13002. } else {
  13003. mixCol[i] = (i << 1) ^ 0x1b;
  13004. }
  13005. }
  13006. var mix = new Uint32Array([
  13007. 0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927,
  13008. 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
  13009. 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb,
  13010. 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
  13011. 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf,
  13012. 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
  13013. 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28,
  13014. 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
  13015. 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec,
  13016. 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
  13017. 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd,
  13018. 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
  13019. 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89,
  13020. 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
  13021. 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815,
  13022. 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f,
  13023. 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa,
  13024. 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8,
  13025. 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36,
  13026. 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
  13027. 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742,
  13028. 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
  13029. 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4,
  13030. 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e,
  13031. 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360,
  13032. 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
  13033. 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87,
  13034. 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
  13035. 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3,
  13036. 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
  13037. 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f,
  13038. 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
  13039. 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26,
  13040. 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
  13041. 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba,
  13042. 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
  13043. 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce,
  13044. 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
  13045. 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929,
  13046. 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
  13047. 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed,
  13048. 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
  13049. 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
  13050. function expandKey128(cipherKey) {
  13051. var b = 176, result = new Uint8Array(b);
  13052. result.set(cipherKey);
  13053. for (var j = 16, i = 1; j < b; ++i) {
  13054. // RotWord
  13055. var t1 = result[j - 3], t2 = result[j - 2],
  13056. t3 = result[j - 1], t4 = result[j - 4];
  13057. // SubWord
  13058. t1 = s[t1];
  13059. t2 = s[t2];
  13060. t3 = s[t3];
  13061. t4 = s[t4];
  13062. // Rcon
  13063. t1 = t1 ^ rcon[i];
  13064. for (var n = 0; n < 4; ++n) {
  13065. result[j] = (t1 ^= result[j - 16]);
  13066. j++;
  13067. result[j] = (t2 ^= result[j - 16]);
  13068. j++;
  13069. result[j] = (t3 ^= result[j - 16]);
  13070. j++;
  13071. result[j] = (t4 ^= result[j - 16]);
  13072. j++;
  13073. }
  13074. }
  13075. return result;
  13076. }
  13077. function decrypt128(input, key) {
  13078. var state = new Uint8Array(16);
  13079. state.set(input);
  13080. var i, j, k;
  13081. var t, u, v;
  13082. // AddRoundKey
  13083. for (j = 0, k = 160; j < 16; ++j, ++k) {
  13084. state[j] ^= key[k];
  13085. }
  13086. for (i = 9; i >= 1; --i) {
  13087. // InvShiftRows
  13088. t = state[13];
  13089. state[13] = state[9];
  13090. state[9] = state[5];
  13091. state[5] = state[1];
  13092. state[1] = t;
  13093. t = state[14];
  13094. u = state[10];
  13095. state[14] = state[6];
  13096. state[10] = state[2];
  13097. state[6] = t;
  13098. state[2] = u;
  13099. t = state[15];
  13100. u = state[11];
  13101. v = state[7];
  13102. state[15] = state[3];
  13103. state[11] = t;
  13104. state[7] = u;
  13105. state[3] = v;
  13106. // InvSubBytes
  13107. for (j = 0; j < 16; ++j) {
  13108. state[j] = inv_s[state[j]];
  13109. }
  13110. // AddRoundKey
  13111. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13112. state[j] ^= key[k];
  13113. }
  13114. // InvMixColumns
  13115. for (j = 0; j < 16; j += 4) {
  13116. var s0 = mix[state[j]], s1 = mix[state[j + 1]],
  13117. s2 = mix[state[j + 2]], s3 = mix[state[j + 3]];
  13118. t = (s0 ^ (s1 >>> 8) ^ (s1 << 24) ^ (s2 >>> 16) ^ (s2 << 16) ^
  13119. (s3 >>> 24) ^ (s3 << 8));
  13120. state[j] = (t >>> 24) & 0xFF;
  13121. state[j + 1] = (t >> 16) & 0xFF;
  13122. state[j + 2] = (t >> 8) & 0xFF;
  13123. state[j + 3] = t & 0xFF;
  13124. }
  13125. }
  13126. // InvShiftRows
  13127. t = state[13];
  13128. state[13] = state[9];
  13129. state[9] = state[5];
  13130. state[5] = state[1];
  13131. state[1] = t;
  13132. t = state[14];
  13133. u = state[10];
  13134. state[14] = state[6];
  13135. state[10] = state[2];
  13136. state[6] = t;
  13137. state[2] = u;
  13138. t = state[15];
  13139. u = state[11];
  13140. v = state[7];
  13141. state[15] = state[3];
  13142. state[11] = t;
  13143. state[7] = u;
  13144. state[3] = v;
  13145. for (j = 0; j < 16; ++j) {
  13146. // InvSubBytes
  13147. state[j] = inv_s[state[j]];
  13148. // AddRoundKey
  13149. state[j] ^= key[j];
  13150. }
  13151. return state;
  13152. }
  13153. function encrypt128(input, key) {
  13154. var t, u, v, k;
  13155. var state = new Uint8Array(16);
  13156. state.set(input);
  13157. for (j = 0; j < 16; ++j) {
  13158. // AddRoundKey
  13159. state[j] ^= key[j];
  13160. }
  13161. for (i = 1; i < 10; i++) {
  13162. //SubBytes
  13163. for (j = 0; j < 16; ++j) {
  13164. state[j] = s[state[j]];
  13165. }
  13166. //ShiftRows
  13167. v = state[1];
  13168. state[1] = state[5];
  13169. state[5] = state[9];
  13170. state[9] = state[13];
  13171. state[13] = v;
  13172. v = state[2];
  13173. u = state[6];
  13174. state[2] = state[10];
  13175. state[6] = state[14];
  13176. state[10] = v;
  13177. state[14] = u;
  13178. v = state[3];
  13179. u = state[7];
  13180. t = state[11];
  13181. state[3] = state[15];
  13182. state[7] = v;
  13183. state[11] = u;
  13184. state[15] = t;
  13185. //MixColumns
  13186. for (var j = 0; j < 16; j += 4) {
  13187. var s0 = state[j + 0], s1 = state[j + 1];
  13188. var s2 = state[j + 2], s3 = state[j + 3];
  13189. t = s0 ^ s1 ^ s2 ^ s3;
  13190. state[j + 0] ^= t ^ mixCol[s0 ^ s1];
  13191. state[j + 1] ^= t ^ mixCol[s1 ^ s2];
  13192. state[j + 2] ^= t ^ mixCol[s2 ^ s3];
  13193. state[j + 3] ^= t ^ mixCol[s3 ^ s0];
  13194. }
  13195. //AddRoundKey
  13196. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13197. state[j] ^= key[k];
  13198. }
  13199. }
  13200. //SubBytes
  13201. for (j = 0; j < 16; ++j) {
  13202. state[j] = s[state[j]];
  13203. }
  13204. //ShiftRows
  13205. v = state[1];
  13206. state[1] = state[5];
  13207. state[5] = state[9];
  13208. state[9] = state[13];
  13209. state[13] = v;
  13210. v = state[2];
  13211. u = state[6];
  13212. state[2] = state[10];
  13213. state[6] = state[14];
  13214. state[10] = v;
  13215. state[14] = u;
  13216. v = state[3];
  13217. u = state[7];
  13218. t = state[11];
  13219. state[3] = state[15];
  13220. state[7] = v;
  13221. state[11] = u;
  13222. state[15] = t;
  13223. //AddRoundKey
  13224. for (j = 0, k = 160; j < 16; ++j, ++k) {
  13225. state[j] ^= key[k];
  13226. }
  13227. return state;
  13228. }
  13229. function AES128Cipher(key) {
  13230. this.key = expandKey128(key);
  13231. this.buffer = new Uint8Array(16);
  13232. this.bufferPosition = 0;
  13233. }
  13234. function decryptBlock2(data, finalize) {
  13235. var i, j, ii, sourceLength = data.length,
  13236. buffer = this.buffer, bufferLength = this.bufferPosition,
  13237. result = [], iv = this.iv;
  13238. for (i = 0; i < sourceLength; ++i) {
  13239. buffer[bufferLength] = data[i];
  13240. ++bufferLength;
  13241. if (bufferLength < 16) {
  13242. continue;
  13243. }
  13244. // buffer is full, decrypting
  13245. var plain = decrypt128(buffer, this.key);
  13246. // xor-ing the IV vector to get plain text
  13247. for (j = 0; j < 16; ++j) {
  13248. plain[j] ^= iv[j];
  13249. }
  13250. iv = buffer;
  13251. result.push(plain);
  13252. buffer = new Uint8Array(16);
  13253. bufferLength = 0;
  13254. }
  13255. // saving incomplete buffer
  13256. this.buffer = buffer;
  13257. this.bufferLength = bufferLength;
  13258. this.iv = iv;
  13259. if (result.length === 0) {
  13260. return new Uint8Array([]);
  13261. }
  13262. // combining plain text blocks into one
  13263. var outputLength = 16 * result.length;
  13264. if (finalize) {
  13265. // undo a padding that is described in RFC 2898
  13266. var lastBlock = result[result.length - 1];
  13267. var psLen = lastBlock[15];
  13268. if (psLen <= 16) {
  13269. for (i = 15, ii = 16 - psLen; i >= ii; --i) {
  13270. if (lastBlock[i] !== psLen) {
  13271. // Invalid padding, assume that the block has no padding.
  13272. psLen = 0;
  13273. break;
  13274. }
  13275. }
  13276. outputLength -= psLen;
  13277. result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
  13278. }
  13279. }
  13280. var output = new Uint8Array(outputLength);
  13281. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13282. output.set(result[i], j);
  13283. }
  13284. return output;
  13285. }
  13286. AES128Cipher.prototype = {
  13287. decryptBlock: function AES128Cipher_decryptBlock(data, finalize) {
  13288. var i, sourceLength = data.length;
  13289. var buffer = this.buffer, bufferLength = this.bufferPosition;
  13290. // waiting for IV values -- they are at the start of the stream
  13291. for (i = 0; bufferLength < 16 && i < sourceLength; ++i, ++bufferLength) {
  13292. buffer[bufferLength] = data[i];
  13293. }
  13294. if (bufferLength < 16) {
  13295. // need more data
  13296. this.bufferLength = bufferLength;
  13297. return new Uint8Array([]);
  13298. }
  13299. this.iv = buffer;
  13300. this.buffer = new Uint8Array(16);
  13301. this.bufferLength = 0;
  13302. // starting decryption
  13303. this.decryptBlock = decryptBlock2;
  13304. return this.decryptBlock(data.subarray(16), finalize);
  13305. },
  13306. encrypt: function AES128Cipher_encrypt(data, iv) {
  13307. var i, j, ii, sourceLength = data.length,
  13308. buffer = this.buffer, bufferLength = this.bufferPosition,
  13309. result = [];
  13310. if (!iv) {
  13311. iv = new Uint8Array(16);
  13312. }
  13313. for (i = 0; i < sourceLength; ++i) {
  13314. buffer[bufferLength] = data[i];
  13315. ++bufferLength;
  13316. if (bufferLength < 16) {
  13317. continue;
  13318. }
  13319. for (j = 0; j < 16; ++j) {
  13320. buffer[j] ^= iv[j];
  13321. }
  13322. // buffer is full, encrypting
  13323. var cipher = encrypt128(buffer, this.key);
  13324. iv = cipher;
  13325. result.push(cipher);
  13326. buffer = new Uint8Array(16);
  13327. bufferLength = 0;
  13328. }
  13329. // saving incomplete buffer
  13330. this.buffer = buffer;
  13331. this.bufferLength = bufferLength;
  13332. this.iv = iv;
  13333. if (result.length === 0) {
  13334. return new Uint8Array([]);
  13335. }
  13336. // combining plain text blocks into one
  13337. var outputLength = 16 * result.length;
  13338. var output = new Uint8Array(outputLength);
  13339. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13340. output.set(result[i], j);
  13341. }
  13342. return output;
  13343. }
  13344. };
  13345. return AES128Cipher;
  13346. })();
  13347. var AES256Cipher = (function AES256CipherClosure() {
  13348. var rcon = new Uint8Array([
  13349. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13350. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13351. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13352. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13353. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
  13354. 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,
  13355. 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  13356. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  13357. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10,
  13358. 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e,
  13359. 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  13360. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
  13361. 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
  13362. 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  13363. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  13364. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
  13365. 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb,
  13366. 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  13367. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a,
  13368. 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
  13369. 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  13370. 0x74, 0xe8, 0xcb, 0x8d]);
  13371. var s = new Uint8Array([
  13372. 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
  13373. 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
  13374. 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
  13375. 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
  13376. 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
  13377. 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
  13378. 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
  13379. 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
  13380. 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
  13381. 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
  13382. 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  13383. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
  13384. 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
  13385. 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
  13386. 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
  13387. 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
  13388. 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
  13389. 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
  13390. 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
  13391. 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
  13392. 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
  13393. 0xb0, 0x54, 0xbb, 0x16]);
  13394. var inv_s = new Uint8Array([
  13395. 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
  13396. 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
  13397. 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
  13398. 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
  13399. 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
  13400. 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
  13401. 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
  13402. 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
  13403. 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
  13404. 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
  13405. 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  13406. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
  13407. 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
  13408. 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
  13409. 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
  13410. 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
  13411. 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
  13412. 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
  13413. 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
  13414. 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
  13415. 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
  13416. 0x55, 0x21, 0x0c, 0x7d]);
  13417. var mixCol = new Uint8Array(256);
  13418. for (var i = 0; i < 256; i++) {
  13419. if (i < 128) {
  13420. mixCol[i] = i << 1;
  13421. } else {
  13422. mixCol[i] = (i << 1) ^ 0x1b;
  13423. }
  13424. }
  13425. var mix = new Uint32Array([
  13426. 0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927,
  13427. 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
  13428. 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb,
  13429. 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
  13430. 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf,
  13431. 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
  13432. 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28,
  13433. 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
  13434. 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec,
  13435. 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
  13436. 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd,
  13437. 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
  13438. 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89,
  13439. 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
  13440. 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815,
  13441. 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f,
  13442. 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa,
  13443. 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8,
  13444. 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36,
  13445. 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
  13446. 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742,
  13447. 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
  13448. 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4,
  13449. 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e,
  13450. 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360,
  13451. 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
  13452. 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87,
  13453. 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
  13454. 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3,
  13455. 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
  13456. 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f,
  13457. 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
  13458. 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26,
  13459. 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
  13460. 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba,
  13461. 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
  13462. 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce,
  13463. 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
  13464. 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929,
  13465. 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
  13466. 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed,
  13467. 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
  13468. 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
  13469. function expandKey256(cipherKey) {
  13470. var b = 240, result = new Uint8Array(b);
  13471. var r = 1;
  13472. result.set(cipherKey);
  13473. for (var j = 32, i = 1; j < b; ++i) {
  13474. if (j % 32 === 16) {
  13475. t1 = s[t1];
  13476. t2 = s[t2];
  13477. t3 = s[t3];
  13478. t4 = s[t4];
  13479. } else if (j % 32 === 0) {
  13480. // RotWord
  13481. var t1 = result[j - 3], t2 = result[j - 2],
  13482. t3 = result[j - 1], t4 = result[j - 4];
  13483. // SubWord
  13484. t1 = s[t1];
  13485. t2 = s[t2];
  13486. t3 = s[t3];
  13487. t4 = s[t4];
  13488. // Rcon
  13489. t1 = t1 ^ r;
  13490. if ((r <<= 1) >= 256) {
  13491. r = (r ^ 0x1b) & 0xFF;
  13492. }
  13493. }
  13494. for (var n = 0; n < 4; ++n) {
  13495. result[j] = (t1 ^= result[j - 32]);
  13496. j++;
  13497. result[j] = (t2 ^= result[j - 32]);
  13498. j++;
  13499. result[j] = (t3 ^= result[j - 32]);
  13500. j++;
  13501. result[j] = (t4 ^= result[j - 32]);
  13502. j++;
  13503. }
  13504. }
  13505. return result;
  13506. }
  13507. function decrypt256(input, key) {
  13508. var state = new Uint8Array(16);
  13509. state.set(input);
  13510. var i, j, k;
  13511. var t, u, v;
  13512. // AddRoundKey
  13513. for (j = 0, k = 224; j < 16; ++j, ++k) {
  13514. state[j] ^= key[k];
  13515. }
  13516. for (i = 13; i >= 1; --i) {
  13517. // InvShiftRows
  13518. t = state[13];
  13519. state[13] = state[9];
  13520. state[9] = state[5];
  13521. state[5] = state[1];
  13522. state[1] = t;
  13523. t = state[14];
  13524. u = state[10];
  13525. state[14] = state[6];
  13526. state[10] = state[2];
  13527. state[6] = t;
  13528. state[2] = u;
  13529. t = state[15];
  13530. u = state[11];
  13531. v = state[7];
  13532. state[15] = state[3];
  13533. state[11] = t;
  13534. state[7] = u;
  13535. state[3] = v;
  13536. // InvSubBytes
  13537. for (j = 0; j < 16; ++j) {
  13538. state[j] = inv_s[state[j]];
  13539. }
  13540. // AddRoundKey
  13541. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13542. state[j] ^= key[k];
  13543. }
  13544. // InvMixColumns
  13545. for (j = 0; j < 16; j += 4) {
  13546. var s0 = mix[state[j]], s1 = mix[state[j + 1]],
  13547. s2 = mix[state[j + 2]], s3 = mix[state[j + 3]];
  13548. t = (s0 ^ (s1 >>> 8) ^ (s1 << 24) ^ (s2 >>> 16) ^ (s2 << 16) ^
  13549. (s3 >>> 24) ^ (s3 << 8));
  13550. state[j] = (t >>> 24) & 0xFF;
  13551. state[j + 1] = (t >> 16) & 0xFF;
  13552. state[j + 2] = (t >> 8) & 0xFF;
  13553. state[j + 3] = t & 0xFF;
  13554. }
  13555. }
  13556. // InvShiftRows
  13557. t = state[13];
  13558. state[13] = state[9];
  13559. state[9] = state[5];
  13560. state[5] = state[1];
  13561. state[1] = t;
  13562. t = state[14];
  13563. u = state[10];
  13564. state[14] = state[6];
  13565. state[10] = state[2];
  13566. state[6] = t;
  13567. state[2] = u;
  13568. t = state[15];
  13569. u = state[11];
  13570. v = state[7];
  13571. state[15] = state[3];
  13572. state[11] = t;
  13573. state[7] = u;
  13574. state[3] = v;
  13575. for (j = 0; j < 16; ++j) {
  13576. // InvSubBytes
  13577. state[j] = inv_s[state[j]];
  13578. // AddRoundKey
  13579. state[j] ^= key[j];
  13580. }
  13581. return state;
  13582. }
  13583. function encrypt256(input, key) {
  13584. var t, u, v, k;
  13585. var state = new Uint8Array(16);
  13586. state.set(input);
  13587. for (j = 0; j < 16; ++j) {
  13588. // AddRoundKey
  13589. state[j] ^= key[j];
  13590. }
  13591. for (i = 1; i < 14; i++) {
  13592. //SubBytes
  13593. for (j = 0; j < 16; ++j) {
  13594. state[j] = s[state[j]];
  13595. }
  13596. //ShiftRows
  13597. v = state[1];
  13598. state[1] = state[5];
  13599. state[5] = state[9];
  13600. state[9] = state[13];
  13601. state[13] = v;
  13602. v = state[2];
  13603. u = state[6];
  13604. state[2] = state[10];
  13605. state[6] = state[14];
  13606. state[10] = v;
  13607. state[14] = u;
  13608. v = state[3];
  13609. u = state[7];
  13610. t = state[11];
  13611. state[3] = state[15];
  13612. state[7] = v;
  13613. state[11] = u;
  13614. state[15] = t;
  13615. //MixColumns
  13616. for (var j = 0; j < 16; j += 4) {
  13617. var s0 = state[j + 0], s1 = state[j + 1];
  13618. var s2 = state[j + 2], s3 = state[j + 3];
  13619. t = s0 ^ s1 ^ s2 ^ s3;
  13620. state[j + 0] ^= t ^ mixCol[s0 ^ s1];
  13621. state[j + 1] ^= t ^ mixCol[s1 ^ s2];
  13622. state[j + 2] ^= t ^ mixCol[s2 ^ s3];
  13623. state[j + 3] ^= t ^ mixCol[s3 ^ s0];
  13624. }
  13625. //AddRoundKey
  13626. for (j = 0, k = i * 16; j < 16; ++j, ++k) {
  13627. state[j] ^= key[k];
  13628. }
  13629. }
  13630. //SubBytes
  13631. for (j = 0; j < 16; ++j) {
  13632. state[j] = s[state[j]];
  13633. }
  13634. //ShiftRows
  13635. v = state[1];
  13636. state[1] = state[5];
  13637. state[5] = state[9];
  13638. state[9] = state[13];
  13639. state[13] = v;
  13640. v = state[2];
  13641. u = state[6];
  13642. state[2] = state[10];
  13643. state[6] = state[14];
  13644. state[10] = v;
  13645. state[14] = u;
  13646. v = state[3];
  13647. u = state[7];
  13648. t = state[11];
  13649. state[3] = state[15];
  13650. state[7] = v;
  13651. state[11] = u;
  13652. state[15] = t;
  13653. //AddRoundKey
  13654. for (j = 0, k = 224; j < 16; ++j, ++k) {
  13655. state[j] ^= key[k];
  13656. }
  13657. return state;
  13658. }
  13659. function AES256Cipher(key) {
  13660. this.key = expandKey256(key);
  13661. this.buffer = new Uint8Array(16);
  13662. this.bufferPosition = 0;
  13663. }
  13664. function decryptBlock2(data, finalize) {
  13665. var i, j, ii, sourceLength = data.length,
  13666. buffer = this.buffer, bufferLength = this.bufferPosition,
  13667. result = [], iv = this.iv;
  13668. for (i = 0; i < sourceLength; ++i) {
  13669. buffer[bufferLength] = data[i];
  13670. ++bufferLength;
  13671. if (bufferLength < 16) {
  13672. continue;
  13673. }
  13674. // buffer is full, decrypting
  13675. var plain = decrypt256(buffer, this.key);
  13676. // xor-ing the IV vector to get plain text
  13677. for (j = 0; j < 16; ++j) {
  13678. plain[j] ^= iv[j];
  13679. }
  13680. iv = buffer;
  13681. result.push(plain);
  13682. buffer = new Uint8Array(16);
  13683. bufferLength = 0;
  13684. }
  13685. // saving incomplete buffer
  13686. this.buffer = buffer;
  13687. this.bufferLength = bufferLength;
  13688. this.iv = iv;
  13689. if (result.length === 0) {
  13690. return new Uint8Array([]);
  13691. }
  13692. // combining plain text blocks into one
  13693. var outputLength = 16 * result.length;
  13694. if (finalize) {
  13695. // undo a padding that is described in RFC 2898
  13696. var lastBlock = result[result.length - 1];
  13697. var psLen = lastBlock[15];
  13698. if (psLen <= 16) {
  13699. for (i = 15, ii = 16 - psLen; i >= ii; --i) {
  13700. if (lastBlock[i] !== psLen) {
  13701. // Invalid padding, assume that the block has no padding.
  13702. psLen = 0;
  13703. break;
  13704. }
  13705. }
  13706. outputLength -= psLen;
  13707. result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
  13708. }
  13709. }
  13710. var output = new Uint8Array(outputLength);
  13711. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13712. output.set(result[i], j);
  13713. }
  13714. return output;
  13715. }
  13716. AES256Cipher.prototype = {
  13717. decryptBlock: function AES256Cipher_decryptBlock(data, finalize, iv) {
  13718. var i, sourceLength = data.length;
  13719. var buffer = this.buffer, bufferLength = this.bufferPosition;
  13720. // if not supplied an IV wait for IV values
  13721. // they are at the start of the stream
  13722. if (iv) {
  13723. this.iv = iv;
  13724. } else {
  13725. for (i = 0; bufferLength < 16 &&
  13726. i < sourceLength; ++i, ++bufferLength) {
  13727. buffer[bufferLength] = data[i];
  13728. }
  13729. if (bufferLength < 16) {
  13730. //need more data
  13731. this.bufferLength = bufferLength;
  13732. return new Uint8Array([]);
  13733. }
  13734. this.iv = buffer;
  13735. data = data.subarray(16);
  13736. }
  13737. this.buffer = new Uint8Array(16);
  13738. this.bufferLength = 0;
  13739. // starting decryption
  13740. this.decryptBlock = decryptBlock2;
  13741. return this.decryptBlock(data, finalize);
  13742. },
  13743. encrypt: function AES256Cipher_encrypt(data, iv) {
  13744. var i, j, ii, sourceLength = data.length,
  13745. buffer = this.buffer, bufferLength = this.bufferPosition,
  13746. result = [];
  13747. if (!iv) {
  13748. iv = new Uint8Array(16);
  13749. }
  13750. for (i = 0; i < sourceLength; ++i) {
  13751. buffer[bufferLength] = data[i];
  13752. ++bufferLength;
  13753. if (bufferLength < 16) {
  13754. continue;
  13755. }
  13756. for (j = 0; j < 16; ++j) {
  13757. buffer[j] ^= iv[j];
  13758. }
  13759. // buffer is full, encrypting
  13760. var cipher = encrypt256(buffer, this.key);
  13761. this.iv = cipher;
  13762. result.push(cipher);
  13763. buffer = new Uint8Array(16);
  13764. bufferLength = 0;
  13765. }
  13766. // saving incomplete buffer
  13767. this.buffer = buffer;
  13768. this.bufferLength = bufferLength;
  13769. this.iv = iv;
  13770. if (result.length === 0) {
  13771. return new Uint8Array([]);
  13772. }
  13773. // combining plain text blocks into one
  13774. var outputLength = 16 * result.length;
  13775. var output = new Uint8Array(outputLength);
  13776. for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
  13777. output.set(result[i], j);
  13778. }
  13779. return output;
  13780. }
  13781. };
  13782. return AES256Cipher;
  13783. })();
  13784. var PDF17 = (function PDF17Closure() {
  13785. function compareByteArrays(array1, array2) {
  13786. if (array1.length !== array2.length) {
  13787. return false;
  13788. }
  13789. for (var i = 0; i < array1.length; i++) {
  13790. if (array1[i] !== array2[i]) {
  13791. return false;
  13792. }
  13793. }
  13794. return true;
  13795. }
  13796. function PDF17() {
  13797. }
  13798. PDF17.prototype = {
  13799. checkOwnerPassword: function PDF17_checkOwnerPassword(password,
  13800. ownerValidationSalt,
  13801. userBytes,
  13802. ownerPassword) {
  13803. var hashData = new Uint8Array(password.length + 56);
  13804. hashData.set(password, 0);
  13805. hashData.set(ownerValidationSalt, password.length);
  13806. hashData.set(userBytes, password.length + ownerValidationSalt.length);
  13807. var result = calculateSHA256(hashData, 0, hashData.length);
  13808. return compareByteArrays(result, ownerPassword);
  13809. },
  13810. checkUserPassword: function PDF17_checkUserPassword(password,
  13811. userValidationSalt,
  13812. userPassword) {
  13813. var hashData = new Uint8Array(password.length + 8);
  13814. hashData.set(password, 0);
  13815. hashData.set(userValidationSalt, password.length);
  13816. var result = calculateSHA256(hashData, 0, hashData.length);
  13817. return compareByteArrays(result, userPassword);
  13818. },
  13819. getOwnerKey: function PDF17_getOwnerKey(password, ownerKeySalt, userBytes,
  13820. ownerEncryption) {
  13821. var hashData = new Uint8Array(password.length + 56);
  13822. hashData.set(password, 0);
  13823. hashData.set(ownerKeySalt, password.length);
  13824. hashData.set(userBytes, password.length + ownerKeySalt.length);
  13825. var key = calculateSHA256(hashData, 0, hashData.length);
  13826. var cipher = new AES256Cipher(key);
  13827. return cipher.decryptBlock(ownerEncryption,
  13828. false,
  13829. new Uint8Array(16));
  13830. },
  13831. getUserKey: function PDF17_getUserKey(password, userKeySalt,
  13832. userEncryption) {
  13833. var hashData = new Uint8Array(password.length + 8);
  13834. hashData.set(password, 0);
  13835. hashData.set(userKeySalt, password.length);
  13836. //key is the decryption key for the UE string
  13837. var key = calculateSHA256(hashData, 0, hashData.length);
  13838. var cipher = new AES256Cipher(key);
  13839. return cipher.decryptBlock(userEncryption,
  13840. false,
  13841. new Uint8Array(16));
  13842. }
  13843. };
  13844. return PDF17;
  13845. })();
  13846. var PDF20 = (function PDF20Closure() {
  13847. function concatArrays(array1, array2) {
  13848. var t = new Uint8Array(array1.length + array2.length);
  13849. t.set(array1, 0);
  13850. t.set(array2, array1.length);
  13851. return t;
  13852. }
  13853. function calculatePDF20Hash(password, input, userBytes) {
  13854. //This refers to Algorithm 2.B as defined in ISO 32000-2
  13855. var k = calculateSHA256(input, 0, input.length).subarray(0, 32);
  13856. var e = [0];
  13857. var i = 0;
  13858. while (i < 64 || e[e.length - 1] > i - 32) {
  13859. var arrayLength = password.length + k.length + userBytes.length;
  13860. var k1 = new Uint8Array(arrayLength * 64);
  13861. var array = concatArrays(password, k);
  13862. array = concatArrays(array, userBytes);
  13863. for (var j = 0, pos = 0; j < 64; j++, pos += arrayLength) {
  13864. k1.set(array, pos);
  13865. }
  13866. //AES128 CBC NO PADDING with
  13867. //first 16 bytes of k as the key and the second 16 as the iv.
  13868. var cipher = new AES128Cipher(k.subarray(0, 16));
  13869. e = cipher.encrypt(k1, k.subarray(16, 32));
  13870. //Now we have to take the first 16 bytes of an unsigned
  13871. //big endian integer... and compute the remainder
  13872. //modulo 3.... That is a fairly large number and
  13873. //JavaScript isn't going to handle that well...
  13874. //So we're using a trick that allows us to perform
  13875. //modulo math byte by byte
  13876. var remainder = 0;
  13877. for (var z = 0; z < 16; z++) {
  13878. remainder *= (256 % 3);
  13879. remainder %= 3;
  13880. remainder += ((e[z] >>> 0) % 3);
  13881. remainder %= 3;
  13882. }
  13883. if (remainder === 0) {
  13884. k = calculateSHA256(e, 0, e.length);
  13885. }
  13886. else if (remainder === 1) {
  13887. k = calculateSHA384(e, 0, e.length);
  13888. }
  13889. else if (remainder === 2) {
  13890. k = calculateSHA512(e, 0, e.length);
  13891. }
  13892. i++;
  13893. }
  13894. return k.subarray(0, 32);
  13895. }
  13896. function PDF20() {
  13897. }
  13898. function compareByteArrays(array1, array2) {
  13899. if (array1.length !== array2.length) {
  13900. return false;
  13901. }
  13902. for (var i = 0; i < array1.length; i++) {
  13903. if (array1[i] !== array2[i]) {
  13904. return false;
  13905. }
  13906. }
  13907. return true;
  13908. }
  13909. PDF20.prototype = {
  13910. hash: function PDF20_hash(password, concatBytes, userBytes) {
  13911. return calculatePDF20Hash(password, concatBytes, userBytes);
  13912. },
  13913. checkOwnerPassword: function PDF20_checkOwnerPassword(password,
  13914. ownerValidationSalt,
  13915. userBytes,
  13916. ownerPassword) {
  13917. var hashData = new Uint8Array(password.length + 56);
  13918. hashData.set(password, 0);
  13919. hashData.set(ownerValidationSalt, password.length);
  13920. hashData.set(userBytes, password.length + ownerValidationSalt.length);
  13921. var result = calculatePDF20Hash(password, hashData, userBytes);
  13922. return compareByteArrays(result, ownerPassword);
  13923. },
  13924. checkUserPassword: function PDF20_checkUserPassword(password,
  13925. userValidationSalt,
  13926. userPassword) {
  13927. var hashData = new Uint8Array(password.length + 8);
  13928. hashData.set(password, 0);
  13929. hashData.set(userValidationSalt, password.length);
  13930. var result = calculatePDF20Hash(password, hashData, []);
  13931. return compareByteArrays(result, userPassword);
  13932. },
  13933. getOwnerKey: function PDF20_getOwnerKey(password, ownerKeySalt, userBytes,
  13934. ownerEncryption) {
  13935. var hashData = new Uint8Array(password.length + 56);
  13936. hashData.set(password, 0);
  13937. hashData.set(ownerKeySalt, password.length);
  13938. hashData.set(userBytes, password.length + ownerKeySalt.length);
  13939. var key = calculatePDF20Hash(password, hashData, userBytes);
  13940. var cipher = new AES256Cipher(key);
  13941. return cipher.decryptBlock(ownerEncryption,
  13942. false,
  13943. new Uint8Array(16));
  13944. },
  13945. getUserKey: function PDF20_getUserKey(password, userKeySalt,
  13946. userEncryption) {
  13947. var hashData = new Uint8Array(password.length + 8);
  13948. hashData.set(password, 0);
  13949. hashData.set(userKeySalt, password.length);
  13950. //key is the decryption key for the UE string
  13951. var key = calculatePDF20Hash(password, hashData, []);
  13952. var cipher = new AES256Cipher(key);
  13953. return cipher.decryptBlock(userEncryption,
  13954. false,
  13955. new Uint8Array(16));
  13956. }
  13957. };
  13958. return PDF20;
  13959. })();
  13960. var CipherTransform = (function CipherTransformClosure() {
  13961. function CipherTransform(stringCipherConstructor, streamCipherConstructor) {
  13962. this.stringCipherConstructor = stringCipherConstructor;
  13963. this.streamCipherConstructor = streamCipherConstructor;
  13964. }
  13965. CipherTransform.prototype = {
  13966. createStream: function CipherTransform_createStream(stream, length) {
  13967. var cipher = new this.streamCipherConstructor();
  13968. return new DecryptStream(stream, length,
  13969. function cipherTransformDecryptStream(data, finalize) {
  13970. return cipher.decryptBlock(data, finalize);
  13971. }
  13972. );
  13973. },
  13974. decryptString: function CipherTransform_decryptString(s) {
  13975. var cipher = new this.stringCipherConstructor();
  13976. var data = stringToBytes(s);
  13977. data = cipher.decryptBlock(data, true);
  13978. return bytesToString(data);
  13979. }
  13980. };
  13981. return CipherTransform;
  13982. })();
  13983. var CipherTransformFactory = (function CipherTransformFactoryClosure() {
  13984. var defaultPasswordBytes = new Uint8Array([
  13985. 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41,
  13986. 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
  13987. 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80,
  13988. 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A]);
  13989. function createEncryptionKey20(revision, password, ownerPassword,
  13990. ownerValidationSalt, ownerKeySalt, uBytes,
  13991. userPassword, userValidationSalt, userKeySalt,
  13992. ownerEncryption, userEncryption, perms) {
  13993. if (password) {
  13994. var passwordLength = Math.min(127, password.length);
  13995. password = password.subarray(0, passwordLength);
  13996. } else {
  13997. password = [];
  13998. }
  13999. var pdfAlgorithm;
  14000. if (revision === 6) {
  14001. pdfAlgorithm = new PDF20();
  14002. } else {
  14003. pdfAlgorithm = new PDF17();
  14004. }
  14005. if (pdfAlgorithm) {
  14006. if (pdfAlgorithm.checkUserPassword(password, userValidationSalt,
  14007. userPassword)) {
  14008. return pdfAlgorithm.getUserKey(password, userKeySalt, userEncryption);
  14009. } else if (pdfAlgorithm.checkOwnerPassword(password, ownerValidationSalt,
  14010. uBytes,
  14011. ownerPassword)) {
  14012. return pdfAlgorithm.getOwnerKey(password, ownerKeySalt, uBytes,
  14013. ownerEncryption);
  14014. }
  14015. }
  14016. return null;
  14017. }
  14018. function prepareKeyData(fileId, password, ownerPassword, userPassword,
  14019. flags, revision, keyLength, encryptMetadata) {
  14020. var hashDataSize = 40 + ownerPassword.length + fileId.length;
  14021. var hashData = new Uint8Array(hashDataSize), i = 0, j, n;
  14022. if (password) {
  14023. n = Math.min(32, password.length);
  14024. for (; i < n; ++i) {
  14025. hashData[i] = password[i];
  14026. }
  14027. }
  14028. j = 0;
  14029. while (i < 32) {
  14030. hashData[i++] = defaultPasswordBytes[j++];
  14031. }
  14032. // as now the padded password in the hashData[0..i]
  14033. for (j = 0, n = ownerPassword.length; j < n; ++j) {
  14034. hashData[i++] = ownerPassword[j];
  14035. }
  14036. hashData[i++] = flags & 0xFF;
  14037. hashData[i++] = (flags >> 8) & 0xFF;
  14038. hashData[i++] = (flags >> 16) & 0xFF;
  14039. hashData[i++] = (flags >>> 24) & 0xFF;
  14040. for (j = 0, n = fileId.length; j < n; ++j) {
  14041. hashData[i++] = fileId[j];
  14042. }
  14043. if (revision >= 4 && !encryptMetadata) {
  14044. hashData[i++] = 0xFF;
  14045. hashData[i++] = 0xFF;
  14046. hashData[i++] = 0xFF;
  14047. hashData[i++] = 0xFF;
  14048. }
  14049. var hash = calculateMD5(hashData, 0, i);
  14050. var keyLengthInBytes = keyLength >> 3;
  14051. if (revision >= 3) {
  14052. for (j = 0; j < 50; ++j) {
  14053. hash = calculateMD5(hash, 0, keyLengthInBytes);
  14054. }
  14055. }
  14056. var encryptionKey = hash.subarray(0, keyLengthInBytes);
  14057. var cipher, checkData;
  14058. if (revision >= 3) {
  14059. for (i = 0; i < 32; ++i) {
  14060. hashData[i] = defaultPasswordBytes[i];
  14061. }
  14062. for (j = 0, n = fileId.length; j < n; ++j) {
  14063. hashData[i++] = fileId[j];
  14064. }
  14065. cipher = new ARCFourCipher(encryptionKey);
  14066. checkData = cipher.encryptBlock(calculateMD5(hashData, 0, i));
  14067. n = encryptionKey.length;
  14068. var derivedKey = new Uint8Array(n), k;
  14069. for (j = 1; j <= 19; ++j) {
  14070. for (k = 0; k < n; ++k) {
  14071. derivedKey[k] = encryptionKey[k] ^ j;
  14072. }
  14073. cipher = new ARCFourCipher(derivedKey);
  14074. checkData = cipher.encryptBlock(checkData);
  14075. }
  14076. for (j = 0, n = checkData.length; j < n; ++j) {
  14077. if (userPassword[j] !== checkData[j]) {
  14078. return null;
  14079. }
  14080. }
  14081. } else {
  14082. cipher = new ARCFourCipher(encryptionKey);
  14083. checkData = cipher.encryptBlock(defaultPasswordBytes);
  14084. for (j = 0, n = checkData.length; j < n; ++j) {
  14085. if (userPassword[j] !== checkData[j]) {
  14086. return null;
  14087. }
  14088. }
  14089. }
  14090. return encryptionKey;
  14091. }
  14092. function decodeUserPassword(password, ownerPassword, revision, keyLength) {
  14093. var hashData = new Uint8Array(32), i = 0, j, n;
  14094. n = Math.min(32, password.length);
  14095. for (; i < n; ++i) {
  14096. hashData[i] = password[i];
  14097. }
  14098. j = 0;
  14099. while (i < 32) {
  14100. hashData[i++] = defaultPasswordBytes[j++];
  14101. }
  14102. var hash = calculateMD5(hashData, 0, i);
  14103. var keyLengthInBytes = keyLength >> 3;
  14104. if (revision >= 3) {
  14105. for (j = 0; j < 50; ++j) {
  14106. hash = calculateMD5(hash, 0, hash.length);
  14107. }
  14108. }
  14109. var cipher, userPassword;
  14110. if (revision >= 3) {
  14111. userPassword = ownerPassword;
  14112. var derivedKey = new Uint8Array(keyLengthInBytes), k;
  14113. for (j = 19; j >= 0; j--) {
  14114. for (k = 0; k < keyLengthInBytes; ++k) {
  14115. derivedKey[k] = hash[k] ^ j;
  14116. }
  14117. cipher = new ARCFourCipher(derivedKey);
  14118. userPassword = cipher.encryptBlock(userPassword);
  14119. }
  14120. } else {
  14121. cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
  14122. userPassword = cipher.encryptBlock(ownerPassword);
  14123. }
  14124. return userPassword;
  14125. }
  14126. var identityName = Name.get('Identity');
  14127. function CipherTransformFactory(dict, fileId, password) {
  14128. var filter = dict.get('Filter');
  14129. if (!isName(filter) || filter.name !== 'Standard') {
  14130. error('unknown encryption method');
  14131. }
  14132. this.dict = dict;
  14133. var algorithm = dict.get('V');
  14134. if (!isInt(algorithm) ||
  14135. (algorithm !== 1 && algorithm !== 2 && algorithm !== 4 &&
  14136. algorithm !== 5)) {
  14137. error('unsupported encryption algorithm');
  14138. }
  14139. this.algorithm = algorithm;
  14140. var keyLength = dict.get('Length') || 40;
  14141. if (!isInt(keyLength) ||
  14142. keyLength < 40 || (keyLength % 8) !== 0) {
  14143. error('invalid key length');
  14144. }
  14145. // prepare keys
  14146. var ownerPassword = stringToBytes(dict.get('O')).subarray(0, 32);
  14147. var userPassword = stringToBytes(dict.get('U')).subarray(0, 32);
  14148. var flags = dict.get('P');
  14149. var revision = dict.get('R');
  14150. // meaningful when V is 4 or 5
  14151. var encryptMetadata = ((algorithm === 4 || algorithm === 5) &&
  14152. dict.get('EncryptMetadata') !== false);
  14153. this.encryptMetadata = encryptMetadata;
  14154. var fileIdBytes = stringToBytes(fileId);
  14155. var passwordBytes;
  14156. if (password) {
  14157. passwordBytes = stringToBytes(password);
  14158. }
  14159. var encryptionKey;
  14160. if (algorithm !== 5) {
  14161. encryptionKey = prepareKeyData(fileIdBytes, passwordBytes,
  14162. ownerPassword, userPassword, flags,
  14163. revision, keyLength, encryptMetadata);
  14164. }
  14165. else {
  14166. var ownerValidationSalt = stringToBytes(dict.get('O')).subarray(32, 40);
  14167. var ownerKeySalt = stringToBytes(dict.get('O')).subarray(40, 48);
  14168. var uBytes = stringToBytes(dict.get('U')).subarray(0, 48);
  14169. var userValidationSalt = stringToBytes(dict.get('U')).subarray(32, 40);
  14170. var userKeySalt = stringToBytes(dict.get('U')).subarray(40, 48);
  14171. var ownerEncryption = stringToBytes(dict.get('OE'));
  14172. var userEncryption = stringToBytes(dict.get('UE'));
  14173. var perms = stringToBytes(dict.get('Perms'));
  14174. encryptionKey =
  14175. createEncryptionKey20(revision, passwordBytes,
  14176. ownerPassword, ownerValidationSalt,
  14177. ownerKeySalt, uBytes,
  14178. userPassword, userValidationSalt,
  14179. userKeySalt, ownerEncryption,
  14180. userEncryption, perms);
  14181. }
  14182. if (!encryptionKey && !password) {
  14183. throw new PasswordException('No password given',
  14184. PasswordResponses.NEED_PASSWORD);
  14185. } else if (!encryptionKey && password) {
  14186. // Attempting use the password as an owner password
  14187. var decodedPassword = decodeUserPassword(passwordBytes, ownerPassword,
  14188. revision, keyLength);
  14189. encryptionKey = prepareKeyData(fileIdBytes, decodedPassword,
  14190. ownerPassword, userPassword, flags,
  14191. revision, keyLength, encryptMetadata);
  14192. }
  14193. if (!encryptionKey) {
  14194. throw new PasswordException('Incorrect Password',
  14195. PasswordResponses.INCORRECT_PASSWORD);
  14196. }
  14197. this.encryptionKey = encryptionKey;
  14198. if (algorithm >= 4) {
  14199. this.cf = dict.get('CF');
  14200. this.stmf = dict.get('StmF') || identityName;
  14201. this.strf = dict.get('StrF') || identityName;
  14202. this.eff = dict.get('EFF') || this.strf;
  14203. }
  14204. }
  14205. function buildObjectKey(num, gen, encryptionKey, isAes) {
  14206. var key = new Uint8Array(encryptionKey.length + 9), i, n;
  14207. for (i = 0, n = encryptionKey.length; i < n; ++i) {
  14208. key[i] = encryptionKey[i];
  14209. }
  14210. key[i++] = num & 0xFF;
  14211. key[i++] = (num >> 8) & 0xFF;
  14212. key[i++] = (num >> 16) & 0xFF;
  14213. key[i++] = gen & 0xFF;
  14214. key[i++] = (gen >> 8) & 0xFF;
  14215. if (isAes) {
  14216. key[i++] = 0x73;
  14217. key[i++] = 0x41;
  14218. key[i++] = 0x6C;
  14219. key[i++] = 0x54;
  14220. }
  14221. var hash = calculateMD5(key, 0, i);
  14222. return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
  14223. }
  14224. function buildCipherConstructor(cf, name, num, gen, key) {
  14225. var cryptFilter = cf.get(name.name);
  14226. var cfm;
  14227. if (cryptFilter !== null && cryptFilter !== undefined) {
  14228. cfm = cryptFilter.get('CFM');
  14229. }
  14230. if (!cfm || cfm.name === 'None') {
  14231. return function cipherTransformFactoryBuildCipherConstructorNone() {
  14232. return new NullCipher();
  14233. };
  14234. }
  14235. if ('V2' === cfm.name) {
  14236. return function cipherTransformFactoryBuildCipherConstructorV2() {
  14237. return new ARCFourCipher(buildObjectKey(num, gen, key, false));
  14238. };
  14239. }
  14240. if ('AESV2' === cfm.name) {
  14241. return function cipherTransformFactoryBuildCipherConstructorAESV2() {
  14242. return new AES128Cipher(buildObjectKey(num, gen, key, true));
  14243. };
  14244. }
  14245. if ('AESV3' === cfm.name) {
  14246. return function cipherTransformFactoryBuildCipherConstructorAESV3() {
  14247. return new AES256Cipher(key);
  14248. };
  14249. }
  14250. error('Unknown crypto method');
  14251. }
  14252. CipherTransformFactory.prototype = {
  14253. createCipherTransform:
  14254. function CipherTransformFactory_createCipherTransform(num, gen) {
  14255. if (this.algorithm === 4 || this.algorithm === 5) {
  14256. return new CipherTransform(
  14257. buildCipherConstructor(this.cf, this.stmf,
  14258. num, gen, this.encryptionKey),
  14259. buildCipherConstructor(this.cf, this.strf,
  14260. num, gen, this.encryptionKey));
  14261. }
  14262. // algorithms 1 and 2
  14263. var key = buildObjectKey(num, gen, this.encryptionKey, false);
  14264. var cipherConstructor = function buildCipherCipherConstructor() {
  14265. return new ARCFourCipher(key);
  14266. };
  14267. return new CipherTransform(cipherConstructor, cipherConstructor);
  14268. }
  14269. };
  14270. return CipherTransformFactory;
  14271. })();
  14272. var PatternType = {
  14273. FUNCTION_BASED: 1,
  14274. AXIAL: 2,
  14275. RADIAL: 3,
  14276. FREE_FORM_MESH: 4,
  14277. LATTICE_FORM_MESH: 5,
  14278. COONS_PATCH_MESH: 6,
  14279. TENSOR_PATCH_MESH: 7
  14280. };
  14281. var Pattern = (function PatternClosure() {
  14282. // Constructor should define this.getPattern
  14283. function Pattern() {
  14284. error('should not call Pattern constructor');
  14285. }
  14286. Pattern.prototype = {
  14287. // Input: current Canvas context
  14288. // Output: the appropriate fillStyle or strokeStyle
  14289. getPattern: function Pattern_getPattern(ctx) {
  14290. error('Should not call Pattern.getStyle: ' + ctx);
  14291. }
  14292. };
  14293. Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref,
  14294. res) {
  14295. var dict = isStream(shading) ? shading.dict : shading;
  14296. var type = dict.get('ShadingType');
  14297. try {
  14298. switch (type) {
  14299. case PatternType.AXIAL:
  14300. case PatternType.RADIAL:
  14301. // Both radial and axial shadings are handled by RadialAxial shading.
  14302. return new Shadings.RadialAxial(dict, matrix, xref, res);
  14303. case PatternType.FREE_FORM_MESH:
  14304. case PatternType.LATTICE_FORM_MESH:
  14305. case PatternType.COONS_PATCH_MESH:
  14306. case PatternType.TENSOR_PATCH_MESH:
  14307. return new Shadings.Mesh(shading, matrix, xref, res);
  14308. default:
  14309. throw new Error('Unknown PatternType: ' + type);
  14310. }
  14311. } catch (ex) {
  14312. if (ex instanceof MissingDataException) {
  14313. throw ex;
  14314. }
  14315. UnsupportedManager.notify(UNSUPPORTED_FEATURES.shadingPattern);
  14316. warn(ex);
  14317. return new Shadings.Dummy();
  14318. }
  14319. };
  14320. return Pattern;
  14321. })();
  14322. var Shadings = {};
  14323. // A small number to offset the first/last color stops so we can insert ones to
  14324. // support extend. Number.MIN_VALUE appears to be too small and breaks the
  14325. // extend. 1e-7 works in FF but chrome seems to use an even smaller sized number
  14326. // internally so we have to go bigger.
  14327. Shadings.SMALL_NUMBER = 1e-2;
  14328. // Radial and axial shading have very similar implementations
  14329. // If needed, the implementations can be broken into two classes
  14330. Shadings.RadialAxial = (function RadialAxialClosure() {
  14331. function RadialAxial(dict, matrix, xref, res) {
  14332. this.matrix = matrix;
  14333. this.coordsArr = dict.get('Coords');
  14334. this.shadingType = dict.get('ShadingType');
  14335. this.type = 'Pattern';
  14336. var cs = dict.get('ColorSpace', 'CS');
  14337. cs = ColorSpace.parse(cs, xref, res);
  14338. this.cs = cs;
  14339. var t0 = 0.0, t1 = 1.0;
  14340. if (dict.has('Domain')) {
  14341. var domainArr = dict.get('Domain');
  14342. t0 = domainArr[0];
  14343. t1 = domainArr[1];
  14344. }
  14345. var extendStart = false, extendEnd = false;
  14346. if (dict.has('Extend')) {
  14347. var extendArr = dict.get('Extend');
  14348. extendStart = extendArr[0];
  14349. extendEnd = extendArr[1];
  14350. }
  14351. if (this.shadingType === PatternType.RADIAL &&
  14352. (!extendStart || !extendEnd)) {
  14353. // Radial gradient only currently works if either circle is fully within
  14354. // the other circle.
  14355. var x1 = this.coordsArr[0];
  14356. var y1 = this.coordsArr[1];
  14357. var r1 = this.coordsArr[2];
  14358. var x2 = this.coordsArr[3];
  14359. var y2 = this.coordsArr[4];
  14360. var r2 = this.coordsArr[5];
  14361. var distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  14362. if (r1 <= r2 + distance &&
  14363. r2 <= r1 + distance) {
  14364. warn('Unsupported radial gradient.');
  14365. }
  14366. }
  14367. this.extendStart = extendStart;
  14368. this.extendEnd = extendEnd;
  14369. var fnObj = dict.get('Function');
  14370. var fn = PDFFunction.parseArray(xref, fnObj);
  14371. // 10 samples seems good enough for now, but probably won't work
  14372. // if there are sharp color changes. Ideally, we would implement
  14373. // the spec faithfully and add lossless optimizations.
  14374. var diff = t1 - t0;
  14375. var step = diff / 10;
  14376. var colorStops = this.colorStops = [];
  14377. // Protect against bad domains so we don't end up in an infinte loop below.
  14378. if (t0 >= t1 || step <= 0) {
  14379. // Acrobat doesn't seem to handle these cases so we'll ignore for
  14380. // now.
  14381. info('Bad shading domain.');
  14382. return;
  14383. }
  14384. var color = new Float32Array(cs.numComps), ratio = new Float32Array(1);
  14385. var rgbColor;
  14386. for (var i = t0; i <= t1; i += step) {
  14387. ratio[0] = i;
  14388. fn(ratio, 0, color, 0);
  14389. rgbColor = cs.getRgb(color, 0);
  14390. var cssColor = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
  14391. colorStops.push([(i - t0) / diff, cssColor]);
  14392. }
  14393. var background = 'transparent';
  14394. if (dict.has('Background')) {
  14395. rgbColor = cs.getRgb(dict.get('Background'), 0);
  14396. background = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
  14397. }
  14398. if (!extendStart) {
  14399. // Insert a color stop at the front and offset the first real color stop
  14400. // so it doesn't conflict with the one we insert.
  14401. colorStops.unshift([0, background]);
  14402. colorStops[1][0] += Shadings.SMALL_NUMBER;
  14403. }
  14404. if (!extendEnd) {
  14405. // Same idea as above in extendStart but for the end.
  14406. colorStops[colorStops.length - 1][0] -= Shadings.SMALL_NUMBER;
  14407. colorStops.push([1, background]);
  14408. }
  14409. this.colorStops = colorStops;
  14410. }
  14411. RadialAxial.prototype = {
  14412. getIR: function RadialAxial_getIR() {
  14413. var coordsArr = this.coordsArr;
  14414. var shadingType = this.shadingType;
  14415. var type, p0, p1, r0, r1;
  14416. if (shadingType === PatternType.AXIAL) {
  14417. p0 = [coordsArr[0], coordsArr[1]];
  14418. p1 = [coordsArr[2], coordsArr[3]];
  14419. r0 = null;
  14420. r1 = null;
  14421. type = 'axial';
  14422. } else if (shadingType === PatternType.RADIAL) {
  14423. p0 = [coordsArr[0], coordsArr[1]];
  14424. p1 = [coordsArr[3], coordsArr[4]];
  14425. r0 = coordsArr[2];
  14426. r1 = coordsArr[5];
  14427. type = 'radial';
  14428. } else {
  14429. error('getPattern type unknown: ' + shadingType);
  14430. }
  14431. var matrix = this.matrix;
  14432. if (matrix) {
  14433. p0 = Util.applyTransform(p0, matrix);
  14434. p1 = Util.applyTransform(p1, matrix);
  14435. }
  14436. return ['RadialAxial', type, this.colorStops, p0, p1, r0, r1];
  14437. }
  14438. };
  14439. return RadialAxial;
  14440. })();
  14441. // All mesh shading. For now, they will be presented as set of the triangles
  14442. // to be drawn on the canvas and rgb color for each vertex.
  14443. Shadings.Mesh = (function MeshClosure() {
  14444. function MeshStreamReader(stream, context) {
  14445. this.stream = stream;
  14446. this.context = context;
  14447. this.buffer = 0;
  14448. this.bufferLength = 0;
  14449. var numComps = context.numComps;
  14450. this.tmpCompsBuf = new Float32Array(numComps);
  14451. var csNumComps = context.colorSpace;
  14452. this.tmpCsCompsBuf = context.colorFn ? new Float32Array(csNumComps) :
  14453. this.tmpCompsBuf;
  14454. }
  14455. MeshStreamReader.prototype = {
  14456. get hasData() {
  14457. if (this.stream.end) {
  14458. return this.stream.pos < this.stream.end;
  14459. }
  14460. if (this.bufferLength > 0) {
  14461. return true;
  14462. }
  14463. var nextByte = this.stream.getByte();
  14464. if (nextByte < 0) {
  14465. return false;
  14466. }
  14467. this.buffer = nextByte;
  14468. this.bufferLength = 8;
  14469. return true;
  14470. },
  14471. readBits: function MeshStreamReader_readBits(n) {
  14472. var buffer = this.buffer;
  14473. var bufferLength = this.bufferLength;
  14474. if (n === 32) {
  14475. if (bufferLength === 0) {
  14476. return ((this.stream.getByte() << 24) |
  14477. (this.stream.getByte() << 16) | (this.stream.getByte() << 8) |
  14478. this.stream.getByte()) >>> 0;
  14479. }
  14480. buffer = (buffer << 24) | (this.stream.getByte() << 16) |
  14481. (this.stream.getByte() << 8) | this.stream.getByte();
  14482. var nextByte = this.stream.getByte();
  14483. this.buffer = nextByte & ((1 << bufferLength) - 1);
  14484. return ((buffer << (8 - bufferLength)) |
  14485. ((nextByte & 0xFF) >> bufferLength)) >>> 0;
  14486. }
  14487. if (n === 8 && bufferLength === 0) {
  14488. return this.stream.getByte();
  14489. }
  14490. while (bufferLength < n) {
  14491. buffer = (buffer << 8) | this.stream.getByte();
  14492. bufferLength += 8;
  14493. }
  14494. bufferLength -= n;
  14495. this.bufferLength = bufferLength;
  14496. this.buffer = buffer & ((1 << bufferLength) - 1);
  14497. return buffer >> bufferLength;
  14498. },
  14499. align: function MeshStreamReader_align() {
  14500. this.buffer = 0;
  14501. this.bufferLength = 0;
  14502. },
  14503. readFlag: function MeshStreamReader_readFlag() {
  14504. return this.readBits(this.context.bitsPerFlag);
  14505. },
  14506. readCoordinate: function MeshStreamReader_readCoordinate() {
  14507. var bitsPerCoordinate = this.context.bitsPerCoordinate;
  14508. var xi = this.readBits(bitsPerCoordinate);
  14509. var yi = this.readBits(bitsPerCoordinate);
  14510. var decode = this.context.decode;
  14511. var scale = bitsPerCoordinate < 32 ? 1 / ((1 << bitsPerCoordinate) - 1) :
  14512. 2.3283064365386963e-10; // 2 ^ -32
  14513. return [
  14514. xi * scale * (decode[1] - decode[0]) + decode[0],
  14515. yi * scale * (decode[3] - decode[2]) + decode[2]
  14516. ];
  14517. },
  14518. readComponents: function MeshStreamReader_readComponents() {
  14519. var numComps = this.context.numComps;
  14520. var bitsPerComponent = this.context.bitsPerComponent;
  14521. var scale = bitsPerComponent < 32 ? 1 / ((1 << bitsPerComponent) - 1) :
  14522. 2.3283064365386963e-10; // 2 ^ -32
  14523. var decode = this.context.decode;
  14524. var components = this.tmpCompsBuf;
  14525. for (var i = 0, j = 4; i < numComps; i++, j += 2) {
  14526. var ci = this.readBits(bitsPerComponent);
  14527. components[i] = ci * scale * (decode[j + 1] - decode[j]) + decode[j];
  14528. }
  14529. var color = this.tmpCsCompsBuf;
  14530. if (this.context.colorFn) {
  14531. this.context.colorFn(components, 0, color, 0);
  14532. }
  14533. return this.context.colorSpace.getRgb(color, 0);
  14534. }
  14535. };
  14536. function decodeType4Shading(mesh, reader) {
  14537. var coords = mesh.coords;
  14538. var colors = mesh.colors;
  14539. var operators = [];
  14540. var ps = []; // not maintaining cs since that will match ps
  14541. var verticesLeft = 0; // assuming we have all data to start a new triangle
  14542. while (reader.hasData) {
  14543. var f = reader.readFlag();
  14544. var coord = reader.readCoordinate();
  14545. var color = reader.readComponents();
  14546. if (verticesLeft === 0) { // ignoring flags if we started a triangle
  14547. assert(0 <= f && f <= 2, 'Unknown type4 flag');
  14548. switch (f) {
  14549. case 0:
  14550. verticesLeft = 3;
  14551. break;
  14552. case 1:
  14553. ps.push(ps[ps.length - 2], ps[ps.length - 1]);
  14554. verticesLeft = 1;
  14555. break;
  14556. case 2:
  14557. ps.push(ps[ps.length - 3], ps[ps.length - 1]);
  14558. verticesLeft = 1;
  14559. break;
  14560. }
  14561. operators.push(f);
  14562. }
  14563. ps.push(coords.length);
  14564. coords.push(coord);
  14565. colors.push(color);
  14566. verticesLeft--;
  14567. reader.align();
  14568. }
  14569. var psPacked = new Int32Array(ps);
  14570. mesh.figures.push({
  14571. type: 'triangles',
  14572. coords: psPacked,
  14573. colors: psPacked
  14574. });
  14575. }
  14576. function decodeType5Shading(mesh, reader, verticesPerRow) {
  14577. var coords = mesh.coords;
  14578. var colors = mesh.colors;
  14579. var ps = []; // not maintaining cs since that will match ps
  14580. while (reader.hasData) {
  14581. var coord = reader.readCoordinate();
  14582. var color = reader.readComponents();
  14583. ps.push(coords.length);
  14584. coords.push(coord);
  14585. colors.push(color);
  14586. }
  14587. var psPacked = new Int32Array(ps);
  14588. mesh.figures.push({
  14589. type: 'lattice',
  14590. coords: psPacked,
  14591. colors: psPacked,
  14592. verticesPerRow: verticesPerRow
  14593. });
  14594. }
  14595. var MIN_SPLIT_PATCH_CHUNKS_AMOUNT = 3;
  14596. var MAX_SPLIT_PATCH_CHUNKS_AMOUNT = 20;
  14597. var TRIANGLE_DENSITY = 20; // count of triangles per entire mesh bounds
  14598. var getB = (function getBClosure() {
  14599. function buildB(count) {
  14600. var lut = [];
  14601. for (var i = 0; i <= count; i++) {
  14602. var t = i / count, t_ = 1 - t;
  14603. lut.push(new Float32Array([t_ * t_ * t_, 3 * t * t_ * t_,
  14604. 3 * t * t * t_, t * t * t]));
  14605. }
  14606. return lut;
  14607. }
  14608. var cache = [];
  14609. return function getB(count) {
  14610. if (!cache[count]) {
  14611. cache[count] = buildB(count);
  14612. }
  14613. return cache[count];
  14614. };
  14615. })();
  14616. function buildFigureFromPatch(mesh, index) {
  14617. var figure = mesh.figures[index];
  14618. assert(figure.type === 'patch', 'Unexpected patch mesh figure');
  14619. var coords = mesh.coords, colors = mesh.colors;
  14620. var pi = figure.coords;
  14621. var ci = figure.colors;
  14622. var figureMinX = Math.min(coords[pi[0]][0], coords[pi[3]][0],
  14623. coords[pi[12]][0], coords[pi[15]][0]);
  14624. var figureMinY = Math.min(coords[pi[0]][1], coords[pi[3]][1],
  14625. coords[pi[12]][1], coords[pi[15]][1]);
  14626. var figureMaxX = Math.max(coords[pi[0]][0], coords[pi[3]][0],
  14627. coords[pi[12]][0], coords[pi[15]][0]);
  14628. var figureMaxY = Math.max(coords[pi[0]][1], coords[pi[3]][1],
  14629. coords[pi[12]][1], coords[pi[15]][1]);
  14630. var splitXBy = Math.ceil((figureMaxX - figureMinX) * TRIANGLE_DENSITY /
  14631. (mesh.bounds[2] - mesh.bounds[0]));
  14632. splitXBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
  14633. Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitXBy));
  14634. var splitYBy = Math.ceil((figureMaxY - figureMinY) * TRIANGLE_DENSITY /
  14635. (mesh.bounds[3] - mesh.bounds[1]));
  14636. splitYBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,
  14637. Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitYBy));
  14638. var verticesPerRow = splitXBy + 1;
  14639. var figureCoords = new Int32Array((splitYBy + 1) * verticesPerRow);
  14640. var figureColors = new Int32Array((splitYBy + 1) * verticesPerRow);
  14641. var k = 0;
  14642. var cl = new Uint8Array(3), cr = new Uint8Array(3);
  14643. var c0 = colors[ci[0]], c1 = colors[ci[1]],
  14644. c2 = colors[ci[2]], c3 = colors[ci[3]];
  14645. var bRow = getB(splitYBy), bCol = getB(splitXBy);
  14646. for (var row = 0; row <= splitYBy; row++) {
  14647. cl[0] = ((c0[0] * (splitYBy - row) + c2[0] * row) / splitYBy) | 0;
  14648. cl[1] = ((c0[1] * (splitYBy - row) + c2[1] * row) / splitYBy) | 0;
  14649. cl[2] = ((c0[2] * (splitYBy - row) + c2[2] * row) / splitYBy) | 0;
  14650. cr[0] = ((c1[0] * (splitYBy - row) + c3[0] * row) / splitYBy) | 0;
  14651. cr[1] = ((c1[1] * (splitYBy - row) + c3[1] * row) / splitYBy) | 0;
  14652. cr[2] = ((c1[2] * (splitYBy - row) + c3[2] * row) / splitYBy) | 0;
  14653. for (var col = 0; col <= splitXBy; col++, k++) {
  14654. if ((row === 0 || row === splitYBy) &&
  14655. (col === 0 || col === splitXBy)) {
  14656. continue;
  14657. }
  14658. var x = 0, y = 0;
  14659. var q = 0;
  14660. for (var i = 0; i <= 3; i++) {
  14661. for (var j = 0; j <= 3; j++, q++) {
  14662. var m = bRow[row][i] * bCol[col][j];
  14663. x += coords[pi[q]][0] * m;
  14664. y += coords[pi[q]][1] * m;
  14665. }
  14666. }
  14667. figureCoords[k] = coords.length;
  14668. coords.push([x, y]);
  14669. figureColors[k] = colors.length;
  14670. var newColor = new Uint8Array(3);
  14671. newColor[0] = ((cl[0] * (splitXBy - col) + cr[0] * col) / splitXBy) | 0;
  14672. newColor[1] = ((cl[1] * (splitXBy - col) + cr[1] * col) / splitXBy) | 0;
  14673. newColor[2] = ((cl[2] * (splitXBy - col) + cr[2] * col) / splitXBy) | 0;
  14674. colors.push(newColor);
  14675. }
  14676. }
  14677. figureCoords[0] = pi[0];
  14678. figureColors[0] = ci[0];
  14679. figureCoords[splitXBy] = pi[3];
  14680. figureColors[splitXBy] = ci[1];
  14681. figureCoords[verticesPerRow * splitYBy] = pi[12];
  14682. figureColors[verticesPerRow * splitYBy] = ci[2];
  14683. figureCoords[verticesPerRow * splitYBy + splitXBy] = pi[15];
  14684. figureColors[verticesPerRow * splitYBy + splitXBy] = ci[3];
  14685. mesh.figures[index] = {
  14686. type: 'lattice',
  14687. coords: figureCoords,
  14688. colors: figureColors,
  14689. verticesPerRow: verticesPerRow
  14690. };
  14691. }
  14692. function decodeType6Shading(mesh, reader) {
  14693. // A special case of Type 7. The p11, p12, p21, p22 automatically filled
  14694. var coords = mesh.coords;
  14695. var colors = mesh.colors;
  14696. var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33
  14697. var cs = new Int32Array(4); // c00, c30, c03, c33
  14698. while (reader.hasData) {
  14699. var f = reader.readFlag();
  14700. assert(0 <= f && f <= 3, 'Unknown type6 flag');
  14701. var i, ii;
  14702. var pi = coords.length;
  14703. for (i = 0, ii = (f !== 0 ? 8 : 12); i < ii; i++) {
  14704. coords.push(reader.readCoordinate());
  14705. }
  14706. var ci = colors.length;
  14707. for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {
  14708. colors.push(reader.readComponents());
  14709. }
  14710. var tmp1, tmp2, tmp3, tmp4;
  14711. switch (f) {
  14712. case 0:
  14713. ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;
  14714. ps[ 8] = pi + 2; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;
  14715. ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 8;
  14716. ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;
  14717. cs[2] = ci + 1; cs[3] = ci + 2;
  14718. cs[0] = ci; cs[1] = ci + 3;
  14719. break;
  14720. case 1:
  14721. tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];
  14722. ps[12] = pi + 5; ps[13] = pi + 4; ps[14] = pi + 3; ps[15] = pi + 2;
  14723. ps[ 8] = pi + 6; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 1;
  14724. ps[ 4] = pi + 7; /* calculated below */ ps[ 7] = pi;
  14725. ps[ 0] = tmp1; ps[ 1] = tmp2; ps[ 2] = tmp3; ps[ 3] = tmp4;
  14726. tmp1 = cs[2]; tmp2 = cs[3];
  14727. cs[2] = ci + 1; cs[3] = ci;
  14728. cs[0] = tmp1; cs[1] = tmp2;
  14729. break;
  14730. case 2:
  14731. ps[12] = ps[15]; ps[13] = pi + 7; ps[14] = pi + 6; ps[15] = pi + 5;
  14732. ps[ 8] = ps[11]; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 4;
  14733. ps[ 4] = ps[7]; /* calculated below */ ps[ 7] = pi + 3;
  14734. ps[ 0] = ps[3]; ps[ 1] = pi; ps[ 2] = pi + 1; ps[ 3] = pi + 2;
  14735. cs[2] = cs[3]; cs[3] = ci + 1;
  14736. cs[0] = cs[1]; cs[1] = ci;
  14737. break;
  14738. case 3:
  14739. ps[12] = ps[0]; ps[13] = ps[1]; ps[14] = ps[2]; ps[15] = ps[3];
  14740. ps[ 8] = pi; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;
  14741. ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 6;
  14742. ps[ 0] = pi + 2; ps[ 1] = pi + 3; ps[ 2] = pi + 4; ps[ 3] = pi + 5;
  14743. cs[2] = cs[0]; cs[3] = cs[1];
  14744. cs[0] = ci; cs[1] = ci + 1;
  14745. break;
  14746. }
  14747. // set p11, p12, p21, p22
  14748. ps[5] = coords.length;
  14749. coords.push([
  14750. (-4 * coords[ps[0]][0] - coords[ps[15]][0] +
  14751. 6 * (coords[ps[4]][0] + coords[ps[1]][0]) -
  14752. 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +
  14753. 3 * (coords[ps[13]][0] + coords[ps[7]][0])) / 9,
  14754. (-4 * coords[ps[0]][1] - coords[ps[15]][1] +
  14755. 6 * (coords[ps[4]][1] + coords[ps[1]][1]) -
  14756. 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +
  14757. 3 * (coords[ps[13]][1] + coords[ps[7]][1])) / 9
  14758. ]);
  14759. ps[6] = coords.length;
  14760. coords.push([
  14761. (-4 * coords[ps[3]][0] - coords[ps[12]][0] +
  14762. 6 * (coords[ps[2]][0] + coords[ps[7]][0]) -
  14763. 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +
  14764. 3 * (coords[ps[4]][0] + coords[ps[14]][0])) / 9,
  14765. (-4 * coords[ps[3]][1] - coords[ps[12]][1] +
  14766. 6 * (coords[ps[2]][1] + coords[ps[7]][1]) -
  14767. 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +
  14768. 3 * (coords[ps[4]][1] + coords[ps[14]][1])) / 9
  14769. ]);
  14770. ps[9] = coords.length;
  14771. coords.push([
  14772. (-4 * coords[ps[12]][0] - coords[ps[3]][0] +
  14773. 6 * (coords[ps[8]][0] + coords[ps[13]][0]) -
  14774. 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +
  14775. 3 * (coords[ps[11]][0] + coords[ps[1]][0])) / 9,
  14776. (-4 * coords[ps[12]][1] - coords[ps[3]][1] +
  14777. 6 * (coords[ps[8]][1] + coords[ps[13]][1]) -
  14778. 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +
  14779. 3 * (coords[ps[11]][1] + coords[ps[1]][1])) / 9
  14780. ]);
  14781. ps[10] = coords.length;
  14782. coords.push([
  14783. (-4 * coords[ps[15]][0] - coords[ps[0]][0] +
  14784. 6 * (coords[ps[11]][0] + coords[ps[14]][0]) -
  14785. 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +
  14786. 3 * (coords[ps[2]][0] + coords[ps[8]][0])) / 9,
  14787. (-4 * coords[ps[15]][1] - coords[ps[0]][1] +
  14788. 6 * (coords[ps[11]][1] + coords[ps[14]][1]) -
  14789. 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +
  14790. 3 * (coords[ps[2]][1] + coords[ps[8]][1])) / 9
  14791. ]);
  14792. mesh.figures.push({
  14793. type: 'patch',
  14794. coords: new Int32Array(ps), // making copies of ps and cs
  14795. colors: new Int32Array(cs)
  14796. });
  14797. }
  14798. }
  14799. function decodeType7Shading(mesh, reader) {
  14800. var coords = mesh.coords;
  14801. var colors = mesh.colors;
  14802. var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33
  14803. var cs = new Int32Array(4); // c00, c30, c03, c33
  14804. while (reader.hasData) {
  14805. var f = reader.readFlag();
  14806. assert(0 <= f && f <= 3, 'Unknown type7 flag');
  14807. var i, ii;
  14808. var pi = coords.length;
  14809. for (i = 0, ii = (f !== 0 ? 12 : 16); i < ii; i++) {
  14810. coords.push(reader.readCoordinate());
  14811. }
  14812. var ci = colors.length;
  14813. for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {
  14814. colors.push(reader.readComponents());
  14815. }
  14816. var tmp1, tmp2, tmp3, tmp4;
  14817. switch (f) {
  14818. case 0:
  14819. ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;
  14820. ps[ 8] = pi + 2; ps[ 9] = pi + 13; ps[10] = pi + 14; ps[11] = pi + 7;
  14821. ps[ 4] = pi + 1; ps[ 5] = pi + 12; ps[ 6] = pi + 15; ps[ 7] = pi + 8;
  14822. ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;
  14823. cs[2] = ci + 1; cs[3] = ci + 2;
  14824. cs[0] = ci; cs[1] = ci + 3;
  14825. break;
  14826. case 1:
  14827. tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];
  14828. ps[12] = pi + 5; ps[13] = pi + 4; ps[14] = pi + 3; ps[15] = pi + 2;
  14829. ps[ 8] = pi + 6; ps[ 9] = pi + 11; ps[10] = pi + 10; ps[11] = pi + 1;
  14830. ps[ 4] = pi + 7; ps[ 5] = pi + 8; ps[ 6] = pi + 9; ps[ 7] = pi;
  14831. ps[ 0] = tmp1; ps[ 1] = tmp2; ps[ 2] = tmp3; ps[ 3] = tmp4;
  14832. tmp1 = cs[2]; tmp2 = cs[3];
  14833. cs[2] = ci + 1; cs[3] = ci;
  14834. cs[0] = tmp1; cs[1] = tmp2;
  14835. break;
  14836. case 2:
  14837. ps[12] = ps[15]; ps[13] = pi + 7; ps[14] = pi + 6; ps[15] = pi + 5;
  14838. ps[ 8] = ps[11]; ps[ 9] = pi + 8; ps[10] = pi + 11; ps[11] = pi + 4;
  14839. ps[ 4] = ps[7]; ps[ 5] = pi + 9; ps[ 6] = pi + 10; ps[ 7] = pi + 3;
  14840. ps[ 0] = ps[3]; ps[ 1] = pi; ps[ 2] = pi + 1; ps[ 3] = pi + 2;
  14841. cs[2] = cs[3]; cs[3] = ci + 1;
  14842. cs[0] = cs[1]; cs[1] = ci;
  14843. break;
  14844. case 3:
  14845. ps[12] = ps[0]; ps[13] = ps[1]; ps[14] = ps[2]; ps[15] = ps[3];
  14846. ps[ 8] = pi; ps[ 9] = pi + 9; ps[10] = pi + 8; ps[11] = pi + 7;
  14847. ps[ 4] = pi + 1; ps[ 5] = pi + 10; ps[ 6] = pi + 11; ps[ 7] = pi + 6;
  14848. ps[ 0] = pi + 2; ps[ 1] = pi + 3; ps[ 2] = pi + 4; ps[ 3] = pi + 5;
  14849. cs[2] = cs[0]; cs[3] = cs[1];
  14850. cs[0] = ci; cs[1] = ci + 1;
  14851. break;
  14852. }
  14853. mesh.figures.push({
  14854. type: 'patch',
  14855. coords: new Int32Array(ps), // making copies of ps and cs
  14856. colors: new Int32Array(cs)
  14857. });
  14858. }
  14859. }
  14860. function updateBounds(mesh) {
  14861. var minX = mesh.coords[0][0], minY = mesh.coords[0][1],
  14862. maxX = minX, maxY = minY;
  14863. for (var i = 1, ii = mesh.coords.length; i < ii; i++) {
  14864. var x = mesh.coords[i][0], y = mesh.coords[i][1];
  14865. minX = minX > x ? x : minX;
  14866. minY = minY > y ? y : minY;
  14867. maxX = maxX < x ? x : maxX;
  14868. maxY = maxY < y ? y : maxY;
  14869. }
  14870. mesh.bounds = [minX, minY, maxX, maxY];
  14871. }
  14872. function packData(mesh) {
  14873. var i, ii, j, jj;
  14874. var coords = mesh.coords;
  14875. var coordsPacked = new Float32Array(coords.length * 2);
  14876. for (i = 0, j = 0, ii = coords.length; i < ii; i++) {
  14877. var xy = coords[i];
  14878. coordsPacked[j++] = xy[0];
  14879. coordsPacked[j++] = xy[1];
  14880. }
  14881. mesh.coords = coordsPacked;
  14882. var colors = mesh.colors;
  14883. var colorsPacked = new Uint8Array(colors.length * 3);
  14884. for (i = 0, j = 0, ii = colors.length; i < ii; i++) {
  14885. var c = colors[i];
  14886. colorsPacked[j++] = c[0];
  14887. colorsPacked[j++] = c[1];
  14888. colorsPacked[j++] = c[2];
  14889. }
  14890. mesh.colors = colorsPacked;
  14891. var figures = mesh.figures;
  14892. for (i = 0, ii = figures.length; i < ii; i++) {
  14893. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  14894. for (j = 0, jj = ps.length; j < jj; j++) {
  14895. ps[j] *= 2;
  14896. cs[j] *= 3;
  14897. }
  14898. }
  14899. }
  14900. function Mesh(stream, matrix, xref, res) {
  14901. assert(isStream(stream), 'Mesh data is not a stream');
  14902. var dict = stream.dict;
  14903. this.matrix = matrix;
  14904. this.shadingType = dict.get('ShadingType');
  14905. this.type = 'Pattern';
  14906. this.bbox = dict.get('BBox');
  14907. var cs = dict.get('ColorSpace', 'CS');
  14908. cs = ColorSpace.parse(cs, xref, res);
  14909. this.cs = cs;
  14910. this.background = dict.has('Background') ?
  14911. cs.getRgb(dict.get('Background'), 0) : null;
  14912. var fnObj = dict.get('Function');
  14913. var fn = fnObj ? PDFFunction.parseArray(xref, fnObj) : null;
  14914. this.coords = [];
  14915. this.colors = [];
  14916. this.figures = [];
  14917. var decodeContext = {
  14918. bitsPerCoordinate: dict.get('BitsPerCoordinate'),
  14919. bitsPerComponent: dict.get('BitsPerComponent'),
  14920. bitsPerFlag: dict.get('BitsPerFlag'),
  14921. decode: dict.get('Decode'),
  14922. colorFn: fn,
  14923. colorSpace: cs,
  14924. numComps: fn ? 1 : cs.numComps
  14925. };
  14926. var reader = new MeshStreamReader(stream, decodeContext);
  14927. var patchMesh = false;
  14928. switch (this.shadingType) {
  14929. case PatternType.FREE_FORM_MESH:
  14930. decodeType4Shading(this, reader);
  14931. break;
  14932. case PatternType.LATTICE_FORM_MESH:
  14933. var verticesPerRow = dict.get('VerticesPerRow') | 0;
  14934. assert(verticesPerRow >= 2, 'Invalid VerticesPerRow');
  14935. decodeType5Shading(this, reader, verticesPerRow);
  14936. break;
  14937. case PatternType.COONS_PATCH_MESH:
  14938. decodeType6Shading(this, reader);
  14939. patchMesh = true;
  14940. break;
  14941. case PatternType.TENSOR_PATCH_MESH:
  14942. decodeType7Shading(this, reader);
  14943. patchMesh = true;
  14944. break;
  14945. default:
  14946. error('Unsupported mesh type.');
  14947. break;
  14948. }
  14949. if (patchMesh) {
  14950. // dirty bounds calculation for determining, how dense shall be triangles
  14951. updateBounds(this);
  14952. for (var i = 0, ii = this.figures.length; i < ii; i++) {
  14953. buildFigureFromPatch(this, i);
  14954. }
  14955. }
  14956. // calculate bounds
  14957. updateBounds(this);
  14958. packData(this);
  14959. }
  14960. Mesh.prototype = {
  14961. getIR: function Mesh_getIR() {
  14962. return ['Mesh', this.shadingType, this.coords, this.colors, this.figures,
  14963. this.bounds, this.matrix, this.bbox, this.background];
  14964. }
  14965. };
  14966. return Mesh;
  14967. })();
  14968. Shadings.Dummy = (function DummyClosure() {
  14969. function Dummy() {
  14970. this.type = 'Pattern';
  14971. }
  14972. Dummy.prototype = {
  14973. getIR: function Dummy_getIR() {
  14974. return ['Dummy'];
  14975. }
  14976. };
  14977. return Dummy;
  14978. })();
  14979. function getTilingPatternIR(operatorList, dict, args) {
  14980. var matrix = dict.get('Matrix');
  14981. var bbox = dict.get('BBox');
  14982. var xstep = dict.get('XStep');
  14983. var ystep = dict.get('YStep');
  14984. var paintType = dict.get('PaintType');
  14985. var tilingType = dict.get('TilingType');
  14986. return [
  14987. 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep,
  14988. paintType, tilingType
  14989. ];
  14990. }
  14991. var PartialEvaluator = (function PartialEvaluatorClosure() {
  14992. function PartialEvaluator(pdfManager, xref, handler, pageIndex,
  14993. uniquePrefix, idCounters, fontCache) {
  14994. this.pdfManager = pdfManager;
  14995. this.xref = xref;
  14996. this.handler = handler;
  14997. this.pageIndex = pageIndex;
  14998. this.uniquePrefix = uniquePrefix;
  14999. this.idCounters = idCounters;
  15000. this.fontCache = fontCache;
  15001. }
  15002. // Trying to minimize Date.now() usage and check every 100 time
  15003. var TIME_SLOT_DURATION_MS = 20;
  15004. var CHECK_TIME_EVERY = 100;
  15005. function TimeSlotManager() {
  15006. this.reset();
  15007. }
  15008. TimeSlotManager.prototype = {
  15009. check: function TimeSlotManager_check() {
  15010. if (++this.checked < CHECK_TIME_EVERY) {
  15011. return false;
  15012. }
  15013. this.checked = 0;
  15014. return this.endTime <= Date.now();
  15015. },
  15016. reset: function TimeSlotManager_reset() {
  15017. this.endTime = Date.now() + TIME_SLOT_DURATION_MS;
  15018. this.checked = 0;
  15019. }
  15020. };
  15021. var deferred = Promise.resolve();
  15022. var TILING_PATTERN = 1, SHADING_PATTERN = 2;
  15023. PartialEvaluator.prototype = {
  15024. hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {
  15025. if (!isDict(resources)) {
  15026. return false;
  15027. }
  15028. var processed = Object.create(null);
  15029. if (resources.objId) {
  15030. processed[resources.objId] = true;
  15031. }
  15032. var nodes = [resources];
  15033. while (nodes.length) {
  15034. var key;
  15035. var node = nodes.shift();
  15036. // First check the current resources for blend modes.
  15037. var graphicStates = node.get('ExtGState');
  15038. if (isDict(graphicStates)) {
  15039. graphicStates = graphicStates.getAll();
  15040. for (key in graphicStates) {
  15041. var graphicState = graphicStates[key];
  15042. var bm = graphicState['BM'];
  15043. if (isName(bm) && bm.name !== 'Normal') {
  15044. return true;
  15045. }
  15046. }
  15047. }
  15048. // Descend into the XObjects to look for more resources and blend modes.
  15049. var xObjects = node.get('XObject');
  15050. if (!isDict(xObjects)) {
  15051. continue;
  15052. }
  15053. xObjects = xObjects.getAll();
  15054. for (key in xObjects) {
  15055. var xObject = xObjects[key];
  15056. if (!isStream(xObject)) {
  15057. continue;
  15058. }
  15059. if (xObject.dict.objId) {
  15060. if (processed[xObject.dict.objId]) {
  15061. // stream has objId and is processed already
  15062. continue;
  15063. }
  15064. processed[xObject.dict.objId] = true;
  15065. }
  15066. var xResources = xObject.dict.get('Resources');
  15067. // Checking objId to detect an infinite loop.
  15068. if (isDict(xResources) &&
  15069. (!xResources.objId || !processed[xResources.objId])) {
  15070. nodes.push(xResources);
  15071. if (xResources.objId) {
  15072. processed[xResources.objId] = true;
  15073. }
  15074. }
  15075. }
  15076. }
  15077. return false;
  15078. },
  15079. buildFormXObject: function PartialEvaluator_buildFormXObject(resources,
  15080. xobj, smask,
  15081. operatorList,
  15082. initialState) {
  15083. var matrix = xobj.dict.get('Matrix');
  15084. var bbox = xobj.dict.get('BBox');
  15085. var group = xobj.dict.get('Group');
  15086. if (group) {
  15087. var groupOptions = {
  15088. matrix: matrix,
  15089. bbox: bbox,
  15090. smask: smask,
  15091. isolated: false,
  15092. knockout: false
  15093. };
  15094. var groupSubtype = group.get('S');
  15095. var colorSpace;
  15096. if (isName(groupSubtype) && groupSubtype.name === 'Transparency') {
  15097. groupOptions.isolated = (group.get('I') || false);
  15098. groupOptions.knockout = (group.get('K') || false);
  15099. colorSpace = (group.has('CS') ?
  15100. ColorSpace.parse(group.get('CS'), this.xref, resources) : null);
  15101. }
  15102. if (smask && smask.backdrop) {
  15103. colorSpace = colorSpace || ColorSpace.singletons.rgb;
  15104. smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
  15105. }
  15106. operatorList.addOp(OPS.beginGroup, [groupOptions]);
  15107. }
  15108. operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]);
  15109. return this.getOperatorList(xobj,
  15110. (xobj.dict.get('Resources') || resources), operatorList, initialState).
  15111. then(function () {
  15112. operatorList.addOp(OPS.paintFormXObjectEnd, []);
  15113. if (group) {
  15114. operatorList.addOp(OPS.endGroup, [groupOptions]);
  15115. }
  15116. });
  15117. },
  15118. buildPaintImageXObject:
  15119. function PartialEvaluator_buildPaintImageXObject(resources, image,
  15120. inline, operatorList,
  15121. cacheKey, imageCache) {
  15122. var self = this;
  15123. var dict = image.dict;
  15124. var w = dict.get('Width', 'W');
  15125. var h = dict.get('Height', 'H');
  15126. if (!(w && isNum(w)) || !(h && isNum(h))) {
  15127. warn('Image dimensions are missing, or not numbers.');
  15128. return;
  15129. }
  15130. if (PDFJS.maxImageSize !== -1 && w * h > PDFJS.maxImageSize) {
  15131. warn('Image exceeded maximum allowed size and was removed.');
  15132. return;
  15133. }
  15134. var imageMask = (dict.get('ImageMask', 'IM') || false);
  15135. var imgData, args;
  15136. if (imageMask) {
  15137. // This depends on a tmpCanvas being filled with the
  15138. // current fillStyle, such that processing the pixel
  15139. // data can't be done here. Instead of creating a
  15140. // complete PDFImage, only read the information needed
  15141. // for later.
  15142. var width = dict.get('Width', 'W');
  15143. var height = dict.get('Height', 'H');
  15144. var bitStrideLength = (width + 7) >> 3;
  15145. var imgArray = image.getBytes(bitStrideLength * height);
  15146. var decode = dict.get('Decode', 'D');
  15147. var inverseDecode = (!!decode && decode[0] > 0);
  15148. imgData = PDFImage.createMask(imgArray, width, height,
  15149. image instanceof DecodeStream,
  15150. inverseDecode);
  15151. imgData.cached = true;
  15152. args = [imgData];
  15153. operatorList.addOp(OPS.paintImageMaskXObject, args);
  15154. if (cacheKey) {
  15155. imageCache[cacheKey] = {
  15156. fn: OPS.paintImageMaskXObject,
  15157. args: args
  15158. };
  15159. }
  15160. return;
  15161. }
  15162. var softMask = (dict.get('SMask', 'SM') || false);
  15163. var mask = (dict.get('Mask') || false);
  15164. var SMALL_IMAGE_DIMENSIONS = 200;
  15165. // Inlining small images into the queue as RGB data
  15166. if (inline && !softMask && !mask && !(image instanceof JpegStream) &&
  15167. (w + h) < SMALL_IMAGE_DIMENSIONS) {
  15168. var imageObj = new PDFImage(this.xref, resources, image,
  15169. inline, null, null);
  15170. // We force the use of RGBA_32BPP images here, because we can't handle
  15171. // any other kind.
  15172. imgData = imageObj.createImageData(/* forceRGBA = */ true);
  15173. operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);
  15174. return;
  15175. }
  15176. // If there is no imageMask, create the PDFImage and a lot
  15177. // of image processing can be done here.
  15178. var uniquePrefix = (this.uniquePrefix || '');
  15179. var objId = 'img_' + uniquePrefix + (++this.idCounters.obj);
  15180. operatorList.addDependency(objId);
  15181. args = [objId, w, h];
  15182. if (!softMask && !mask && image instanceof JpegStream &&
  15183. image.isNativelySupported(this.xref, resources)) {
  15184. // These JPEGs don't need any more processing so we can just send it.
  15185. operatorList.addOp(OPS.paintJpegXObject, args);
  15186. this.handler.send('obj',
  15187. [objId, this.pageIndex, 'JpegStream', image.getIR()]);
  15188. return;
  15189. }
  15190. PDFImage.buildImage(self.handler, self.xref, resources, image, inline).
  15191. then(function(imageObj) {
  15192. var imgData = imageObj.createImageData(/* forceRGBA = */ false);
  15193. self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData],
  15194. [imgData.data.buffer]);
  15195. }).then(undefined, function (reason) {
  15196. warn('Unable to decode image: ' + reason);
  15197. self.handler.send('obj', [objId, self.pageIndex, 'Image', null]);
  15198. });
  15199. operatorList.addOp(OPS.paintImageXObject, args);
  15200. if (cacheKey) {
  15201. imageCache[cacheKey] = {
  15202. fn: OPS.paintImageXObject,
  15203. args: args
  15204. };
  15205. }
  15206. },
  15207. handleSMask: function PartialEvaluator_handleSmask(smask, resources,
  15208. operatorList,
  15209. stateManager) {
  15210. var smaskContent = smask.get('G');
  15211. var smaskOptions = {
  15212. subtype: smask.get('S').name,
  15213. backdrop: smask.get('BC')
  15214. };
  15215. return this.buildFormXObject(resources, smaskContent, smaskOptions,
  15216. operatorList, stateManager.state.clone());
  15217. },
  15218. handleTilingType:
  15219. function PartialEvaluator_handleTilingType(fn, args, resources,
  15220. pattern, patternDict,
  15221. operatorList) {
  15222. // Create an IR of the pattern code.
  15223. var tilingOpList = new OperatorList();
  15224. return this.getOperatorList(pattern,
  15225. (patternDict.get('Resources') || resources), tilingOpList).
  15226. then(function () {
  15227. // Add the dependencies to the parent operator list so they are
  15228. // resolved before sub operator list is executed synchronously.
  15229. operatorList.addDependencies(tilingOpList.dependencies);
  15230. operatorList.addOp(fn, getTilingPatternIR({
  15231. fnArray: tilingOpList.fnArray,
  15232. argsArray: tilingOpList.argsArray
  15233. }, patternDict, args));
  15234. });
  15235. },
  15236. handleSetFont:
  15237. function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef,
  15238. operatorList, state) {
  15239. // TODO(mack): Not needed?
  15240. var fontName;
  15241. if (fontArgs) {
  15242. fontArgs = fontArgs.slice();
  15243. fontName = fontArgs[0].name;
  15244. }
  15245. var self = this;
  15246. return this.loadFont(fontName, fontRef, this.xref, resources).then(
  15247. function (translated) {
  15248. if (!translated.font.isType3Font) {
  15249. return translated;
  15250. }
  15251. return translated.loadType3Data(self, resources, operatorList).then(
  15252. function () {
  15253. return translated;
  15254. });
  15255. }).then(function (translated) {
  15256. state.font = translated.font;
  15257. translated.send(self.handler);
  15258. return translated.loadedName;
  15259. });
  15260. },
  15261. handleText: function PartialEvaluator_handleText(chars, state) {
  15262. var font = state.font;
  15263. var glyphs = font.charsToGlyphs(chars);
  15264. var isAddToPathSet = !!(state.textRenderingMode &
  15265. TextRenderingMode.ADD_TO_PATH_FLAG);
  15266. if (font.data && (isAddToPathSet || PDFJS.disableFontFace)) {
  15267. var buildPath = function (fontChar) {
  15268. if (!font.renderer.hasBuiltPath(fontChar)) {
  15269. var path = font.renderer.getPathJs(fontChar);
  15270. this.handler.send('commonobj', [
  15271. font.loadedName + '_path_' + fontChar,
  15272. 'FontPath',
  15273. path
  15274. ]);
  15275. }
  15276. }.bind(this);
  15277. for (var i = 0, ii = glyphs.length; i < ii; i++) {
  15278. var glyph = glyphs[i];
  15279. if (glyph === null) {
  15280. continue;
  15281. }
  15282. buildPath(glyph.fontChar);
  15283. // If the glyph has an accent we need to build a path for its
  15284. // fontChar too, otherwise CanvasGraphics_paintChar will fail.
  15285. var accent = glyph.accent;
  15286. if (accent && accent.fontChar) {
  15287. buildPath(accent.fontChar);
  15288. }
  15289. }
  15290. }
  15291. return glyphs;
  15292. },
  15293. setGState: function PartialEvaluator_setGState(resources, gState,
  15294. operatorList, xref,
  15295. stateManager) {
  15296. // This array holds the converted/processed state data.
  15297. var gStateObj = [];
  15298. var gStateMap = gState.map;
  15299. var self = this;
  15300. var promise = Promise.resolve();
  15301. for (var key in gStateMap) {
  15302. var value = gStateMap[key];
  15303. switch (key) {
  15304. case 'Type':
  15305. break;
  15306. case 'LW':
  15307. case 'LC':
  15308. case 'LJ':
  15309. case 'ML':
  15310. case 'D':
  15311. case 'RI':
  15312. case 'FL':
  15313. case 'CA':
  15314. case 'ca':
  15315. gStateObj.push([key, value]);
  15316. break;
  15317. case 'Font':
  15318. promise = promise.then(function () {
  15319. return self.handleSetFont(resources, null, value[0],
  15320. operatorList, stateManager.state).
  15321. then(function (loadedName) {
  15322. operatorList.addDependency(loadedName);
  15323. gStateObj.push([key, [loadedName, value[1]]]);
  15324. });
  15325. });
  15326. break;
  15327. case 'BM':
  15328. gStateObj.push([key, value]);
  15329. break;
  15330. case 'SMask':
  15331. if (isName(value) && value.name === 'None') {
  15332. gStateObj.push([key, false]);
  15333. break;
  15334. }
  15335. var dict = xref.fetchIfRef(value);
  15336. if (isDict(dict)) {
  15337. promise = promise.then(function () {
  15338. return self.handleSMask(dict, resources, operatorList,
  15339. stateManager);
  15340. });
  15341. gStateObj.push([key, true]);
  15342. } else {
  15343. warn('Unsupported SMask type');
  15344. }
  15345. break;
  15346. // Only generate info log messages for the following since
  15347. // they are unlikely to have a big impact on the rendering.
  15348. case 'OP':
  15349. case 'op':
  15350. case 'OPM':
  15351. case 'BG':
  15352. case 'BG2':
  15353. case 'UCR':
  15354. case 'UCR2':
  15355. case 'TR':
  15356. case 'TR2':
  15357. case 'HT':
  15358. case 'SM':
  15359. case 'SA':
  15360. case 'AIS':
  15361. case 'TK':
  15362. // TODO implement these operators.
  15363. info('graphic state operator ' + key);
  15364. break;
  15365. default:
  15366. info('Unknown graphic state operator ' + key);
  15367. break;
  15368. }
  15369. }
  15370. return promise.then(function () {
  15371. if (gStateObj.length >= 0) {
  15372. operatorList.addOp(OPS.setGState, [gStateObj]);
  15373. }
  15374. });
  15375. },
  15376. loadFont: function PartialEvaluator_loadFont(fontName, font, xref,
  15377. resources) {
  15378. function errorFont() {
  15379. return Promise.resolve(new TranslatedFont('g_font_error',
  15380. new ErrorFont('Font ' + fontName + ' is not available'), font));
  15381. }
  15382. var fontRef;
  15383. if (font) { // Loading by ref.
  15384. assert(isRef(font));
  15385. fontRef = font;
  15386. } else { // Loading by name.
  15387. var fontRes = resources.get('Font');
  15388. if (fontRes) {
  15389. fontRef = fontRes.getRaw(fontName);
  15390. } else {
  15391. warn('fontRes not available');
  15392. return errorFont();
  15393. }
  15394. }
  15395. if (!fontRef) {
  15396. warn('fontRef not available');
  15397. return errorFont();
  15398. }
  15399. if (this.fontCache.has(fontRef)) {
  15400. return this.fontCache.get(fontRef);
  15401. }
  15402. font = xref.fetchIfRef(fontRef);
  15403. if (!isDict(font)) {
  15404. return errorFont();
  15405. }
  15406. // We are holding font.translated references just for fontRef that are not
  15407. // dictionaries (Dict). See explanation below.
  15408. if (font.translated) {
  15409. return font.translated;
  15410. }
  15411. var fontCapability = createPromiseCapability();
  15412. var preEvaluatedFont = this.preEvaluateFont(font, xref);
  15413. var descriptor = preEvaluatedFont.descriptor;
  15414. var fontID = fontRef.num + '_' + fontRef.gen;
  15415. if (isDict(descriptor)) {
  15416. if (!descriptor.fontAliases) {
  15417. descriptor.fontAliases = Object.create(null);
  15418. }
  15419. var fontAliases = descriptor.fontAliases;
  15420. var hash = preEvaluatedFont.hash;
  15421. if (fontAliases[hash]) {
  15422. var aliasFontRef = fontAliases[hash].aliasRef;
  15423. if (aliasFontRef && this.fontCache.has(aliasFontRef)) {
  15424. this.fontCache.putAlias(fontRef, aliasFontRef);
  15425. return this.fontCache.get(fontRef);
  15426. }
  15427. }
  15428. if (!fontAliases[hash]) {
  15429. fontAliases[hash] = {
  15430. fontID: Font.getFontID()
  15431. };
  15432. }
  15433. fontAliases[hash].aliasRef = fontRef;
  15434. fontID = fontAliases[hash].fontID;
  15435. }
  15436. // Workaround for bad PDF generators that don't reference fonts
  15437. // properly, i.e. by not using an object identifier.
  15438. // Check if the fontRef is a Dict (as opposed to a standard object),
  15439. // in which case we don't cache the font and instead reference it by
  15440. // fontName in font.loadedName below.
  15441. var fontRefIsDict = isDict(fontRef);
  15442. if (!fontRefIsDict) {
  15443. this.fontCache.put(fontRef, fontCapability.promise);
  15444. }
  15445. // Keep track of each font we translated so the caller can
  15446. // load them asynchronously before calling display on a page.
  15447. font.loadedName = 'g_font_' + (fontRefIsDict ?
  15448. fontName.replace(/\W/g, '') : fontID);
  15449. font.translated = fontCapability.promise;
  15450. // TODO move promises into translate font
  15451. var translatedPromise;
  15452. try {
  15453. translatedPromise = Promise.resolve(
  15454. this.translateFont(preEvaluatedFont, xref));
  15455. } catch (e) {
  15456. translatedPromise = Promise.reject(e);
  15457. }
  15458. translatedPromise.then(function (translatedFont) {
  15459. if (translatedFont.fontType !== undefined) {
  15460. var xrefFontStats = xref.stats.fontTypes;
  15461. xrefFontStats[translatedFont.fontType] = true;
  15462. }
  15463. fontCapability.resolve(new TranslatedFont(font.loadedName,
  15464. translatedFont, font));
  15465. }, function (reason) {
  15466. // TODO fontCapability.reject?
  15467. UnsupportedManager.notify(UNSUPPORTED_FEATURES.font);
  15468. try {
  15469. // error, but it's still nice to have font type reported
  15470. var descriptor = preEvaluatedFont.descriptor;
  15471. var fontFile3 = descriptor && descriptor.get('FontFile3');
  15472. var subtype = fontFile3 && fontFile3.get('Subtype');
  15473. var fontType = getFontType(preEvaluatedFont.type,
  15474. subtype && subtype.name);
  15475. var xrefFontStats = xref.stats.fontTypes;
  15476. xrefFontStats[fontType] = true;
  15477. } catch (ex) { }
  15478. fontCapability.resolve(new TranslatedFont(font.loadedName,
  15479. new ErrorFont(reason instanceof Error ? reason.message : reason),
  15480. font));
  15481. });
  15482. return fontCapability.promise;
  15483. },
  15484. buildPath: function PartialEvaluator_buildPath(operatorList, fn, args) {
  15485. var lastIndex = operatorList.length - 1;
  15486. if (!args) {
  15487. args = [];
  15488. }
  15489. if (lastIndex < 0 ||
  15490. operatorList.fnArray[lastIndex] !== OPS.constructPath) {
  15491. operatorList.addOp(OPS.constructPath, [[fn], args]);
  15492. } else {
  15493. var opArgs = operatorList.argsArray[lastIndex];
  15494. opArgs[0].push(fn);
  15495. Array.prototype.push.apply(opArgs[1], args);
  15496. }
  15497. },
  15498. handleColorN: function PartialEvaluator_handleColorN(operatorList, fn, args,
  15499. cs, patterns, resources, xref) {
  15500. // compile tiling patterns
  15501. var patternName = args[args.length - 1];
  15502. // SCN/scn applies patterns along with normal colors
  15503. var pattern;
  15504. if (isName(patternName) &&
  15505. (pattern = patterns.get(patternName.name))) {
  15506. var dict = (isStream(pattern) ? pattern.dict : pattern);
  15507. var typeNum = dict.get('PatternType');
  15508. if (typeNum === TILING_PATTERN) {
  15509. var color = cs.base ? cs.base.getRgb(args, 0) : null;
  15510. return this.handleTilingType(fn, color, resources, pattern,
  15511. dict, operatorList);
  15512. } else if (typeNum === SHADING_PATTERN) {
  15513. var shading = dict.get('Shading');
  15514. var matrix = dict.get('Matrix');
  15515. pattern = Pattern.parseShading(shading, matrix, xref, resources);
  15516. operatorList.addOp(fn, pattern.getIR());
  15517. return Promise.resolve();
  15518. } else {
  15519. return Promise.reject('Unknown PatternType: ' + typeNum);
  15520. }
  15521. }
  15522. // TODO shall we fail here?
  15523. operatorList.addOp(fn, args);
  15524. return Promise.resolve();
  15525. },
  15526. getOperatorList: function PartialEvaluator_getOperatorList(stream,
  15527. resources,
  15528. operatorList,
  15529. initialState) {
  15530. var self = this;
  15531. var xref = this.xref;
  15532. var imageCache = {};
  15533. assert(operatorList);
  15534. resources = (resources || Dict.empty);
  15535. var xobjs = (resources.get('XObject') || Dict.empty);
  15536. var patterns = (resources.get('Pattern') || Dict.empty);
  15537. var stateManager = new StateManager(initialState || new EvalState());
  15538. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  15539. var timeSlotManager = new TimeSlotManager();
  15540. return new Promise(function next(resolve, reject) {
  15541. timeSlotManager.reset();
  15542. var stop, operation = {}, i, ii, cs;
  15543. while (!(stop = timeSlotManager.check())) {
  15544. // The arguments parsed by read() are used beyond this loop, so we
  15545. // cannot reuse the same array on each iteration. Therefore we pass
  15546. // in |null| as the initial value (see the comment on
  15547. // EvaluatorPreprocessor_read() for why).
  15548. operation.args = null;
  15549. if (!(preprocessor.read(operation))) {
  15550. break;
  15551. }
  15552. var args = operation.args;
  15553. var fn = operation.fn;
  15554. switch (fn | 0) {
  15555. case OPS.paintXObject:
  15556. if (args[0].code) {
  15557. break;
  15558. }
  15559. // eagerly compile XForm objects
  15560. var name = args[0].name;
  15561. if (imageCache[name] !== undefined) {
  15562. operatorList.addOp(imageCache[name].fn, imageCache[name].args);
  15563. args = null;
  15564. continue;
  15565. }
  15566. var xobj = xobjs.get(name);
  15567. if (xobj) {
  15568. assert(isStream(xobj), 'XObject should be a stream');
  15569. var type = xobj.dict.get('Subtype');
  15570. assert(isName(type),
  15571. 'XObject should have a Name subtype');
  15572. if (type.name === 'Form') {
  15573. stateManager.save();
  15574. return self.buildFormXObject(resources, xobj, null,
  15575. operatorList,
  15576. stateManager.state.clone()).
  15577. then(function () {
  15578. stateManager.restore();
  15579. next(resolve, reject);
  15580. }, reject);
  15581. } else if (type.name === 'Image') {
  15582. self.buildPaintImageXObject(resources, xobj, false,
  15583. operatorList, name, imageCache);
  15584. args = null;
  15585. continue;
  15586. } else if (type.name === 'PS') {
  15587. // PostScript XObjects are unused when viewing documents.
  15588. // See section 4.7.1 of Adobe's PDF reference.
  15589. info('Ignored XObject subtype PS');
  15590. continue;
  15591. } else {
  15592. error('Unhandled XObject subtype ' + type.name);
  15593. }
  15594. }
  15595. break;
  15596. case OPS.setFont:
  15597. var fontSize = args[1];
  15598. // eagerly collect all fonts
  15599. return self.handleSetFont(resources, args, null,
  15600. operatorList, stateManager.state).
  15601. then(function (loadedName) {
  15602. operatorList.addDependency(loadedName);
  15603. operatorList.addOp(OPS.setFont, [loadedName, fontSize]);
  15604. next(resolve, reject);
  15605. }, reject);
  15606. case OPS.endInlineImage:
  15607. var cacheKey = args[0].cacheKey;
  15608. if (cacheKey) {
  15609. var cacheEntry = imageCache[cacheKey];
  15610. if (cacheEntry !== undefined) {
  15611. operatorList.addOp(cacheEntry.fn, cacheEntry.args);
  15612. args = null;
  15613. continue;
  15614. }
  15615. }
  15616. self.buildPaintImageXObject(resources, args[0], true,
  15617. operatorList, cacheKey, imageCache);
  15618. args = null;
  15619. continue;
  15620. case OPS.showText:
  15621. args[0] = self.handleText(args[0], stateManager.state);
  15622. break;
  15623. case OPS.showSpacedText:
  15624. var arr = args[0];
  15625. var combinedGlyphs = [];
  15626. var arrLength = arr.length;
  15627. for (i = 0; i < arrLength; ++i) {
  15628. var arrItem = arr[i];
  15629. if (isString(arrItem)) {
  15630. Array.prototype.push.apply(combinedGlyphs,
  15631. self.handleText(arrItem, stateManager.state));
  15632. } else if (isNum(arrItem)) {
  15633. combinedGlyphs.push(arrItem);
  15634. }
  15635. }
  15636. args[0] = combinedGlyphs;
  15637. fn = OPS.showText;
  15638. break;
  15639. case OPS.nextLineShowText:
  15640. operatorList.addOp(OPS.nextLine);
  15641. args[0] = self.handleText(args[0], stateManager.state);
  15642. fn = OPS.showText;
  15643. break;
  15644. case OPS.nextLineSetSpacingShowText:
  15645. operatorList.addOp(OPS.nextLine);
  15646. operatorList.addOp(OPS.setWordSpacing, [args.shift()]);
  15647. operatorList.addOp(OPS.setCharSpacing, [args.shift()]);
  15648. args[0] = self.handleText(args[0], stateManager.state);
  15649. fn = OPS.showText;
  15650. break;
  15651. case OPS.setTextRenderingMode:
  15652. stateManager.state.textRenderingMode = args[0];
  15653. break;
  15654. case OPS.setFillColorSpace:
  15655. stateManager.state.fillColorSpace =
  15656. ColorSpace.parse(args[0], xref, resources);
  15657. continue;
  15658. case OPS.setStrokeColorSpace:
  15659. stateManager.state.strokeColorSpace =
  15660. ColorSpace.parse(args[0], xref, resources);
  15661. continue;
  15662. case OPS.setFillColor:
  15663. cs = stateManager.state.fillColorSpace;
  15664. args = cs.getRgb(args, 0);
  15665. fn = OPS.setFillRGBColor;
  15666. break;
  15667. case OPS.setStrokeColor:
  15668. cs = stateManager.state.strokeColorSpace;
  15669. args = cs.getRgb(args, 0);
  15670. fn = OPS.setStrokeRGBColor;
  15671. break;
  15672. case OPS.setFillGray:
  15673. stateManager.state.fillColorSpace = ColorSpace.singletons.gray;
  15674. args = ColorSpace.singletons.gray.getRgb(args, 0);
  15675. fn = OPS.setFillRGBColor;
  15676. break;
  15677. case OPS.setStrokeGray:
  15678. stateManager.state.strokeColorSpace = ColorSpace.singletons.gray;
  15679. args = ColorSpace.singletons.gray.getRgb(args, 0);
  15680. fn = OPS.setStrokeRGBColor;
  15681. break;
  15682. case OPS.setFillCMYKColor:
  15683. stateManager.state.fillColorSpace = ColorSpace.singletons.cmyk;
  15684. args = ColorSpace.singletons.cmyk.getRgb(args, 0);
  15685. fn = OPS.setFillRGBColor;
  15686. break;
  15687. case OPS.setStrokeCMYKColor:
  15688. stateManager.state.strokeColorSpace = ColorSpace.singletons.cmyk;
  15689. args = ColorSpace.singletons.cmyk.getRgb(args, 0);
  15690. fn = OPS.setStrokeRGBColor;
  15691. break;
  15692. case OPS.setFillRGBColor:
  15693. stateManager.state.fillColorSpace = ColorSpace.singletons.rgb;
  15694. args = ColorSpace.singletons.rgb.getRgb(args, 0);
  15695. break;
  15696. case OPS.setStrokeRGBColor:
  15697. stateManager.state.strokeColorSpace = ColorSpace.singletons.rgb;
  15698. args = ColorSpace.singletons.rgb.getRgb(args, 0);
  15699. break;
  15700. case OPS.setFillColorN:
  15701. cs = stateManager.state.fillColorSpace;
  15702. if (cs.name === 'Pattern') {
  15703. return self.handleColorN(operatorList, OPS.setFillColorN,
  15704. args, cs, patterns, resources, xref).then(function() {
  15705. next(resolve, reject);
  15706. }, reject);
  15707. }
  15708. args = cs.getRgb(args, 0);
  15709. fn = OPS.setFillRGBColor;
  15710. break;
  15711. case OPS.setStrokeColorN:
  15712. cs = stateManager.state.strokeColorSpace;
  15713. if (cs.name === 'Pattern') {
  15714. return self.handleColorN(operatorList, OPS.setStrokeColorN,
  15715. args, cs, patterns, resources, xref).then(function() {
  15716. next(resolve, reject);
  15717. }, reject);
  15718. }
  15719. args = cs.getRgb(args, 0);
  15720. fn = OPS.setStrokeRGBColor;
  15721. break;
  15722. case OPS.shadingFill:
  15723. var shadingRes = resources.get('Shading');
  15724. if (!shadingRes) {
  15725. error('No shading resource found');
  15726. }
  15727. var shading = shadingRes.get(args[0].name);
  15728. if (!shading) {
  15729. error('No shading object found');
  15730. }
  15731. var shadingFill = Pattern.parseShading(shading, null, xref,
  15732. resources);
  15733. var patternIR = shadingFill.getIR();
  15734. args = [patternIR];
  15735. fn = OPS.shadingFill;
  15736. break;
  15737. case OPS.setGState:
  15738. var dictName = args[0];
  15739. var extGState = resources.get('ExtGState');
  15740. if (!isDict(extGState) || !extGState.has(dictName.name)) {
  15741. break;
  15742. }
  15743. var gState = extGState.get(dictName.name);
  15744. return self.setGState(resources, gState, operatorList, xref,
  15745. stateManager).then(function() {
  15746. next(resolve, reject);
  15747. }, reject);
  15748. case OPS.moveTo:
  15749. case OPS.lineTo:
  15750. case OPS.curveTo:
  15751. case OPS.curveTo2:
  15752. case OPS.curveTo3:
  15753. case OPS.closePath:
  15754. self.buildPath(operatorList, fn, args);
  15755. continue;
  15756. case OPS.rectangle:
  15757. self.buildPath(operatorList, fn, args);
  15758. continue;
  15759. }
  15760. operatorList.addOp(fn, args);
  15761. }
  15762. if (stop) {
  15763. deferred.then(function () {
  15764. next(resolve, reject);
  15765. });
  15766. return;
  15767. }
  15768. // Some PDFs don't close all restores inside object/form.
  15769. // Closing those for them.
  15770. for (i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
  15771. operatorList.addOp(OPS.restore, []);
  15772. }
  15773. resolve();
  15774. });
  15775. },
  15776. getTextContent: function PartialEvaluator_getTextContent(stream, resources,
  15777. stateManager) {
  15778. stateManager = (stateManager || new StateManager(new TextState()));
  15779. var textContent = {
  15780. items: [],
  15781. styles: Object.create(null)
  15782. };
  15783. var bidiTexts = textContent.items;
  15784. var SPACE_FACTOR = 0.35;
  15785. var MULTI_SPACE_FACTOR = 1.5;
  15786. var self = this;
  15787. var xref = this.xref;
  15788. resources = (xref.fetchIfRef(resources) || Dict.empty);
  15789. // The xobj is parsed iff it's needed, e.g. if there is a `DO` cmd.
  15790. var xobjs = null;
  15791. var xobjsCache = {};
  15792. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  15793. var textState;
  15794. function newTextChunk() {
  15795. var font = textState.font;
  15796. if (!(font.loadedName in textContent.styles)) {
  15797. textContent.styles[font.loadedName] = {
  15798. fontFamily: font.fallbackName,
  15799. ascent: font.ascent,
  15800. descent: font.descent,
  15801. vertical: font.vertical
  15802. };
  15803. }
  15804. return {
  15805. // |str| is initially an array which we push individual chars to, and
  15806. // then runBidi() overwrites it with the final string.
  15807. str: [],
  15808. dir: null,
  15809. width: 0,
  15810. height: 0,
  15811. transform: null,
  15812. fontName: font.loadedName
  15813. };
  15814. }
  15815. function runBidi(textChunk) {
  15816. var str = textChunk.str.join('');
  15817. var bidiResult = PDFJS.bidi(str, -1, textState.font.vertical);
  15818. textChunk.str = bidiResult.str;
  15819. textChunk.dir = bidiResult.dir;
  15820. return textChunk;
  15821. }
  15822. function handleSetFont(fontName, fontRef) {
  15823. return self.loadFont(fontName, fontRef, xref, resources).
  15824. then(function (translated) {
  15825. textState.font = translated.font;
  15826. textState.fontMatrix = translated.font.fontMatrix ||
  15827. FONT_IDENTITY_MATRIX;
  15828. });
  15829. }
  15830. function buildTextGeometry(chars, textChunk) {
  15831. var font = textState.font;
  15832. textChunk = textChunk || newTextChunk();
  15833. if (!textChunk.transform) {
  15834. // 9.4.4 Text Space Details
  15835. var tsm = [textState.fontSize * textState.textHScale, 0,
  15836. 0, textState.fontSize,
  15837. 0, textState.textRise];
  15838. var trm = textChunk.transform = Util.transform(textState.ctm,
  15839. Util.transform(textState.textMatrix, tsm));
  15840. if (!font.vertical) {
  15841. textChunk.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]);
  15842. } else {
  15843. textChunk.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]);
  15844. }
  15845. }
  15846. var width = 0;
  15847. var height = 0;
  15848. var glyphs = font.charsToGlyphs(chars);
  15849. var defaultVMetrics = font.defaultVMetrics;
  15850. for (var i = 0; i < glyphs.length; i++) {
  15851. var glyph = glyphs[i];
  15852. if (!glyph) { // Previous glyph was a space.
  15853. width += textState.wordSpacing * textState.textHScale;
  15854. continue;
  15855. }
  15856. var vMetricX = null;
  15857. var vMetricY = null;
  15858. var glyphWidth = null;
  15859. if (font.vertical) {
  15860. if (glyph.vmetric) {
  15861. glyphWidth = glyph.vmetric[0];
  15862. vMetricX = glyph.vmetric[1];
  15863. vMetricY = glyph.vmetric[2];
  15864. } else {
  15865. glyphWidth = glyph.width;
  15866. vMetricX = glyph.width * 0.5;
  15867. vMetricY = defaultVMetrics[2];
  15868. }
  15869. } else {
  15870. glyphWidth = glyph.width;
  15871. }
  15872. var glyphUnicode = glyph.unicode;
  15873. if (NormalizedUnicodes[glyphUnicode] !== undefined) {
  15874. glyphUnicode = NormalizedUnicodes[glyphUnicode];
  15875. }
  15876. glyphUnicode = reverseIfRtl(glyphUnicode);
  15877. // The following will calculate the x and y of the individual glyphs.
  15878. // if (font.vertical) {
  15879. // tsm[4] -= vMetricX * Math.abs(textState.fontSize) *
  15880. // textState.fontMatrix[0];
  15881. // tsm[5] -= vMetricY * textState.fontSize *
  15882. // textState.fontMatrix[0];
  15883. // }
  15884. // var trm = Util.transform(textState.textMatrix, tsm);
  15885. // var pt = Util.applyTransform([trm[4], trm[5]], textState.ctm);
  15886. // var x = pt[0];
  15887. // var y = pt[1];
  15888. var tx = 0;
  15889. var ty = 0;
  15890. if (!font.vertical) {
  15891. var w0 = glyphWidth * textState.fontMatrix[0];
  15892. tx = (w0 * textState.fontSize + textState.charSpacing) *
  15893. textState.textHScale;
  15894. width += tx;
  15895. } else {
  15896. var w1 = glyphWidth * textState.fontMatrix[0];
  15897. ty = w1 * textState.fontSize + textState.charSpacing;
  15898. height += ty;
  15899. }
  15900. textState.translateTextMatrix(tx, ty);
  15901. textChunk.str.push(glyphUnicode);
  15902. }
  15903. var a = textState.textLineMatrix[0];
  15904. var b = textState.textLineMatrix[1];
  15905. var scaleLineX = Math.sqrt(a * a + b * b);
  15906. a = textState.ctm[0];
  15907. b = textState.ctm[1];
  15908. var scaleCtmX = Math.sqrt(a * a + b * b);
  15909. if (!font.vertical) {
  15910. textChunk.width += width * scaleCtmX * scaleLineX;
  15911. } else {
  15912. textChunk.height += Math.abs(height * scaleCtmX * scaleLineX);
  15913. }
  15914. return textChunk;
  15915. }
  15916. var timeSlotManager = new TimeSlotManager();
  15917. return new Promise(function next(resolve, reject) {
  15918. timeSlotManager.reset();
  15919. var stop, operation = {}, args = [];
  15920. while (!(stop = timeSlotManager.check())) {
  15921. // The arguments parsed by read() are not used beyond this loop, so
  15922. // we can reuse the same array on every iteration, thus avoiding
  15923. // unnecessary allocations.
  15924. args.length = 0;
  15925. operation.args = args;
  15926. if (!(preprocessor.read(operation))) {
  15927. break;
  15928. }
  15929. textState = stateManager.state;
  15930. var fn = operation.fn;
  15931. args = operation.args;
  15932. switch (fn | 0) {
  15933. case OPS.setFont:
  15934. textState.fontSize = args[1];
  15935. return handleSetFont(args[0].name).then(function() {
  15936. next(resolve, reject);
  15937. }, reject);
  15938. case OPS.setTextRise:
  15939. textState.textRise = args[0];
  15940. break;
  15941. case OPS.setHScale:
  15942. textState.textHScale = args[0] / 100;
  15943. break;
  15944. case OPS.setLeading:
  15945. textState.leading = args[0];
  15946. break;
  15947. case OPS.moveText:
  15948. textState.translateTextLineMatrix(args[0], args[1]);
  15949. textState.textMatrix = textState.textLineMatrix.slice();
  15950. break;
  15951. case OPS.setLeadingMoveText:
  15952. textState.leading = -args[1];
  15953. textState.translateTextLineMatrix(args[0], args[1]);
  15954. textState.textMatrix = textState.textLineMatrix.slice();
  15955. break;
  15956. case OPS.nextLine:
  15957. textState.carriageReturn();
  15958. break;
  15959. case OPS.setTextMatrix:
  15960. textState.setTextMatrix(args[0], args[1], args[2], args[3],
  15961. args[4], args[5]);
  15962. textState.setTextLineMatrix(args[0], args[1], args[2], args[3],
  15963. args[4], args[5]);
  15964. break;
  15965. case OPS.setCharSpacing:
  15966. textState.charSpacing = args[0];
  15967. break;
  15968. case OPS.setWordSpacing:
  15969. textState.wordSpacing = args[0];
  15970. break;
  15971. case OPS.beginText:
  15972. textState.textMatrix = IDENTITY_MATRIX.slice();
  15973. textState.textLineMatrix = IDENTITY_MATRIX.slice();
  15974. break;
  15975. case OPS.showSpacedText:
  15976. var items = args[0];
  15977. var textChunk = newTextChunk();
  15978. var offset;
  15979. for (var j = 0, jj = items.length; j < jj; j++) {
  15980. if (typeof items[j] === 'string') {
  15981. buildTextGeometry(items[j], textChunk);
  15982. } else {
  15983. var val = items[j] / 1000;
  15984. if (!textState.font.vertical) {
  15985. offset = -val * textState.fontSize * textState.textHScale *
  15986. textState.textMatrix[0];
  15987. textState.translateTextMatrix(offset, 0);
  15988. textChunk.width += offset;
  15989. } else {
  15990. offset = -val * textState.fontSize *
  15991. textState.textMatrix[3];
  15992. textState.translateTextMatrix(0, offset);
  15993. textChunk.height += offset;
  15994. }
  15995. if (items[j] < 0 && textState.font.spaceWidth > 0) {
  15996. var fakeSpaces = -items[j] / textState.font.spaceWidth;
  15997. if (fakeSpaces > MULTI_SPACE_FACTOR) {
  15998. fakeSpaces = Math.round(fakeSpaces);
  15999. while (fakeSpaces--) {
  16000. textChunk.str.push(' ');
  16001. }
  16002. } else if (fakeSpaces > SPACE_FACTOR) {
  16003. textChunk.str.push(' ');
  16004. }
  16005. }
  16006. }
  16007. }
  16008. bidiTexts.push(runBidi(textChunk));
  16009. break;
  16010. case OPS.showText:
  16011. bidiTexts.push(runBidi(buildTextGeometry(args[0])));
  16012. break;
  16013. case OPS.nextLineShowText:
  16014. textState.carriageReturn();
  16015. bidiTexts.push(runBidi(buildTextGeometry(args[0])));
  16016. break;
  16017. case OPS.nextLineSetSpacingShowText:
  16018. textState.wordSpacing = args[0];
  16019. textState.charSpacing = args[1];
  16020. textState.carriageReturn();
  16021. bidiTexts.push(runBidi(buildTextGeometry(args[2])));
  16022. break;
  16023. case OPS.paintXObject:
  16024. if (args[0].code) {
  16025. break;
  16026. }
  16027. if (!xobjs) {
  16028. xobjs = (resources.get('XObject') || Dict.empty);
  16029. }
  16030. var name = args[0].name;
  16031. if (xobjsCache.key === name) {
  16032. if (xobjsCache.texts) {
  16033. Util.appendToArray(bidiTexts, xobjsCache.texts.items);
  16034. Util.extendObj(textContent.styles, xobjsCache.texts.styles);
  16035. }
  16036. break;
  16037. }
  16038. var xobj = xobjs.get(name);
  16039. if (!xobj) {
  16040. break;
  16041. }
  16042. assert(isStream(xobj), 'XObject should be a stream');
  16043. var type = xobj.dict.get('Subtype');
  16044. assert(isName(type),
  16045. 'XObject should have a Name subtype');
  16046. if ('Form' !== type.name) {
  16047. xobjsCache.key = name;
  16048. xobjsCache.texts = null;
  16049. break;
  16050. }
  16051. stateManager.save();
  16052. var matrix = xobj.dict.get('Matrix');
  16053. if (isArray(matrix) && matrix.length === 6) {
  16054. stateManager.transform(matrix);
  16055. }
  16056. return self.getTextContent(xobj,
  16057. xobj.dict.get('Resources') || resources, stateManager).
  16058. then(function (formTextContent) {
  16059. Util.appendToArray(bidiTexts, formTextContent.items);
  16060. Util.extendObj(textContent.styles, formTextContent.styles);
  16061. stateManager.restore();
  16062. xobjsCache.key = name;
  16063. xobjsCache.texts = formTextContent;
  16064. next(resolve, reject);
  16065. }, reject);
  16066. case OPS.setGState:
  16067. var dictName = args[0];
  16068. var extGState = resources.get('ExtGState');
  16069. if (!isDict(extGState) || !extGState.has(dictName.name)) {
  16070. break;
  16071. }
  16072. var gsStateMap = extGState.get(dictName.name);
  16073. var gsStateFont = null;
  16074. for (var key in gsStateMap) {
  16075. if (key === 'Font') {
  16076. assert(!gsStateFont);
  16077. gsStateFont = gsStateMap[key];
  16078. }
  16079. }
  16080. if (gsStateFont) {
  16081. textState.fontSize = gsStateFont[1];
  16082. return handleSetFont(gsStateFont[0]).then(function() {
  16083. next(resolve, reject);
  16084. }, reject);
  16085. }
  16086. break;
  16087. } // switch
  16088. } // while
  16089. if (stop) {
  16090. deferred.then(function () {
  16091. next(resolve, reject);
  16092. });
  16093. return;
  16094. }
  16095. resolve(textContent);
  16096. });
  16097. },
  16098. extractDataStructures: function
  16099. partialEvaluatorExtractDataStructures(dict, baseDict,
  16100. xref, properties) {
  16101. // 9.10.2
  16102. var toUnicode = (dict.get('ToUnicode') || baseDict.get('ToUnicode'));
  16103. if (toUnicode) {
  16104. properties.toUnicode = this.readToUnicode(toUnicode);
  16105. }
  16106. if (properties.composite) {
  16107. // CIDSystemInfo helps to match CID to glyphs
  16108. var cidSystemInfo = dict.get('CIDSystemInfo');
  16109. if (isDict(cidSystemInfo)) {
  16110. properties.cidSystemInfo = {
  16111. registry: cidSystemInfo.get('Registry'),
  16112. ordering: cidSystemInfo.get('Ordering'),
  16113. supplement: cidSystemInfo.get('Supplement')
  16114. };
  16115. }
  16116. var cidToGidMap = dict.get('CIDToGIDMap');
  16117. if (isStream(cidToGidMap)) {
  16118. properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
  16119. }
  16120. }
  16121. // Based on 9.6.6 of the spec the encoding can come from multiple places
  16122. // and depends on the font type. The base encoding and differences are
  16123. // read here, but the encoding that is actually used is chosen during
  16124. // glyph mapping in the font.
  16125. // TODO: Loading the built in encoding in the font would allow the
  16126. // differences to be merged in here not require us to hold on to it.
  16127. var differences = [];
  16128. var baseEncodingName = null;
  16129. var encoding;
  16130. if (dict.has('Encoding')) {
  16131. encoding = dict.get('Encoding');
  16132. if (isDict(encoding)) {
  16133. baseEncodingName = encoding.get('BaseEncoding');
  16134. baseEncodingName = (isName(baseEncodingName) ?
  16135. baseEncodingName.name : null);
  16136. // Load the differences between the base and original
  16137. if (encoding.has('Differences')) {
  16138. var diffEncoding = encoding.get('Differences');
  16139. var index = 0;
  16140. for (var j = 0, jj = diffEncoding.length; j < jj; j++) {
  16141. var data = diffEncoding[j];
  16142. if (isNum(data)) {
  16143. index = data;
  16144. } else {
  16145. differences[index++] = data.name;
  16146. }
  16147. }
  16148. }
  16149. } else if (isName(encoding)) {
  16150. baseEncodingName = encoding.name;
  16151. } else {
  16152. error('Encoding is not a Name nor a Dict');
  16153. }
  16154. // According to table 114 if the encoding is a named encoding it must be
  16155. // one of these predefined encodings.
  16156. if ((baseEncodingName !== 'MacRomanEncoding' &&
  16157. baseEncodingName !== 'MacExpertEncoding' &&
  16158. baseEncodingName !== 'WinAnsiEncoding')) {
  16159. baseEncodingName = null;
  16160. }
  16161. }
  16162. if (baseEncodingName) {
  16163. properties.defaultEncoding = Encodings[baseEncodingName].slice();
  16164. } else {
  16165. encoding = (properties.type === 'TrueType' ?
  16166. Encodings.WinAnsiEncoding : Encodings.StandardEncoding);
  16167. // The Symbolic attribute can be misused for regular fonts
  16168. // Heuristic: we have to check if the font is a standard one also
  16169. if (!!(properties.flags & FontFlags.Symbolic)) {
  16170. encoding = Encodings.MacRomanEncoding;
  16171. if (!properties.file) {
  16172. if (/Symbol/i.test(properties.name)) {
  16173. encoding = Encodings.SymbolSetEncoding;
  16174. } else if (/Dingbats/i.test(properties.name)) {
  16175. encoding = Encodings.ZapfDingbatsEncoding;
  16176. }
  16177. }
  16178. }
  16179. properties.defaultEncoding = encoding;
  16180. }
  16181. properties.differences = differences;
  16182. properties.baseEncodingName = baseEncodingName;
  16183. properties.dict = dict;
  16184. },
  16185. readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
  16186. var cmap, cmapObj = toUnicode;
  16187. if (isName(cmapObj)) {
  16188. cmap = CMapFactory.create(cmapObj,
  16189. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null).getMap();
  16190. return new ToUnicodeMap(cmap);
  16191. } else if (isStream(cmapObj)) {
  16192. cmap = CMapFactory.create(cmapObj,
  16193. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null).getMap();
  16194. // Convert UTF-16BE
  16195. // NOTE: cmap can be a sparse array, so use forEach instead of for(;;)
  16196. // to iterate over all keys.
  16197. cmap.forEach(function(token, i) {
  16198. var str = [];
  16199. for (var k = 0; k < token.length; k += 2) {
  16200. var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
  16201. if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF
  16202. str.push(w1);
  16203. continue;
  16204. }
  16205. k += 2;
  16206. var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
  16207. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  16208. }
  16209. cmap[i] = String.fromCharCode.apply(String, str);
  16210. });
  16211. return new ToUnicodeMap(cmap);
  16212. }
  16213. return null;
  16214. },
  16215. readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
  16216. // Extract the encoding from the CIDToGIDMap
  16217. var glyphsData = cidToGidStream.getBytes();
  16218. // Set encoding 0 to later verify the font has an encoding
  16219. var result = [];
  16220. for (var j = 0, jj = glyphsData.length; j < jj; j++) {
  16221. var glyphID = (glyphsData[j++] << 8) | glyphsData[j];
  16222. if (glyphID === 0) {
  16223. continue;
  16224. }
  16225. var code = j >> 1;
  16226. result[code] = glyphID;
  16227. }
  16228. return result;
  16229. },
  16230. extractWidths: function PartialEvaluator_extractWidths(dict, xref,
  16231. descriptor,
  16232. properties) {
  16233. var glyphsWidths = [];
  16234. var defaultWidth = 0;
  16235. var glyphsVMetrics = [];
  16236. var defaultVMetrics;
  16237. var i, ii, j, jj, start, code, widths;
  16238. if (properties.composite) {
  16239. defaultWidth = dict.get('DW') || 1000;
  16240. widths = dict.get('W');
  16241. if (widths) {
  16242. for (i = 0, ii = widths.length; i < ii; i++) {
  16243. start = widths[i++];
  16244. code = xref.fetchIfRef(widths[i]);
  16245. if (isArray(code)) {
  16246. for (j = 0, jj = code.length; j < jj; j++) {
  16247. glyphsWidths[start++] = code[j];
  16248. }
  16249. } else {
  16250. var width = widths[++i];
  16251. for (j = start; j <= code; j++) {
  16252. glyphsWidths[j] = width;
  16253. }
  16254. }
  16255. }
  16256. }
  16257. if (properties.vertical) {
  16258. var vmetrics = (dict.get('DW2') || [880, -1000]);
  16259. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  16260. vmetrics = dict.get('W2');
  16261. if (vmetrics) {
  16262. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  16263. start = vmetrics[i++];
  16264. code = xref.fetchIfRef(vmetrics[i]);
  16265. if (isArray(code)) {
  16266. for (j = 0, jj = code.length; j < jj; j++) {
  16267. glyphsVMetrics[start++] = [code[j++], code[j++], code[j]];
  16268. }
  16269. } else {
  16270. var vmetric = [vmetrics[++i], vmetrics[++i], vmetrics[++i]];
  16271. for (j = start; j <= code; j++) {
  16272. glyphsVMetrics[j] = vmetric;
  16273. }
  16274. }
  16275. }
  16276. }
  16277. }
  16278. } else {
  16279. var firstChar = properties.firstChar;
  16280. widths = dict.get('Widths');
  16281. if (widths) {
  16282. j = firstChar;
  16283. for (i = 0, ii = widths.length; i < ii; i++) {
  16284. glyphsWidths[j++] = widths[i];
  16285. }
  16286. defaultWidth = (parseFloat(descriptor.get('MissingWidth')) || 0);
  16287. } else {
  16288. // Trying get the BaseFont metrics (see comment above).
  16289. var baseFontName = dict.get('BaseFont');
  16290. if (isName(baseFontName)) {
  16291. var metrics = this.getBaseFontMetrics(baseFontName.name);
  16292. glyphsWidths = this.buildCharCodeToWidth(metrics.widths,
  16293. properties);
  16294. defaultWidth = metrics.defaultWidth;
  16295. }
  16296. }
  16297. }
  16298. // Heuristic: detection of monospace font by checking all non-zero widths
  16299. var isMonospace = true;
  16300. var firstWidth = defaultWidth;
  16301. for (var glyph in glyphsWidths) {
  16302. var glyphWidth = glyphsWidths[glyph];
  16303. if (!glyphWidth) {
  16304. continue;
  16305. }
  16306. if (!firstWidth) {
  16307. firstWidth = glyphWidth;
  16308. continue;
  16309. }
  16310. if (firstWidth !== glyphWidth) {
  16311. isMonospace = false;
  16312. break;
  16313. }
  16314. }
  16315. if (isMonospace) {
  16316. properties.flags |= FontFlags.FixedPitch;
  16317. }
  16318. properties.defaultWidth = defaultWidth;
  16319. properties.widths = glyphsWidths;
  16320. properties.defaultVMetrics = defaultVMetrics;
  16321. properties.vmetrics = glyphsVMetrics;
  16322. },
  16323. isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
  16324. // Simulating descriptor flags attribute
  16325. var fontNameWoStyle = baseFontName.split('-')[0];
  16326. return (fontNameWoStyle in serifFonts) ||
  16327. (fontNameWoStyle.search(/serif/gi) !== -1);
  16328. },
  16329. getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
  16330. var defaultWidth = 0;
  16331. var widths = [];
  16332. var monospace = false;
  16333. var lookupName = (stdFontMap[name] || name);
  16334. if (!(lookupName in Metrics)) {
  16335. // Use default fonts for looking up font metrics if the passed
  16336. // font is not a base font
  16337. if (this.isSerifFont(name)) {
  16338. lookupName = 'Times-Roman';
  16339. } else {
  16340. lookupName = 'Helvetica';
  16341. }
  16342. }
  16343. var glyphWidths = Metrics[lookupName];
  16344. if (isNum(glyphWidths)) {
  16345. defaultWidth = glyphWidths;
  16346. monospace = true;
  16347. } else {
  16348. widths = glyphWidths;
  16349. }
  16350. return {
  16351. defaultWidth: defaultWidth,
  16352. monospace: monospace,
  16353. widths: widths
  16354. };
  16355. },
  16356. buildCharCodeToWidth:
  16357. function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName,
  16358. properties) {
  16359. var widths = Object.create(null);
  16360. var differences = properties.differences;
  16361. var encoding = properties.defaultEncoding;
  16362. for (var charCode = 0; charCode < 256; charCode++) {
  16363. if (charCode in differences &&
  16364. widthsByGlyphName[differences[charCode]]) {
  16365. widths[charCode] = widthsByGlyphName[differences[charCode]];
  16366. continue;
  16367. }
  16368. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  16369. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  16370. continue;
  16371. }
  16372. }
  16373. return widths;
  16374. },
  16375. preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict, xref) {
  16376. var baseDict = dict;
  16377. var type = dict.get('Subtype');
  16378. assert(isName(type), 'invalid font Subtype');
  16379. var composite = false;
  16380. var uint8array;
  16381. if (type.name === 'Type0') {
  16382. // If font is a composite
  16383. // - get the descendant font
  16384. // - set the type according to the descendant font
  16385. // - get the FontDescriptor from the descendant font
  16386. var df = dict.get('DescendantFonts');
  16387. if (!df) {
  16388. error('Descendant fonts are not specified');
  16389. }
  16390. dict = (isArray(df) ? xref.fetchIfRef(df[0]) : df);
  16391. type = dict.get('Subtype');
  16392. assert(isName(type), 'invalid font Subtype');
  16393. composite = true;
  16394. }
  16395. var descriptor = dict.get('FontDescriptor');
  16396. if (descriptor) {
  16397. var hash = new MurmurHash3_64();
  16398. var encoding = baseDict.getRaw('Encoding');
  16399. if (isName(encoding)) {
  16400. hash.update(encoding.name);
  16401. } else if (isRef(encoding)) {
  16402. hash.update(encoding.num + '_' + encoding.gen);
  16403. }
  16404. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  16405. if (isStream(toUnicode)) {
  16406. var stream = toUnicode.str || toUnicode;
  16407. uint8array = stream.buffer ?
  16408. new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) :
  16409. new Uint8Array(stream.bytes.buffer,
  16410. stream.start, stream.end - stream.start);
  16411. hash.update(uint8array);
  16412. } else if (isName(toUnicode)) {
  16413. hash.update(toUnicode.name);
  16414. }
  16415. var widths = dict.get('Widths') || baseDict.get('Widths');
  16416. if (widths) {
  16417. uint8array = new Uint8Array(new Uint32Array(widths).buffer);
  16418. hash.update(uint8array);
  16419. }
  16420. }
  16421. return {
  16422. descriptor: descriptor,
  16423. dict: dict,
  16424. baseDict: baseDict,
  16425. composite: composite,
  16426. type: type.name,
  16427. hash: hash ? hash.hexdigest() : ''
  16428. };
  16429. },
  16430. translateFont: function PartialEvaluator_translateFont(preEvaluatedFont,
  16431. xref) {
  16432. var baseDict = preEvaluatedFont.baseDict;
  16433. var dict = preEvaluatedFont.dict;
  16434. var composite = preEvaluatedFont.composite;
  16435. var descriptor = preEvaluatedFont.descriptor;
  16436. var type = preEvaluatedFont.type;
  16437. var maxCharIndex = (composite ? 0xFFFF : 0xFF);
  16438. var properties;
  16439. if (!descriptor) {
  16440. if (type === 'Type3') {
  16441. // FontDescriptor is only required for Type3 fonts when the document
  16442. // is a tagged pdf. Create a barbebones one to get by.
  16443. descriptor = new Dict(null);
  16444. descriptor.set('FontName', Name.get(type));
  16445. } else {
  16446. // Before PDF 1.5 if the font was one of the base 14 fonts, having a
  16447. // FontDescriptor was not required.
  16448. // This case is here for compatibility.
  16449. var baseFontName = dict.get('BaseFont');
  16450. if (!isName(baseFontName)) {
  16451. error('Base font is not specified');
  16452. }
  16453. // Using base font name as a font name.
  16454. baseFontName = baseFontName.name.replace(/[,_]/g, '-');
  16455. var metrics = this.getBaseFontMetrics(baseFontName);
  16456. // Simulating descriptor flags attribute
  16457. var fontNameWoStyle = baseFontName.split('-')[0];
  16458. var flags =
  16459. (this.isSerifFont(fontNameWoStyle) ? FontFlags.Serif : 0) |
  16460. (metrics.monospace ? FontFlags.FixedPitch : 0) |
  16461. (symbolsFonts[fontNameWoStyle] ? FontFlags.Symbolic :
  16462. FontFlags.Nonsymbolic);
  16463. properties = {
  16464. type: type,
  16465. name: baseFontName,
  16466. widths: metrics.widths,
  16467. defaultWidth: metrics.defaultWidth,
  16468. flags: flags,
  16469. firstChar: 0,
  16470. lastChar: maxCharIndex
  16471. };
  16472. this.extractDataStructures(dict, dict, xref, properties);
  16473. properties.widths = this.buildCharCodeToWidth(metrics.widths,
  16474. properties);
  16475. return new Font(baseFontName, null, properties);
  16476. }
  16477. }
  16478. // According to the spec if 'FontDescriptor' is declared, 'FirstChar',
  16479. // 'LastChar' and 'Widths' should exist too, but some PDF encoders seem
  16480. // to ignore this rule when a variant of a standart font is used.
  16481. // TODO Fill the width array depending on which of the base font this is
  16482. // a variant.
  16483. var firstChar = (dict.get('FirstChar') || 0);
  16484. var lastChar = (dict.get('LastChar') || maxCharIndex);
  16485. var fontName = descriptor.get('FontName');
  16486. var baseFont = dict.get('BaseFont');
  16487. // Some bad PDFs have a string as the font name.
  16488. if (isString(fontName)) {
  16489. fontName = Name.get(fontName);
  16490. }
  16491. if (isString(baseFont)) {
  16492. baseFont = Name.get(baseFont);
  16493. }
  16494. if (type !== 'Type3') {
  16495. var fontNameStr = fontName && fontName.name;
  16496. var baseFontStr = baseFont && baseFont.name;
  16497. if (fontNameStr !== baseFontStr) {
  16498. info('The FontDescriptor\'s FontName is "' + fontNameStr +
  16499. '" but should be the same as the Font\'s BaseFont "' +
  16500. baseFontStr + '"');
  16501. // Workaround for cases where e.g. fontNameStr = 'Arial' and
  16502. // baseFontStr = 'Arial,Bold' (needed when no font file is embedded).
  16503. if (fontNameStr && baseFontStr &&
  16504. baseFontStr.indexOf(fontNameStr) === 0) {
  16505. fontName = baseFont;
  16506. }
  16507. }
  16508. }
  16509. fontName = (fontName || baseFont);
  16510. assert(isName(fontName), 'invalid font name');
  16511. var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
  16512. if (fontFile) {
  16513. if (fontFile.dict) {
  16514. var subtype = fontFile.dict.get('Subtype');
  16515. if (subtype) {
  16516. subtype = subtype.name;
  16517. }
  16518. var length1 = fontFile.dict.get('Length1');
  16519. var length2 = fontFile.dict.get('Length2');
  16520. }
  16521. }
  16522. properties = {
  16523. type: type,
  16524. name: fontName.name,
  16525. subtype: subtype,
  16526. file: fontFile,
  16527. length1: length1,
  16528. length2: length2,
  16529. loadedName: baseDict.loadedName,
  16530. composite: composite,
  16531. wideChars: composite,
  16532. fixedPitch: false,
  16533. fontMatrix: (dict.get('FontMatrix') || FONT_IDENTITY_MATRIX),
  16534. firstChar: firstChar || 0,
  16535. lastChar: (lastChar || maxCharIndex),
  16536. bbox: descriptor.get('FontBBox'),
  16537. ascent: descriptor.get('Ascent'),
  16538. descent: descriptor.get('Descent'),
  16539. xHeight: descriptor.get('XHeight'),
  16540. capHeight: descriptor.get('CapHeight'),
  16541. flags: descriptor.get('Flags'),
  16542. italicAngle: descriptor.get('ItalicAngle'),
  16543. coded: false
  16544. };
  16545. if (composite) {
  16546. var cidEncoding = baseDict.get('Encoding');
  16547. if (isName(cidEncoding)) {
  16548. properties.cidEncoding = cidEncoding.name;
  16549. }
  16550. properties.cMap = CMapFactory.create(cidEncoding,
  16551. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  16552. properties.vertical = properties.cMap.vertical;
  16553. }
  16554. this.extractDataStructures(dict, baseDict, xref, properties);
  16555. this.extractWidths(dict, xref, descriptor, properties);
  16556. if (type === 'Type3') {
  16557. properties.isType3Font = true;
  16558. }
  16559. return new Font(fontName.name, fontFile, properties);
  16560. }
  16561. };
  16562. return PartialEvaluator;
  16563. })();
  16564. var TranslatedFont = (function TranslatedFontClosure() {
  16565. function TranslatedFont(loadedName, font, dict) {
  16566. this.loadedName = loadedName;
  16567. this.font = font;
  16568. this.dict = dict;
  16569. this.type3Loaded = null;
  16570. this.sent = false;
  16571. }
  16572. TranslatedFont.prototype = {
  16573. send: function (handler) {
  16574. if (this.sent) {
  16575. return;
  16576. }
  16577. var fontData = this.font.exportData();
  16578. handler.send('commonobj', [
  16579. this.loadedName,
  16580. 'Font',
  16581. fontData
  16582. ]);
  16583. this.sent = true;
  16584. },
  16585. loadType3Data: function (evaluator, resources, parentOperatorList) {
  16586. assert(this.font.isType3Font);
  16587. if (this.type3Loaded) {
  16588. return this.type3Loaded;
  16589. }
  16590. var translatedFont = this.font;
  16591. var loadCharProcsPromise = Promise.resolve();
  16592. var charProcs = this.dict.get('CharProcs').getAll();
  16593. var fontResources = this.dict.get('Resources') || resources;
  16594. var charProcKeys = Object.keys(charProcs);
  16595. var charProcOperatorList = {};
  16596. for (var i = 0, n = charProcKeys.length; i < n; ++i) {
  16597. loadCharProcsPromise = loadCharProcsPromise.then(function (key) {
  16598. var glyphStream = charProcs[key];
  16599. var operatorList = new OperatorList();
  16600. return evaluator.getOperatorList(glyphStream, fontResources,
  16601. operatorList).then(function () {
  16602. charProcOperatorList[key] = operatorList.getIR();
  16603. // Add the dependencies to the parent operator list so they are
  16604. // resolved before sub operator list is executed synchronously.
  16605. parentOperatorList.addDependencies(operatorList.dependencies);
  16606. }, function (reason) {
  16607. warn('Type3 font resource \"' + key + '\" is not available');
  16608. var operatorList = new OperatorList();
  16609. charProcOperatorList[key] = operatorList.getIR();
  16610. });
  16611. }.bind(this, charProcKeys[i]));
  16612. }
  16613. this.type3Loaded = loadCharProcsPromise.then(function () {
  16614. translatedFont.charProcOperatorList = charProcOperatorList;
  16615. });
  16616. return this.type3Loaded;
  16617. }
  16618. };
  16619. return TranslatedFont;
  16620. })();
  16621. var OperatorList = (function OperatorListClosure() {
  16622. var CHUNK_SIZE = 1000;
  16623. var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5; // close to chunk size
  16624. function getTransfers(queue) {
  16625. var transfers = [];
  16626. var fnArray = queue.fnArray, argsArray = queue.argsArray;
  16627. for (var i = 0, ii = queue.length; i < ii; i++) {
  16628. switch (fnArray[i]) {
  16629. case OPS.paintInlineImageXObject:
  16630. case OPS.paintInlineImageXObjectGroup:
  16631. case OPS.paintImageMaskXObject:
  16632. var arg = argsArray[i][0]; // first param in imgData
  16633. if (!arg.cached) {
  16634. transfers.push(arg.data.buffer);
  16635. }
  16636. break;
  16637. }
  16638. }
  16639. return transfers;
  16640. }
  16641. function OperatorList(intent, messageHandler, pageIndex) {
  16642. this.messageHandler = messageHandler;
  16643. this.fnArray = [];
  16644. this.argsArray = [];
  16645. this.dependencies = {};
  16646. this.pageIndex = pageIndex;
  16647. this.intent = intent;
  16648. }
  16649. OperatorList.prototype = {
  16650. get length() {
  16651. return this.argsArray.length;
  16652. },
  16653. addOp: function(fn, args) {
  16654. this.fnArray.push(fn);
  16655. this.argsArray.push(args);
  16656. if (this.messageHandler) {
  16657. if (this.fnArray.length >= CHUNK_SIZE) {
  16658. this.flush();
  16659. } else if (this.fnArray.length >= CHUNK_SIZE_ABOUT &&
  16660. (fn === OPS.restore || fn === OPS.endText)) {
  16661. // heuristic to flush on boundary of restore or endText
  16662. this.flush();
  16663. }
  16664. }
  16665. },
  16666. addDependency: function(dependency) {
  16667. if (dependency in this.dependencies) {
  16668. return;
  16669. }
  16670. this.dependencies[dependency] = true;
  16671. this.addOp(OPS.dependency, [dependency]);
  16672. },
  16673. addDependencies: function(dependencies) {
  16674. for (var key in dependencies) {
  16675. this.addDependency(key);
  16676. }
  16677. },
  16678. addOpList: function(opList) {
  16679. Util.extendObj(this.dependencies, opList.dependencies);
  16680. for (var i = 0, ii = opList.length; i < ii; i++) {
  16681. this.addOp(opList.fnArray[i], opList.argsArray[i]);
  16682. }
  16683. },
  16684. getIR: function() {
  16685. return {
  16686. fnArray: this.fnArray,
  16687. argsArray: this.argsArray,
  16688. length: this.length
  16689. };
  16690. },
  16691. flush: function(lastChunk) {
  16692. if (this.intent !== 'oplist') {
  16693. new QueueOptimizer().optimize(this);
  16694. }
  16695. var transfers = getTransfers(this);
  16696. this.messageHandler.send('RenderPageChunk', {
  16697. operatorList: {
  16698. fnArray: this.fnArray,
  16699. argsArray: this.argsArray,
  16700. lastChunk: lastChunk,
  16701. length: this.length
  16702. },
  16703. pageIndex: this.pageIndex,
  16704. intent: this.intent
  16705. }, transfers);
  16706. this.dependencies = {};
  16707. this.fnArray.length = 0;
  16708. this.argsArray.length = 0;
  16709. }
  16710. };
  16711. return OperatorList;
  16712. })();
  16713. var StateManager = (function StateManagerClosure() {
  16714. function StateManager(initialState) {
  16715. this.state = initialState;
  16716. this.stateStack = [];
  16717. }
  16718. StateManager.prototype = {
  16719. save: function () {
  16720. var old = this.state;
  16721. this.stateStack.push(this.state);
  16722. this.state = old.clone();
  16723. },
  16724. restore: function () {
  16725. var prev = this.stateStack.pop();
  16726. if (prev) {
  16727. this.state = prev;
  16728. }
  16729. },
  16730. transform: function (args) {
  16731. this.state.ctm = Util.transform(this.state.ctm, args);
  16732. }
  16733. };
  16734. return StateManager;
  16735. })();
  16736. var TextState = (function TextStateClosure() {
  16737. function TextState() {
  16738. this.ctm = new Float32Array(IDENTITY_MATRIX);
  16739. this.fontSize = 0;
  16740. this.font = null;
  16741. this.fontMatrix = FONT_IDENTITY_MATRIX;
  16742. this.textMatrix = IDENTITY_MATRIX.slice();
  16743. this.textLineMatrix = IDENTITY_MATRIX.slice();
  16744. this.charSpacing = 0;
  16745. this.wordSpacing = 0;
  16746. this.leading = 0;
  16747. this.textHScale = 1;
  16748. this.textRise = 0;
  16749. }
  16750. TextState.prototype = {
  16751. setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  16752. var m = this.textMatrix;
  16753. m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
  16754. },
  16755. setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  16756. var m = this.textLineMatrix;
  16757. m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
  16758. },
  16759. translateTextMatrix: function TextState_translateTextMatrix(x, y) {
  16760. var m = this.textMatrix;
  16761. m[4] = m[0] * x + m[2] * y + m[4];
  16762. m[5] = m[1] * x + m[3] * y + m[5];
  16763. },
  16764. translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
  16765. var m = this.textLineMatrix;
  16766. m[4] = m[0] * x + m[2] * y + m[4];
  16767. m[5] = m[1] * x + m[3] * y + m[5];
  16768. },
  16769. calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
  16770. // 9.4.4 Text Space Details
  16771. var tsm = [this.fontSize * this.textHScale, 0,
  16772. 0, this.fontSize,
  16773. 0, this.textRise];
  16774. return Util.transform(ctm, Util.transform(this.textMatrix, tsm));
  16775. },
  16776. carriageReturn: function TextState_carriageReturn() {
  16777. this.translateTextLineMatrix(0, -this.leading);
  16778. this.textMatrix = this.textLineMatrix.slice();
  16779. },
  16780. clone: function TextState_clone() {
  16781. var clone = Object.create(this);
  16782. clone.textMatrix = this.textMatrix.slice();
  16783. clone.textLineMatrix = this.textLineMatrix.slice();
  16784. clone.fontMatrix = this.fontMatrix.slice();
  16785. return clone;
  16786. }
  16787. };
  16788. return TextState;
  16789. })();
  16790. var EvalState = (function EvalStateClosure() {
  16791. function EvalState() {
  16792. this.ctm = new Float32Array(IDENTITY_MATRIX);
  16793. this.font = null;
  16794. this.textRenderingMode = TextRenderingMode.FILL;
  16795. this.fillColorSpace = ColorSpace.singletons.gray;
  16796. this.strokeColorSpace = ColorSpace.singletons.gray;
  16797. }
  16798. EvalState.prototype = {
  16799. clone: function CanvasExtraState_clone() {
  16800. return Object.create(this);
  16801. },
  16802. };
  16803. return EvalState;
  16804. })();
  16805. var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
  16806. // Specifies properties for each command
  16807. //
  16808. // If variableArgs === true: [0, `numArgs`] expected
  16809. // If variableArgs === false: exactly `numArgs` expected
  16810. var OP_MAP = {
  16811. // Graphic state
  16812. w: { id: OPS.setLineWidth, numArgs: 1, variableArgs: false },
  16813. J: { id: OPS.setLineCap, numArgs: 1, variableArgs: false },
  16814. j: { id: OPS.setLineJoin, numArgs: 1, variableArgs: false },
  16815. M: { id: OPS.setMiterLimit, numArgs: 1, variableArgs: false },
  16816. d: { id: OPS.setDash, numArgs: 2, variableArgs: false },
  16817. ri: { id: OPS.setRenderingIntent, numArgs: 1, variableArgs: false },
  16818. i: { id: OPS.setFlatness, numArgs: 1, variableArgs: false },
  16819. gs: { id: OPS.setGState, numArgs: 1, variableArgs: false },
  16820. q: { id: OPS.save, numArgs: 0, variableArgs: false },
  16821. Q: { id: OPS.restore, numArgs: 0, variableArgs: false },
  16822. cm: { id: OPS.transform, numArgs: 6, variableArgs: false },
  16823. // Path
  16824. m: { id: OPS.moveTo, numArgs: 2, variableArgs: false },
  16825. l: { id: OPS.lineTo, numArgs: 2, variableArgs: false },
  16826. c: { id: OPS.curveTo, numArgs: 6, variableArgs: false },
  16827. v: { id: OPS.curveTo2, numArgs: 4, variableArgs: false },
  16828. y: { id: OPS.curveTo3, numArgs: 4, variableArgs: false },
  16829. h: { id: OPS.closePath, numArgs: 0, variableArgs: false },
  16830. re: { id: OPS.rectangle, numArgs: 4, variableArgs: false },
  16831. S: { id: OPS.stroke, numArgs: 0, variableArgs: false },
  16832. s: { id: OPS.closeStroke, numArgs: 0, variableArgs: false },
  16833. f: { id: OPS.fill, numArgs: 0, variableArgs: false },
  16834. F: { id: OPS.fill, numArgs: 0, variableArgs: false },
  16835. 'f*': { id: OPS.eoFill, numArgs: 0, variableArgs: false },
  16836. B: { id: OPS.fillStroke, numArgs: 0, variableArgs: false },
  16837. 'B*': { id: OPS.eoFillStroke, numArgs: 0, variableArgs: false },
  16838. b: { id: OPS.closeFillStroke, numArgs: 0, variableArgs: false },
  16839. 'b*': { id: OPS.closeEOFillStroke, numArgs: 0, variableArgs: false },
  16840. n: { id: OPS.endPath, numArgs: 0, variableArgs: false },
  16841. // Clipping
  16842. W: { id: OPS.clip, numArgs: 0, variableArgs: false },
  16843. 'W*': { id: OPS.eoClip, numArgs: 0, variableArgs: false },
  16844. // Text
  16845. BT: { id: OPS.beginText, numArgs: 0, variableArgs: false },
  16846. ET: { id: OPS.endText, numArgs: 0, variableArgs: false },
  16847. Tc: { id: OPS.setCharSpacing, numArgs: 1, variableArgs: false },
  16848. Tw: { id: OPS.setWordSpacing, numArgs: 1, variableArgs: false },
  16849. Tz: { id: OPS.setHScale, numArgs: 1, variableArgs: false },
  16850. TL: { id: OPS.setLeading, numArgs: 1, variableArgs: false },
  16851. Tf: { id: OPS.setFont, numArgs: 2, variableArgs: false },
  16852. Tr: { id: OPS.setTextRenderingMode, numArgs: 1, variableArgs: false },
  16853. Ts: { id: OPS.setTextRise, numArgs: 1, variableArgs: false },
  16854. Td: { id: OPS.moveText, numArgs: 2, variableArgs: false },
  16855. TD: { id: OPS.setLeadingMoveText, numArgs: 2, variableArgs: false },
  16856. Tm: { id: OPS.setTextMatrix, numArgs: 6, variableArgs: false },
  16857. 'T*': { id: OPS.nextLine, numArgs: 0, variableArgs: false },
  16858. Tj: { id: OPS.showText, numArgs: 1, variableArgs: false },
  16859. TJ: { id: OPS.showSpacedText, numArgs: 1, variableArgs: false },
  16860. '\'': { id: OPS.nextLineShowText, numArgs: 1, variableArgs: false },
  16861. '"': { id: OPS.nextLineSetSpacingShowText, numArgs: 3,
  16862. variableArgs: false },
  16863. // Type3 fonts
  16864. d0: { id: OPS.setCharWidth, numArgs: 2, variableArgs: false },
  16865. d1: { id: OPS.setCharWidthAndBounds, numArgs: 6, variableArgs: false },
  16866. // Color
  16867. CS: { id: OPS.setStrokeColorSpace, numArgs: 1, variableArgs: false },
  16868. cs: { id: OPS.setFillColorSpace, numArgs: 1, variableArgs: false },
  16869. SC: { id: OPS.setStrokeColor, numArgs: 4, variableArgs: true },
  16870. SCN: { id: OPS.setStrokeColorN, numArgs: 33, variableArgs: true },
  16871. sc: { id: OPS.setFillColor, numArgs: 4, variableArgs: true },
  16872. scn: { id: OPS.setFillColorN, numArgs: 33, variableArgs: true },
  16873. G: { id: OPS.setStrokeGray, numArgs: 1, variableArgs: false },
  16874. g: { id: OPS.setFillGray, numArgs: 1, variableArgs: false },
  16875. RG: { id: OPS.setStrokeRGBColor, numArgs: 3, variableArgs: false },
  16876. rg: { id: OPS.setFillRGBColor, numArgs: 3, variableArgs: false },
  16877. K: { id: OPS.setStrokeCMYKColor, numArgs: 4, variableArgs: false },
  16878. k: { id: OPS.setFillCMYKColor, numArgs: 4, variableArgs: false },
  16879. // Shading
  16880. sh: { id: OPS.shadingFill, numArgs: 1, variableArgs: false },
  16881. // Images
  16882. BI: { id: OPS.beginInlineImage, numArgs: 0, variableArgs: false },
  16883. ID: { id: OPS.beginImageData, numArgs: 0, variableArgs: false },
  16884. EI: { id: OPS.endInlineImage, numArgs: 1, variableArgs: false },
  16885. // XObjects
  16886. Do: { id: OPS.paintXObject, numArgs: 1, variableArgs: false },
  16887. MP: { id: OPS.markPoint, numArgs: 1, variableArgs: false },
  16888. DP: { id: OPS.markPointProps, numArgs: 2, variableArgs: false },
  16889. BMC: { id: OPS.beginMarkedContent, numArgs: 1, variableArgs: false },
  16890. BDC: { id: OPS.beginMarkedContentProps, numArgs: 2,
  16891. variableArgs: false },
  16892. EMC: { id: OPS.endMarkedContent, numArgs: 0, variableArgs: false },
  16893. // Compatibility
  16894. BX: { id: OPS.beginCompat, numArgs: 0, variableArgs: false },
  16895. EX: { id: OPS.endCompat, numArgs: 0, variableArgs: false },
  16896. // (reserved partial commands for the lexer)
  16897. BM: null,
  16898. BD: null,
  16899. 'true': null,
  16900. fa: null,
  16901. fal: null,
  16902. fals: null,
  16903. 'false': null,
  16904. nu: null,
  16905. nul: null,
  16906. 'null': null
  16907. };
  16908. function EvaluatorPreprocessor(stream, xref, stateManager) {
  16909. // TODO(mduan): pass array of knownCommands rather than OP_MAP
  16910. // dictionary
  16911. this.parser = new Parser(new Lexer(stream, OP_MAP), false, xref);
  16912. this.stateManager = stateManager;
  16913. this.nonProcessedArgs = [];
  16914. }
  16915. EvaluatorPreprocessor.prototype = {
  16916. get savedStatesDepth() {
  16917. return this.stateManager.stateStack.length;
  16918. },
  16919. // |operation| is an object with two fields:
  16920. //
  16921. // - |fn| is an out param.
  16922. //
  16923. // - |args| is an inout param. On entry, it should have one of two values.
  16924. //
  16925. // - An empty array. This indicates that the caller is providing the
  16926. // array in which the args will be stored in. The caller should use
  16927. // this value if it can reuse a single array for each call to read().
  16928. //
  16929. // - |null|. This indicates that the caller needs this function to create
  16930. // the array in which any args are stored in. If there are zero args,
  16931. // this function will leave |operation.args| as |null| (thus avoiding
  16932. // allocations that would occur if we used an empty array to represent
  16933. // zero arguments). Otherwise, it will replace |null| with a new array
  16934. // containing the arguments. The caller should use this value if it
  16935. // cannot reuse an array for each call to read().
  16936. //
  16937. // These two modes are present because this function is very hot and so
  16938. // avoiding allocations where possible is worthwhile.
  16939. //
  16940. read: function EvaluatorPreprocessor_read(operation) {
  16941. var args = operation.args;
  16942. while (true) {
  16943. var obj = this.parser.getObj();
  16944. if (isCmd(obj)) {
  16945. var cmd = obj.cmd;
  16946. // Check that the command is valid
  16947. var opSpec = OP_MAP[cmd];
  16948. if (!opSpec) {
  16949. warn('Unknown command "' + cmd + '"');
  16950. continue;
  16951. }
  16952. var fn = opSpec.id;
  16953. var numArgs = opSpec.numArgs;
  16954. var argsLength = args !== null ? args.length : 0;
  16955. if (!opSpec.variableArgs) {
  16956. // Postscript commands can be nested, e.g. /F2 /GS2 gs 5.711 Tf
  16957. if (argsLength !== numArgs) {
  16958. var nonProcessedArgs = this.nonProcessedArgs;
  16959. while (argsLength > numArgs) {
  16960. nonProcessedArgs.push(args.shift());
  16961. argsLength--;
  16962. }
  16963. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  16964. if (!args) {
  16965. args = [];
  16966. }
  16967. args.unshift(nonProcessedArgs.pop());
  16968. argsLength++;
  16969. }
  16970. }
  16971. if (argsLength < numArgs) {
  16972. // If we receive too few args, it's not possible to possible
  16973. // to execute the command, so skip the command
  16974. info('Command ' + fn + ': because expected ' +
  16975. numArgs + ' args, but received ' + argsLength +
  16976. ' args; skipping');
  16977. args = null;
  16978. continue;
  16979. }
  16980. } else if (argsLength > numArgs) {
  16981. info('Command ' + fn + ': expected [0,' + numArgs +
  16982. '] args, but received ' + argsLength + ' args');
  16983. }
  16984. // TODO figure out how to type-check vararg functions
  16985. this.preprocessCommand(fn, args);
  16986. operation.fn = fn;
  16987. operation.args = args;
  16988. return true;
  16989. } else {
  16990. if (isEOF(obj)) {
  16991. return false; // no more commands
  16992. }
  16993. // argument
  16994. if (obj !== null) {
  16995. if (!args) {
  16996. args = [];
  16997. }
  16998. args.push((obj instanceof Dict ? obj.getAll() : obj));
  16999. assert(args.length <= 33, 'Too many arguments');
  17000. }
  17001. }
  17002. }
  17003. },
  17004. preprocessCommand:
  17005. function EvaluatorPreprocessor_preprocessCommand(fn, args) {
  17006. switch (fn | 0) {
  17007. case OPS.save:
  17008. this.stateManager.save();
  17009. break;
  17010. case OPS.restore:
  17011. this.stateManager.restore();
  17012. break;
  17013. case OPS.transform:
  17014. this.stateManager.transform(args);
  17015. break;
  17016. }
  17017. }
  17018. };
  17019. return EvaluatorPreprocessor;
  17020. })();
  17021. var QueueOptimizer = (function QueueOptimizerClosure() {
  17022. function addState(parentState, pattern, fn) {
  17023. var state = parentState;
  17024. for (var i = 0, ii = pattern.length - 1; i < ii; i++) {
  17025. var item = pattern[i];
  17026. state = (state[item] || (state[item] = []));
  17027. }
  17028. state[pattern[pattern.length - 1]] = fn;
  17029. }
  17030. function handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
  17031. argsArray) {
  17032. // Handles special case of mainly LaTeX documents which use image masks to
  17033. // draw lines with the current fill style.
  17034. // 'count' groups of (save, transform, paintImageMaskXObject, restore)+
  17035. // have been found at iFirstSave.
  17036. var iFirstPIMXO = iFirstSave + 2;
  17037. for (var i = 0; i < count; i++) {
  17038. var arg = argsArray[iFirstPIMXO + 4 * i];
  17039. var imageMask = arg.length === 1 && arg[0];
  17040. if (imageMask && imageMask.width === 1 && imageMask.height === 1 &&
  17041. (!imageMask.data.length ||
  17042. (imageMask.data.length === 1 && imageMask.data[0] === 0))) {
  17043. fnArray[iFirstPIMXO + 4 * i] = OPS.paintSolidColorImageMask;
  17044. continue;
  17045. }
  17046. break;
  17047. }
  17048. return count - i;
  17049. }
  17050. var InitialState = [];
  17051. // This replaces (save, transform, paintInlineImageXObject, restore)+
  17052. // sequences with one |paintInlineImageXObjectGroup| operation.
  17053. addState(InitialState,
  17054. [OPS.save, OPS.transform, OPS.paintInlineImageXObject, OPS.restore],
  17055. function foundInlineImageGroup(context) {
  17056. var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
  17057. var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
  17058. var MAX_WIDTH = 1000;
  17059. var IMAGE_PADDING = 1;
  17060. var fnArray = context.fnArray, argsArray = context.argsArray;
  17061. var curr = context.iCurr;
  17062. var iFirstSave = curr - 3;
  17063. var iFirstTransform = curr - 2;
  17064. var iFirstPIIXO = curr - 1;
  17065. // Look for the quartets.
  17066. var i = iFirstSave + 4;
  17067. var ii = fnArray.length;
  17068. while (i + 3 < ii) {
  17069. if (fnArray[i] !== OPS.save ||
  17070. fnArray[i + 1] !== OPS.transform ||
  17071. fnArray[i + 2] !== OPS.paintInlineImageXObject ||
  17072. fnArray[i + 3] !== OPS.restore) {
  17073. break; // ops don't match
  17074. }
  17075. i += 4;
  17076. }
  17077. // At this point, i is the index of the first op past the last valid
  17078. // quartet.
  17079. var count = Math.min((i - iFirstSave) / 4,
  17080. MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);
  17081. if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {
  17082. return i;
  17083. }
  17084. // assuming that heights of those image is too small (~1 pixel)
  17085. // packing as much as possible by lines
  17086. var maxX = 0;
  17087. var map = [], maxLineHeight = 0;
  17088. var currentX = IMAGE_PADDING, currentY = IMAGE_PADDING;
  17089. var q;
  17090. for (q = 0; q < count; q++) {
  17091. var transform = argsArray[iFirstTransform + (q << 2)];
  17092. var img = argsArray[iFirstPIIXO + (q << 2)][0];
  17093. if (currentX + img.width > MAX_WIDTH) {
  17094. // starting new line
  17095. maxX = Math.max(maxX, currentX);
  17096. currentY += maxLineHeight + 2 * IMAGE_PADDING;
  17097. currentX = 0;
  17098. maxLineHeight = 0;
  17099. }
  17100. map.push({
  17101. transform: transform,
  17102. x: currentX, y: currentY,
  17103. w: img.width, h: img.height
  17104. });
  17105. currentX += img.width + 2 * IMAGE_PADDING;
  17106. maxLineHeight = Math.max(maxLineHeight, img.height);
  17107. }
  17108. var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;
  17109. var imgHeight = currentY + maxLineHeight + IMAGE_PADDING;
  17110. var imgData = new Uint8Array(imgWidth * imgHeight * 4);
  17111. var imgRowSize = imgWidth << 2;
  17112. for (q = 0; q < count; q++) {
  17113. var data = argsArray[iFirstPIIXO + (q << 2)][0].data;
  17114. // Copy image by lines and extends pixels into padding.
  17115. var rowSize = map[q].w << 2;
  17116. var dataOffset = 0;
  17117. var offset = (map[q].x + map[q].y * imgWidth) << 2;
  17118. imgData.set(data.subarray(0, rowSize), offset - imgRowSize);
  17119. for (var k = 0, kk = map[q].h; k < kk; k++) {
  17120. imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);
  17121. dataOffset += rowSize;
  17122. offset += imgRowSize;
  17123. }
  17124. imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);
  17125. while (offset >= 0) {
  17126. data[offset - 4] = data[offset];
  17127. data[offset - 3] = data[offset + 1];
  17128. data[offset - 2] = data[offset + 2];
  17129. data[offset - 1] = data[offset + 3];
  17130. data[offset + rowSize] = data[offset + rowSize - 4];
  17131. data[offset + rowSize + 1] = data[offset + rowSize - 3];
  17132. data[offset + rowSize + 2] = data[offset + rowSize - 2];
  17133. data[offset + rowSize + 3] = data[offset + rowSize - 1];
  17134. offset -= imgRowSize;
  17135. }
  17136. }
  17137. // Replace queue items.
  17138. fnArray.splice(iFirstSave, count * 4, OPS.paintInlineImageXObjectGroup);
  17139. argsArray.splice(iFirstSave, count * 4,
  17140. [{ width: imgWidth, height: imgHeight, kind: ImageKind.RGBA_32BPP,
  17141. data: imgData }, map]);
  17142. return iFirstSave + 1;
  17143. });
  17144. // This replaces (save, transform, paintImageMaskXObject, restore)+
  17145. // sequences with one |paintImageMaskXObjectGroup| or one
  17146. // |paintImageMaskXObjectRepeat| operation.
  17147. addState(InitialState,
  17148. [OPS.save, OPS.transform, OPS.paintImageMaskXObject, OPS.restore],
  17149. function foundImageMaskGroup(context) {
  17150. var MIN_IMAGES_IN_MASKS_BLOCK = 10;
  17151. var MAX_IMAGES_IN_MASKS_BLOCK = 100;
  17152. var MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;
  17153. var fnArray = context.fnArray, argsArray = context.argsArray;
  17154. var curr = context.iCurr;
  17155. var iFirstSave = curr - 3;
  17156. var iFirstTransform = curr - 2;
  17157. var iFirstPIMXO = curr - 1;
  17158. // Look for the quartets.
  17159. var i = iFirstSave + 4;
  17160. var ii = fnArray.length;
  17161. while (i + 3 < ii) {
  17162. if (fnArray[i] !== OPS.save ||
  17163. fnArray[i + 1] !== OPS.transform ||
  17164. fnArray[i + 2] !== OPS.paintImageMaskXObject ||
  17165. fnArray[i + 3] !== OPS.restore) {
  17166. break; // ops don't match
  17167. }
  17168. i += 4;
  17169. }
  17170. // At this point, i is the index of the first op past the last valid
  17171. // quartet.
  17172. var count = (i - iFirstSave) / 4;
  17173. count = handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
  17174. argsArray);
  17175. if (count < MIN_IMAGES_IN_MASKS_BLOCK) {
  17176. return i;
  17177. }
  17178. var q;
  17179. var isSameImage = false;
  17180. var iTransform, transformArgs;
  17181. var firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
  17182. if (argsArray[iFirstTransform][1] === 0 &&
  17183. argsArray[iFirstTransform][2] === 0) {
  17184. isSameImage = true;
  17185. var firstTransformArg0 = argsArray[iFirstTransform][0];
  17186. var firstTransformArg3 = argsArray[iFirstTransform][3];
  17187. iTransform = iFirstTransform + 4;
  17188. var iPIMXO = iFirstPIMXO + 4;
  17189. for (q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) {
  17190. transformArgs = argsArray[iTransform];
  17191. if (argsArray[iPIMXO][0] !== firstPIMXOArg0 ||
  17192. transformArgs[0] !== firstTransformArg0 ||
  17193. transformArgs[1] !== 0 ||
  17194. transformArgs[2] !== 0 ||
  17195. transformArgs[3] !== firstTransformArg3) {
  17196. if (q < MIN_IMAGES_IN_MASKS_BLOCK) {
  17197. isSameImage = false;
  17198. } else {
  17199. count = q;
  17200. }
  17201. break; // different image or transform
  17202. }
  17203. }
  17204. }
  17205. if (isSameImage) {
  17206. count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);
  17207. var positions = new Float32Array(count * 2);
  17208. iTransform = iFirstTransform;
  17209. for (q = 0; q < count; q++, iTransform += 4) {
  17210. transformArgs = argsArray[iTransform];
  17211. positions[(q << 1)] = transformArgs[4];
  17212. positions[(q << 1) + 1] = transformArgs[5];
  17213. }
  17214. // Replace queue items.
  17215. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectRepeat);
  17216. argsArray.splice(iFirstSave, count * 4,
  17217. [firstPIMXOArg0, firstTransformArg0, firstTransformArg3, positions]);
  17218. } else {
  17219. count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);
  17220. var images = [];
  17221. for (q = 0; q < count; q++) {
  17222. transformArgs = argsArray[iFirstTransform + (q << 2)];
  17223. var maskParams = argsArray[iFirstPIMXO + (q << 2)][0];
  17224. images.push({ data: maskParams.data, width: maskParams.width,
  17225. height: maskParams.height,
  17226. transform: transformArgs });
  17227. }
  17228. // Replace queue items.
  17229. fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectGroup);
  17230. argsArray.splice(iFirstSave, count * 4, [images]);
  17231. }
  17232. return iFirstSave + 1;
  17233. });
  17234. // This replaces (save, transform, paintImageXObject, restore)+ sequences
  17235. // with one paintImageXObjectRepeat operation, if the |transform| and
  17236. // |paintImageXObjectRepeat| ops are appropriate.
  17237. addState(InitialState,
  17238. [OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore],
  17239. function (context) {
  17240. var MIN_IMAGES_IN_BLOCK = 3;
  17241. var MAX_IMAGES_IN_BLOCK = 1000;
  17242. var fnArray = context.fnArray, argsArray = context.argsArray;
  17243. var curr = context.iCurr;
  17244. var iFirstSave = curr - 3;
  17245. var iFirstTransform = curr - 2;
  17246. var iFirstPIXO = curr - 1;
  17247. var iFirstRestore = curr;
  17248. if (argsArray[iFirstTransform][1] !== 0 ||
  17249. argsArray[iFirstTransform][2] !== 0) {
  17250. return iFirstRestore + 1; // transform has the wrong form
  17251. }
  17252. // Look for the quartets.
  17253. var firstPIXOArg0 = argsArray[iFirstPIXO][0];
  17254. var firstTransformArg0 = argsArray[iFirstTransform][0];
  17255. var firstTransformArg3 = argsArray[iFirstTransform][3];
  17256. var i = iFirstSave + 4;
  17257. var ii = fnArray.length;
  17258. while (i + 3 < ii) {
  17259. if (fnArray[i] !== OPS.save ||
  17260. fnArray[i + 1] !== OPS.transform ||
  17261. fnArray[i + 2] !== OPS.paintImageXObject ||
  17262. fnArray[i + 3] !== OPS.restore) {
  17263. break; // ops don't match
  17264. }
  17265. if (argsArray[i + 1][0] !== firstTransformArg0 ||
  17266. argsArray[i + 1][1] !== 0 ||
  17267. argsArray[i + 1][2] !== 0 ||
  17268. argsArray[i + 1][3] !== firstTransformArg3) {
  17269. break; // transforms don't match
  17270. }
  17271. if (argsArray[i + 2][0] !== firstPIXOArg0) {
  17272. break; // images don't match
  17273. }
  17274. i += 4;
  17275. }
  17276. // At this point, i is the index of the first op past the last valid
  17277. // quartet.
  17278. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_BLOCK);
  17279. if (count < MIN_IMAGES_IN_BLOCK) {
  17280. return i;
  17281. }
  17282. // Extract the (x,y) positions from all of the matching transforms.
  17283. var positions = new Float32Array(count * 2);
  17284. var iTransform = iFirstTransform;
  17285. for (var q = 0; q < count; q++, iTransform += 4) {
  17286. var transformArgs = argsArray[iTransform];
  17287. positions[(q << 1)] = transformArgs[4];
  17288. positions[(q << 1) + 1] = transformArgs[5];
  17289. }
  17290. // Replace queue items.
  17291. var args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3,
  17292. positions];
  17293. fnArray.splice(iFirstSave, count * 4, OPS.paintImageXObjectRepeat);
  17294. argsArray.splice(iFirstSave, count * 4, args);
  17295. return iFirstSave + 1;
  17296. });
  17297. // This replaces (beginText, setFont, setTextMatrix, showText, endText)+
  17298. // sequences with (beginText, setFont, (setTextMatrix, showText)+, endText)+
  17299. // sequences, if the font for each one is the same.
  17300. addState(InitialState,
  17301. [OPS.beginText, OPS.setFont, OPS.setTextMatrix, OPS.showText, OPS.endText],
  17302. function (context) {
  17303. var MIN_CHARS_IN_BLOCK = 3;
  17304. var MAX_CHARS_IN_BLOCK = 1000;
  17305. var fnArray = context.fnArray, argsArray = context.argsArray;
  17306. var curr = context.iCurr;
  17307. var iFirstBeginText = curr - 4;
  17308. var iFirstSetFont = curr - 3;
  17309. var iFirstSetTextMatrix = curr - 2;
  17310. var iFirstShowText = curr - 1;
  17311. var iFirstEndText = curr;
  17312. // Look for the quintets.
  17313. var firstSetFontArg0 = argsArray[iFirstSetFont][0];
  17314. var firstSetFontArg1 = argsArray[iFirstSetFont][1];
  17315. var i = iFirstBeginText + 5;
  17316. var ii = fnArray.length;
  17317. while (i + 4 < ii) {
  17318. if (fnArray[i] !== OPS.beginText ||
  17319. fnArray[i + 1] !== OPS.setFont ||
  17320. fnArray[i + 2] !== OPS.setTextMatrix ||
  17321. fnArray[i + 3] !== OPS.showText ||
  17322. fnArray[i + 4] !== OPS.endText) {
  17323. break; // ops don't match
  17324. }
  17325. if (argsArray[i + 1][0] !== firstSetFontArg0 ||
  17326. argsArray[i + 1][1] !== firstSetFontArg1) {
  17327. break; // fonts don't match
  17328. }
  17329. i += 5;
  17330. }
  17331. // At this point, i is the index of the first op past the last valid
  17332. // quintet.
  17333. var count = Math.min(((i - iFirstBeginText) / 5), MAX_CHARS_IN_BLOCK);
  17334. if (count < MIN_CHARS_IN_BLOCK) {
  17335. return i;
  17336. }
  17337. // If the preceding quintet is (<something>, setFont, setTextMatrix,
  17338. // showText, endText), include that as well. (E.g. <something> might be
  17339. // |dependency|.)
  17340. var iFirst = iFirstBeginText;
  17341. if (iFirstBeginText >= 4 &&
  17342. fnArray[iFirstBeginText - 4] === fnArray[iFirstSetFont] &&
  17343. fnArray[iFirstBeginText - 3] === fnArray[iFirstSetTextMatrix] &&
  17344. fnArray[iFirstBeginText - 2] === fnArray[iFirstShowText] &&
  17345. fnArray[iFirstBeginText - 1] === fnArray[iFirstEndText] &&
  17346. argsArray[iFirstBeginText - 4][0] === firstSetFontArg0 &&
  17347. argsArray[iFirstBeginText - 4][1] === firstSetFontArg1) {
  17348. count++;
  17349. iFirst -= 5;
  17350. }
  17351. // Remove (endText, beginText, setFont) trios.
  17352. var iEndText = iFirst + 4;
  17353. for (var q = 1; q < count; q++) {
  17354. fnArray.splice(iEndText, 3);
  17355. argsArray.splice(iEndText, 3);
  17356. iEndText += 2;
  17357. }
  17358. return iEndText + 1;
  17359. });
  17360. function QueueOptimizer() {}
  17361. QueueOptimizer.prototype = {
  17362. optimize: function QueueOptimizer_optimize(queue) {
  17363. var fnArray = queue.fnArray, argsArray = queue.argsArray;
  17364. var context = {
  17365. iCurr: 0,
  17366. fnArray: fnArray,
  17367. argsArray: argsArray
  17368. };
  17369. var state;
  17370. var i = 0, ii = fnArray.length;
  17371. while (i < ii) {
  17372. state = (state || InitialState)[fnArray[i]];
  17373. if (typeof state === 'function') { // we found some handler
  17374. context.iCurr = i;
  17375. // state() returns the index of the first non-matching op (if we
  17376. // didn't match) or the first op past the modified ops (if we did
  17377. // match and replace).
  17378. i = state(context);
  17379. state = undefined; // reset the state machine
  17380. ii = context.fnArray.length;
  17381. } else {
  17382. i++;
  17383. }
  17384. }
  17385. }
  17386. };
  17387. return QueueOptimizer;
  17388. })();
  17389. var BUILT_IN_CMAPS = [
  17390. // << Start unicode maps.
  17391. 'Adobe-GB1-UCS2',
  17392. 'Adobe-CNS1-UCS2',
  17393. 'Adobe-Japan1-UCS2',
  17394. 'Adobe-Korea1-UCS2',
  17395. // >> End unicode maps.
  17396. '78-EUC-H',
  17397. '78-EUC-V',
  17398. '78-H',
  17399. '78-RKSJ-H',
  17400. '78-RKSJ-V',
  17401. '78-V',
  17402. '78ms-RKSJ-H',
  17403. '78ms-RKSJ-V',
  17404. '83pv-RKSJ-H',
  17405. '90ms-RKSJ-H',
  17406. '90ms-RKSJ-V',
  17407. '90msp-RKSJ-H',
  17408. '90msp-RKSJ-V',
  17409. '90pv-RKSJ-H',
  17410. '90pv-RKSJ-V',
  17411. 'Add-H',
  17412. 'Add-RKSJ-H',
  17413. 'Add-RKSJ-V',
  17414. 'Add-V',
  17415. 'Adobe-CNS1-0',
  17416. 'Adobe-CNS1-1',
  17417. 'Adobe-CNS1-2',
  17418. 'Adobe-CNS1-3',
  17419. 'Adobe-CNS1-4',
  17420. 'Adobe-CNS1-5',
  17421. 'Adobe-CNS1-6',
  17422. 'Adobe-GB1-0',
  17423. 'Adobe-GB1-1',
  17424. 'Adobe-GB1-2',
  17425. 'Adobe-GB1-3',
  17426. 'Adobe-GB1-4',
  17427. 'Adobe-GB1-5',
  17428. 'Adobe-Japan1-0',
  17429. 'Adobe-Japan1-1',
  17430. 'Adobe-Japan1-2',
  17431. 'Adobe-Japan1-3',
  17432. 'Adobe-Japan1-4',
  17433. 'Adobe-Japan1-5',
  17434. 'Adobe-Japan1-6',
  17435. 'Adobe-Korea1-0',
  17436. 'Adobe-Korea1-1',
  17437. 'Adobe-Korea1-2',
  17438. 'B5-H',
  17439. 'B5-V',
  17440. 'B5pc-H',
  17441. 'B5pc-V',
  17442. 'CNS-EUC-H',
  17443. 'CNS-EUC-V',
  17444. 'CNS1-H',
  17445. 'CNS1-V',
  17446. 'CNS2-H',
  17447. 'CNS2-V',
  17448. 'ETHK-B5-H',
  17449. 'ETHK-B5-V',
  17450. 'ETen-B5-H',
  17451. 'ETen-B5-V',
  17452. 'ETenms-B5-H',
  17453. 'ETenms-B5-V',
  17454. 'EUC-H',
  17455. 'EUC-V',
  17456. 'Ext-H',
  17457. 'Ext-RKSJ-H',
  17458. 'Ext-RKSJ-V',
  17459. 'Ext-V',
  17460. 'GB-EUC-H',
  17461. 'GB-EUC-V',
  17462. 'GB-H',
  17463. 'GB-V',
  17464. 'GBK-EUC-H',
  17465. 'GBK-EUC-V',
  17466. 'GBK2K-H',
  17467. 'GBK2K-V',
  17468. 'GBKp-EUC-H',
  17469. 'GBKp-EUC-V',
  17470. 'GBT-EUC-H',
  17471. 'GBT-EUC-V',
  17472. 'GBT-H',
  17473. 'GBT-V',
  17474. 'GBTpc-EUC-H',
  17475. 'GBTpc-EUC-V',
  17476. 'GBpc-EUC-H',
  17477. 'GBpc-EUC-V',
  17478. 'H',
  17479. 'HKdla-B5-H',
  17480. 'HKdla-B5-V',
  17481. 'HKdlb-B5-H',
  17482. 'HKdlb-B5-V',
  17483. 'HKgccs-B5-H',
  17484. 'HKgccs-B5-V',
  17485. 'HKm314-B5-H',
  17486. 'HKm314-B5-V',
  17487. 'HKm471-B5-H',
  17488. 'HKm471-B5-V',
  17489. 'HKscs-B5-H',
  17490. 'HKscs-B5-V',
  17491. 'Hankaku',
  17492. 'Hiragana',
  17493. 'KSC-EUC-H',
  17494. 'KSC-EUC-V',
  17495. 'KSC-H',
  17496. 'KSC-Johab-H',
  17497. 'KSC-Johab-V',
  17498. 'KSC-V',
  17499. 'KSCms-UHC-H',
  17500. 'KSCms-UHC-HW-H',
  17501. 'KSCms-UHC-HW-V',
  17502. 'KSCms-UHC-V',
  17503. 'KSCpc-EUC-H',
  17504. 'KSCpc-EUC-V',
  17505. 'Katakana',
  17506. 'NWP-H',
  17507. 'NWP-V',
  17508. 'RKSJ-H',
  17509. 'RKSJ-V',
  17510. 'Roman',
  17511. 'UniCNS-UCS2-H',
  17512. 'UniCNS-UCS2-V',
  17513. 'UniCNS-UTF16-H',
  17514. 'UniCNS-UTF16-V',
  17515. 'UniCNS-UTF32-H',
  17516. 'UniCNS-UTF32-V',
  17517. 'UniCNS-UTF8-H',
  17518. 'UniCNS-UTF8-V',
  17519. 'UniGB-UCS2-H',
  17520. 'UniGB-UCS2-V',
  17521. 'UniGB-UTF16-H',
  17522. 'UniGB-UTF16-V',
  17523. 'UniGB-UTF32-H',
  17524. 'UniGB-UTF32-V',
  17525. 'UniGB-UTF8-H',
  17526. 'UniGB-UTF8-V',
  17527. 'UniJIS-UCS2-H',
  17528. 'UniJIS-UCS2-HW-H',
  17529. 'UniJIS-UCS2-HW-V',
  17530. 'UniJIS-UCS2-V',
  17531. 'UniJIS-UTF16-H',
  17532. 'UniJIS-UTF16-V',
  17533. 'UniJIS-UTF32-H',
  17534. 'UniJIS-UTF32-V',
  17535. 'UniJIS-UTF8-H',
  17536. 'UniJIS-UTF8-V',
  17537. 'UniJIS2004-UTF16-H',
  17538. 'UniJIS2004-UTF16-V',
  17539. 'UniJIS2004-UTF32-H',
  17540. 'UniJIS2004-UTF32-V',
  17541. 'UniJIS2004-UTF8-H',
  17542. 'UniJIS2004-UTF8-V',
  17543. 'UniJISPro-UCS2-HW-V',
  17544. 'UniJISPro-UCS2-V',
  17545. 'UniJISPro-UTF8-V',
  17546. 'UniJISX0213-UTF32-H',
  17547. 'UniJISX0213-UTF32-V',
  17548. 'UniJISX02132004-UTF32-H',
  17549. 'UniJISX02132004-UTF32-V',
  17550. 'UniKS-UCS2-H',
  17551. 'UniKS-UCS2-V',
  17552. 'UniKS-UTF16-H',
  17553. 'UniKS-UTF16-V',
  17554. 'UniKS-UTF32-H',
  17555. 'UniKS-UTF32-V',
  17556. 'UniKS-UTF8-H',
  17557. 'UniKS-UTF8-V',
  17558. 'V',
  17559. 'WP-Symbol'];
  17560. // CMap, not to be confused with TrueType's cmap.
  17561. var CMap = (function CMapClosure() {
  17562. function CMap(builtInCMap) {
  17563. // Codespace ranges are stored as follows:
  17564. // [[1BytePairs], [2BytePairs], [3BytePairs], [4BytePairs]]
  17565. // where nBytePairs are ranges e.g. [low1, high1, low2, high2, ...]
  17566. this.codespaceRanges = [[], [], [], []];
  17567. this.numCodespaceRanges = 0;
  17568. // Map entries have one of two forms.
  17569. // - cid chars are 16-bit unsigned integers, stored as integers.
  17570. // - bf chars are variable-length byte sequences, stored as strings, with
  17571. // one byte per character.
  17572. this._map = [];
  17573. this.vertical = false;
  17574. this.useCMap = null;
  17575. this.builtInCMap = builtInCMap;
  17576. }
  17577. CMap.prototype = {
  17578. addCodespaceRange: function(n, low, high) {
  17579. this.codespaceRanges[n - 1].push(low, high);
  17580. this.numCodespaceRanges++;
  17581. },
  17582. mapCidRange: function(low, high, dstLow) {
  17583. while (low <= high) {
  17584. this._map[low++] = dstLow++;
  17585. }
  17586. },
  17587. mapBfRange: function(low, high, dstLow) {
  17588. var lastByte = dstLow.length - 1;
  17589. while (low <= high) {
  17590. this._map[low++] = dstLow;
  17591. // Only the last byte has to be incremented.
  17592. dstLow = dstLow.substr(0, lastByte) +
  17593. String.fromCharCode(dstLow.charCodeAt(lastByte) + 1);
  17594. }
  17595. },
  17596. mapBfRangeToArray: function(low, high, array) {
  17597. var i = 0, ii = array.length;
  17598. while (low <= high && i < ii) {
  17599. this._map[low] = array[i++];
  17600. ++low;
  17601. }
  17602. },
  17603. // This is used for both bf and cid chars.
  17604. mapOne: function(src, dst) {
  17605. this._map[src] = dst;
  17606. },
  17607. lookup: function(code) {
  17608. return this._map[code];
  17609. },
  17610. contains: function(code) {
  17611. return this._map[code] !== undefined;
  17612. },
  17613. forEach: function(callback) {
  17614. // Most maps have fewer than 65536 entries, and for those we use normal
  17615. // array iteration. But really sparse tables are possible -- e.g. with
  17616. // indices in the *billions*. For such tables we use for..in, which isn't
  17617. // ideal because it stringifies the indices for all present elements, but
  17618. // it does avoid iterating over every undefined entry.
  17619. var map = this._map;
  17620. var length = map.length;
  17621. var i;
  17622. if (length <= 0x10000) {
  17623. for (i = 0; i < length; i++) {
  17624. if (map[i] !== undefined) {
  17625. callback(i, map[i]);
  17626. }
  17627. }
  17628. } else {
  17629. for (i in this._map) {
  17630. callback(i, map[i]);
  17631. }
  17632. }
  17633. },
  17634. charCodeOf: function(value) {
  17635. return this._map.indexOf(value);
  17636. },
  17637. getMap: function() {
  17638. return this._map;
  17639. },
  17640. readCharCode: function(str, offset, out) {
  17641. var c = 0;
  17642. var codespaceRanges = this.codespaceRanges;
  17643. var codespaceRangesLen = this.codespaceRanges.length;
  17644. // 9.7.6.2 CMap Mapping
  17645. // The code length is at most 4.
  17646. for (var n = 0; n < codespaceRangesLen; n++) {
  17647. c = ((c << 8) | str.charCodeAt(offset + n)) >>> 0;
  17648. // Check each codespace range to see if it falls within.
  17649. var codespaceRange = codespaceRanges[n];
  17650. for (var k = 0, kk = codespaceRange.length; k < kk;) {
  17651. var low = codespaceRange[k++];
  17652. var high = codespaceRange[k++];
  17653. if (c >= low && c <= high) {
  17654. out.charcode = c;
  17655. out.length = n + 1;
  17656. return;
  17657. }
  17658. }
  17659. }
  17660. out.charcode = 0;
  17661. out.length = 1;
  17662. }
  17663. };
  17664. return CMap;
  17665. })();
  17666. // A special case of CMap, where the _map array implicitly has a length of
  17667. // 65535 and each element is equal to its index.
  17668. var IdentityCMap = (function IdentityCMapClosure() {
  17669. function IdentityCMap(vertical, n) {
  17670. CMap.call(this);
  17671. this.vertical = vertical;
  17672. this.addCodespaceRange(n, 0, 0xffff);
  17673. }
  17674. Util.inherit(IdentityCMap, CMap, {});
  17675. IdentityCMap.prototype = {
  17676. addCodespaceRange: CMap.prototype.addCodespaceRange,
  17677. mapCidRange: function(low, high, dstLow) {
  17678. error('should not call mapCidRange');
  17679. },
  17680. mapBfRange: function(low, high, dstLow) {
  17681. error('should not call mapBfRange');
  17682. },
  17683. mapBfRangeToArray: function(low, high, array) {
  17684. error('should not call mapBfRangeToArray');
  17685. },
  17686. mapOne: function(src, dst) {
  17687. error('should not call mapCidOne');
  17688. },
  17689. lookup: function(code) {
  17690. return (isInt(code) && code <= 0xffff) ? code : undefined;
  17691. },
  17692. contains: function(code) {
  17693. return isInt(code) && code <= 0xffff;
  17694. },
  17695. forEach: function(callback) {
  17696. for (var i = 0; i <= 0xffff; i++) {
  17697. callback(i, i);
  17698. }
  17699. },
  17700. charCodeOf: function(value) {
  17701. return (isInt(value) && value <= 0xffff) ? value : -1;
  17702. },
  17703. getMap: function() {
  17704. // Sometimes identity maps must be instantiated, but it's rare.
  17705. var map = new Array(0x10000);
  17706. for (var i = 0; i <= 0xffff; i++) {
  17707. map[i] = i;
  17708. }
  17709. return map;
  17710. },
  17711. readCharCode: CMap.prototype.readCharCode
  17712. };
  17713. return IdentityCMap;
  17714. })();
  17715. var BinaryCMapReader = (function BinaryCMapReaderClosure() {
  17716. function fetchBinaryData(url) {
  17717. var nonBinaryRequest = PDFJS.disableWorker;
  17718. var request = new XMLHttpRequest();
  17719. request.open('GET', url, false);
  17720. if (!nonBinaryRequest) {
  17721. try {
  17722. request.responseType = 'arraybuffer';
  17723. nonBinaryRequest = request.responseType !== 'arraybuffer';
  17724. } catch (e) {
  17725. nonBinaryRequest = true;
  17726. }
  17727. }
  17728. if (nonBinaryRequest && request.overrideMimeType) {
  17729. request.overrideMimeType('text/plain; charset=x-user-defined');
  17730. }
  17731. request.send(null);
  17732. if (nonBinaryRequest ? !request.responseText : !request.response) {
  17733. error('Unable to get binary cMap at: ' + url);
  17734. }
  17735. if (nonBinaryRequest) {
  17736. var data = Array.prototype.map.call(request.responseText, function (ch) {
  17737. return ch.charCodeAt(0) & 255;
  17738. });
  17739. return new Uint8Array(data);
  17740. }
  17741. return new Uint8Array(request.response);
  17742. }
  17743. function hexToInt(a, size) {
  17744. var n = 0;
  17745. for (var i = 0; i <= size; i++) {
  17746. n = (n << 8) | a[i];
  17747. }
  17748. return n >>> 0;
  17749. }
  17750. function hexToStr(a, size) {
  17751. // This code is hot. Special-case some common values to avoid creating an
  17752. // object with subarray().
  17753. if (size === 1) {
  17754. return String.fromCharCode(a[0], a[1]);
  17755. }
  17756. if (size === 3) {
  17757. return String.fromCharCode(a[0], a[1], a[2], a[3]);
  17758. }
  17759. return String.fromCharCode.apply(null, a.subarray(0, size + 1));
  17760. }
  17761. function addHex(a, b, size) {
  17762. var c = 0;
  17763. for (var i = size; i >= 0; i--) {
  17764. c += a[i] + b[i];
  17765. a[i] = c & 255;
  17766. c >>= 8;
  17767. }
  17768. }
  17769. function incHex(a, size) {
  17770. var c = 1;
  17771. for (var i = size; i >= 0 && c > 0; i--) {
  17772. c += a[i];
  17773. a[i] = c & 255;
  17774. c >>= 8;
  17775. }
  17776. }
  17777. var MAX_NUM_SIZE = 16;
  17778. var MAX_ENCODED_NUM_SIZE = 19; // ceil(MAX_NUM_SIZE * 7 / 8)
  17779. function BinaryCMapStream(data) {
  17780. this.buffer = data;
  17781. this.pos = 0;
  17782. this.end = data.length;
  17783. this.tmpBuf = new Uint8Array(MAX_ENCODED_NUM_SIZE);
  17784. }
  17785. BinaryCMapStream.prototype = {
  17786. readByte: function () {
  17787. if (this.pos >= this.end) {
  17788. return -1;
  17789. }
  17790. return this.buffer[this.pos++];
  17791. },
  17792. readNumber: function () {
  17793. var n = 0;
  17794. var last;
  17795. do {
  17796. var b = this.readByte();
  17797. if (b < 0) {
  17798. error('unexpected EOF in bcmap');
  17799. }
  17800. last = !(b & 0x80);
  17801. n = (n << 7) | (b & 0x7F);
  17802. } while (!last);
  17803. return n;
  17804. },
  17805. readSigned: function () {
  17806. var n = this.readNumber();
  17807. return (n & 1) ? ~(n >>> 1) : n >>> 1;
  17808. },
  17809. readHex: function (num, size) {
  17810. num.set(this.buffer.subarray(this.pos,
  17811. this.pos + size + 1));
  17812. this.pos += size + 1;
  17813. },
  17814. readHexNumber: function (num, size) {
  17815. var last;
  17816. var stack = this.tmpBuf, sp = 0;
  17817. do {
  17818. var b = this.readByte();
  17819. if (b < 0) {
  17820. error('unexpected EOF in bcmap');
  17821. }
  17822. last = !(b & 0x80);
  17823. stack[sp++] = b & 0x7F;
  17824. } while (!last);
  17825. var i = size, buffer = 0, bufferSize = 0;
  17826. while (i >= 0) {
  17827. while (bufferSize < 8 && stack.length > 0) {
  17828. buffer = (stack[--sp] << bufferSize) | buffer;
  17829. bufferSize += 7;
  17830. }
  17831. num[i] = buffer & 255;
  17832. i--;
  17833. buffer >>= 8;
  17834. bufferSize -= 8;
  17835. }
  17836. },
  17837. readHexSigned: function (num, size) {
  17838. this.readHexNumber(num, size);
  17839. var sign = num[size] & 1 ? 255 : 0;
  17840. var c = 0;
  17841. for (var i = 0; i <= size; i++) {
  17842. c = ((c & 1) << 8) | num[i];
  17843. num[i] = (c >> 1) ^ sign;
  17844. }
  17845. },
  17846. readString: function () {
  17847. var len = this.readNumber();
  17848. var s = '';
  17849. for (var i = 0; i < len; i++) {
  17850. s += String.fromCharCode(this.readNumber());
  17851. }
  17852. return s;
  17853. }
  17854. };
  17855. function processBinaryCMap(url, cMap, extend) {
  17856. var data = fetchBinaryData(url);
  17857. var stream = new BinaryCMapStream(data);
  17858. var header = stream.readByte();
  17859. cMap.vertical = !!(header & 1);
  17860. var useCMap = null;
  17861. var start = new Uint8Array(MAX_NUM_SIZE);
  17862. var end = new Uint8Array(MAX_NUM_SIZE);
  17863. var char = new Uint8Array(MAX_NUM_SIZE);
  17864. var charCode = new Uint8Array(MAX_NUM_SIZE);
  17865. var tmp = new Uint8Array(MAX_NUM_SIZE);
  17866. var code;
  17867. var b;
  17868. while ((b = stream.readByte()) >= 0) {
  17869. var type = b >> 5;
  17870. if (type === 7) { // metadata, e.g. comment or usecmap
  17871. switch (b & 0x1F) {
  17872. case 0:
  17873. stream.readString(); // skipping comment
  17874. break;
  17875. case 1:
  17876. useCMap = stream.readString();
  17877. break;
  17878. }
  17879. continue;
  17880. }
  17881. var sequence = !!(b & 0x10);
  17882. var dataSize = b & 15;
  17883. assert(dataSize + 1 <= MAX_NUM_SIZE);
  17884. var ucs2DataSize = 1;
  17885. var subitemsCount = stream.readNumber();
  17886. var i;
  17887. switch (type) {
  17888. case 0: // codespacerange
  17889. stream.readHex(start, dataSize);
  17890. stream.readHexNumber(end, dataSize);
  17891. addHex(end, start, dataSize);
  17892. cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
  17893. hexToInt(end, dataSize));
  17894. for (i = 1; i < subitemsCount; i++) {
  17895. incHex(end, dataSize);
  17896. stream.readHexNumber(start, dataSize);
  17897. addHex(start, end, dataSize);
  17898. stream.readHexNumber(end, dataSize);
  17899. addHex(end, start, dataSize);
  17900. cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
  17901. hexToInt(end, dataSize));
  17902. }
  17903. break;
  17904. case 1: // notdefrange
  17905. stream.readHex(start, dataSize);
  17906. stream.readHexNumber(end, dataSize);
  17907. addHex(end, start, dataSize);
  17908. code = stream.readNumber();
  17909. // undefined range, skipping
  17910. for (i = 1; i < subitemsCount; i++) {
  17911. incHex(end, dataSize);
  17912. stream.readHexNumber(start, dataSize);
  17913. addHex(start, end, dataSize);
  17914. stream.readHexNumber(end, dataSize);
  17915. addHex(end, start, dataSize);
  17916. code = stream.readNumber();
  17917. // nop
  17918. }
  17919. break;
  17920. case 2: // cidchar
  17921. stream.readHex(char, dataSize);
  17922. code = stream.readNumber();
  17923. cMap.mapOne(hexToInt(char, dataSize), code);
  17924. for (i = 1; i < subitemsCount; i++) {
  17925. incHex(char, dataSize);
  17926. if (!sequence) {
  17927. stream.readHexNumber(tmp, dataSize);
  17928. addHex(char, tmp, dataSize);
  17929. }
  17930. code = stream.readSigned() + (code + 1);
  17931. cMap.mapOne(hexToInt(char, dataSize), code);
  17932. }
  17933. break;
  17934. case 3: // cidrange
  17935. stream.readHex(start, dataSize);
  17936. stream.readHexNumber(end, dataSize);
  17937. addHex(end, start, dataSize);
  17938. code = stream.readNumber();
  17939. cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
  17940. code);
  17941. for (i = 1; i < subitemsCount; i++) {
  17942. incHex(end, dataSize);
  17943. if (!sequence) {
  17944. stream.readHexNumber(start, dataSize);
  17945. addHex(start, end, dataSize);
  17946. } else {
  17947. start.set(end);
  17948. }
  17949. stream.readHexNumber(end, dataSize);
  17950. addHex(end, start, dataSize);
  17951. code = stream.readNumber();
  17952. cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
  17953. code);
  17954. }
  17955. break;
  17956. case 4: // bfchar
  17957. stream.readHex(char, ucs2DataSize);
  17958. stream.readHex(charCode, dataSize);
  17959. cMap.mapOne(hexToInt(char, ucs2DataSize),
  17960. hexToStr(charCode, dataSize));
  17961. for (i = 1; i < subitemsCount; i++) {
  17962. incHex(char, ucs2DataSize);
  17963. if (!sequence) {
  17964. stream.readHexNumber(tmp, ucs2DataSize);
  17965. addHex(char, tmp, ucs2DataSize);
  17966. }
  17967. incHex(charCode, dataSize);
  17968. stream.readHexSigned(tmp, dataSize);
  17969. addHex(charCode, tmp, dataSize);
  17970. cMap.mapOne(hexToInt(char, ucs2DataSize),
  17971. hexToStr(charCode, dataSize));
  17972. }
  17973. break;
  17974. case 5: // bfrange
  17975. stream.readHex(start, ucs2DataSize);
  17976. stream.readHexNumber(end, ucs2DataSize);
  17977. addHex(end, start, ucs2DataSize);
  17978. stream.readHex(charCode, dataSize);
  17979. cMap.mapBfRange(hexToInt(start, ucs2DataSize),
  17980. hexToInt(end, ucs2DataSize),
  17981. hexToStr(charCode, dataSize));
  17982. for (i = 1; i < subitemsCount; i++) {
  17983. incHex(end, ucs2DataSize);
  17984. if (!sequence) {
  17985. stream.readHexNumber(start, ucs2DataSize);
  17986. addHex(start, end, ucs2DataSize);
  17987. } else {
  17988. start.set(end);
  17989. }
  17990. stream.readHexNumber(end, ucs2DataSize);
  17991. addHex(end, start, ucs2DataSize);
  17992. stream.readHex(charCode, dataSize);
  17993. cMap.mapBfRange(hexToInt(start, ucs2DataSize),
  17994. hexToInt(end, ucs2DataSize),
  17995. hexToStr(charCode, dataSize));
  17996. }
  17997. break;
  17998. default:
  17999. error('Unknown type: ' + type);
  18000. break;
  18001. }
  18002. }
  18003. if (useCMap) {
  18004. extend(useCMap);
  18005. }
  18006. return cMap;
  18007. }
  18008. function BinaryCMapReader() {}
  18009. BinaryCMapReader.prototype = {
  18010. read: processBinaryCMap
  18011. };
  18012. return BinaryCMapReader;
  18013. })();
  18014. var CMapFactory = (function CMapFactoryClosure() {
  18015. function strToInt(str) {
  18016. var a = 0;
  18017. for (var i = 0; i < str.length; i++) {
  18018. a = (a << 8) | str.charCodeAt(i);
  18019. }
  18020. return a >>> 0;
  18021. }
  18022. function expectString(obj) {
  18023. if (!isString(obj)) {
  18024. error('Malformed CMap: expected string.');
  18025. }
  18026. }
  18027. function expectInt(obj) {
  18028. if (!isInt(obj)) {
  18029. error('Malformed CMap: expected int.');
  18030. }
  18031. }
  18032. function parseBfChar(cMap, lexer) {
  18033. while (true) {
  18034. var obj = lexer.getObj();
  18035. if (isEOF(obj)) {
  18036. break;
  18037. }
  18038. if (isCmd(obj, 'endbfchar')) {
  18039. return;
  18040. }
  18041. expectString(obj);
  18042. var src = strToInt(obj);
  18043. obj = lexer.getObj();
  18044. // TODO are /dstName used?
  18045. expectString(obj);
  18046. var dst = obj;
  18047. cMap.mapOne(src, dst);
  18048. }
  18049. }
  18050. function parseBfRange(cMap, lexer) {
  18051. while (true) {
  18052. var obj = lexer.getObj();
  18053. if (isEOF(obj)) {
  18054. break;
  18055. }
  18056. if (isCmd(obj, 'endbfrange')) {
  18057. return;
  18058. }
  18059. expectString(obj);
  18060. var low = strToInt(obj);
  18061. obj = lexer.getObj();
  18062. expectString(obj);
  18063. var high = strToInt(obj);
  18064. obj = lexer.getObj();
  18065. if (isInt(obj) || isString(obj)) {
  18066. var dstLow = isInt(obj) ? String.fromCharCode(obj) : obj;
  18067. cMap.mapBfRange(low, high, dstLow);
  18068. } else if (isCmd(obj, '[')) {
  18069. obj = lexer.getObj();
  18070. var array = [];
  18071. while (!isCmd(obj, ']') && !isEOF(obj)) {
  18072. array.push(obj);
  18073. obj = lexer.getObj();
  18074. }
  18075. cMap.mapBfRangeToArray(low, high, array);
  18076. } else {
  18077. break;
  18078. }
  18079. }
  18080. error('Invalid bf range.');
  18081. }
  18082. function parseCidChar(cMap, lexer) {
  18083. while (true) {
  18084. var obj = lexer.getObj();
  18085. if (isEOF(obj)) {
  18086. break;
  18087. }
  18088. if (isCmd(obj, 'endcidchar')) {
  18089. return;
  18090. }
  18091. expectString(obj);
  18092. var src = strToInt(obj);
  18093. obj = lexer.getObj();
  18094. expectInt(obj);
  18095. var dst = obj;
  18096. cMap.mapOne(src, dst);
  18097. }
  18098. }
  18099. function parseCidRange(cMap, lexer) {
  18100. while (true) {
  18101. var obj = lexer.getObj();
  18102. if (isEOF(obj)) {
  18103. break;
  18104. }
  18105. if (isCmd(obj, 'endcidrange')) {
  18106. return;
  18107. }
  18108. expectString(obj);
  18109. var low = strToInt(obj);
  18110. obj = lexer.getObj();
  18111. expectString(obj);
  18112. var high = strToInt(obj);
  18113. obj = lexer.getObj();
  18114. expectInt(obj);
  18115. var dstLow = obj;
  18116. cMap.mapCidRange(low, high, dstLow);
  18117. }
  18118. }
  18119. function parseCodespaceRange(cMap, lexer) {
  18120. while (true) {
  18121. var obj = lexer.getObj();
  18122. if (isEOF(obj)) {
  18123. break;
  18124. }
  18125. if (isCmd(obj, 'endcodespacerange')) {
  18126. return;
  18127. }
  18128. if (!isString(obj)) {
  18129. break;
  18130. }
  18131. var low = strToInt(obj);
  18132. obj = lexer.getObj();
  18133. if (!isString(obj)) {
  18134. break;
  18135. }
  18136. var high = strToInt(obj);
  18137. cMap.addCodespaceRange(obj.length, low, high);
  18138. }
  18139. error('Invalid codespace range.');
  18140. }
  18141. function parseWMode(cMap, lexer) {
  18142. var obj = lexer.getObj();
  18143. if (isInt(obj)) {
  18144. cMap.vertical = !!obj;
  18145. }
  18146. }
  18147. function parseCMap(cMap, lexer, builtInCMapParams, useCMap) {
  18148. var previous;
  18149. var embededUseCMap;
  18150. objLoop: while (true) {
  18151. var obj = lexer.getObj();
  18152. if (isEOF(obj)) {
  18153. break;
  18154. } else if (isName(obj)) {
  18155. if (obj.name === 'WMode') {
  18156. parseWMode(cMap, lexer);
  18157. }
  18158. previous = obj;
  18159. } else if (isCmd(obj)) {
  18160. switch (obj.cmd) {
  18161. case 'endcmap':
  18162. break objLoop;
  18163. case 'usecmap':
  18164. if (isName(previous)) {
  18165. embededUseCMap = previous.name;
  18166. }
  18167. break;
  18168. case 'begincodespacerange':
  18169. parseCodespaceRange(cMap, lexer);
  18170. break;
  18171. case 'beginbfchar':
  18172. parseBfChar(cMap, lexer);
  18173. break;
  18174. case 'begincidchar':
  18175. parseCidChar(cMap, lexer);
  18176. break;
  18177. case 'beginbfrange':
  18178. parseBfRange(cMap, lexer);
  18179. break;
  18180. case 'begincidrange':
  18181. parseCidRange(cMap, lexer);
  18182. break;
  18183. }
  18184. }
  18185. }
  18186. if (!useCMap && embededUseCMap) {
  18187. // Load the usecmap definition from the file only if there wasn't one
  18188. // specified.
  18189. useCMap = embededUseCMap;
  18190. }
  18191. if (useCMap) {
  18192. extendCMap(cMap, builtInCMapParams, useCMap);
  18193. }
  18194. }
  18195. function extendCMap(cMap, builtInCMapParams, useCMap) {
  18196. cMap.useCMap = createBuiltInCMap(useCMap, builtInCMapParams);
  18197. // If there aren't any code space ranges defined clone all the parent ones
  18198. // into this cMap.
  18199. if (cMap.numCodespaceRanges === 0) {
  18200. var useCodespaceRanges = cMap.useCMap.codespaceRanges;
  18201. for (var i = 0; i < useCodespaceRanges.length; i++) {
  18202. cMap.codespaceRanges[i] = useCodespaceRanges[i].slice();
  18203. }
  18204. cMap.numCodespaceRanges = cMap.useCMap.numCodespaceRanges;
  18205. }
  18206. // Merge the map into the current one, making sure not to override
  18207. // any previously defined entries.
  18208. cMap.useCMap.forEach(function(key, value) {
  18209. if (!cMap.contains(key)) {
  18210. cMap.mapOne(key, cMap.useCMap.lookup(key));
  18211. }
  18212. });
  18213. }
  18214. function parseBinaryCMap(name, builtInCMapParams) {
  18215. var url = builtInCMapParams.url + name + '.bcmap';
  18216. var cMap = new CMap(true);
  18217. new BinaryCMapReader().read(url, cMap, function (useCMap) {
  18218. extendCMap(cMap, builtInCMapParams, useCMap);
  18219. });
  18220. return cMap;
  18221. }
  18222. function createBuiltInCMap(name, builtInCMapParams) {
  18223. if (name === 'Identity-H') {
  18224. return new IdentityCMap(false, 2);
  18225. } else if (name === 'Identity-V') {
  18226. return new IdentityCMap(true, 2);
  18227. }
  18228. if (BUILT_IN_CMAPS.indexOf(name) === -1) {
  18229. error('Unknown cMap name: ' + name);
  18230. }
  18231. assert(builtInCMapParams, 'built-in cMap parameters are not provided');
  18232. if (builtInCMapParams.packed) {
  18233. return parseBinaryCMap(name, builtInCMapParams);
  18234. }
  18235. var request = new XMLHttpRequest();
  18236. var url = builtInCMapParams.url + name;
  18237. request.open('GET', url, false);
  18238. request.send(null);
  18239. if (!request.responseText) {
  18240. error('Unable to get cMap at: ' + url);
  18241. }
  18242. var cMap = new CMap(true);
  18243. var lexer = new Lexer(new StringStream(request.responseText));
  18244. parseCMap(cMap, lexer, builtInCMapParams, null);
  18245. return cMap;
  18246. }
  18247. return {
  18248. create: function (encoding, builtInCMapParams, useCMap) {
  18249. if (isName(encoding)) {
  18250. return createBuiltInCMap(encoding.name, builtInCMapParams);
  18251. } else if (isStream(encoding)) {
  18252. var cMap = new CMap();
  18253. var lexer = new Lexer(encoding);
  18254. try {
  18255. parseCMap(cMap, lexer, builtInCMapParams, useCMap);
  18256. } catch (e) {
  18257. warn('Invalid CMap data. ' + e);
  18258. }
  18259. return cMap;
  18260. }
  18261. error('Encoding required.');
  18262. }
  18263. };
  18264. })();
  18265. // Unicode Private Use Area
  18266. var PRIVATE_USE_OFFSET_START = 0xE000;
  18267. var PRIVATE_USE_OFFSET_END = 0xF8FF;
  18268. var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false;
  18269. // PDF Glyph Space Units are one Thousandth of a TextSpace Unit
  18270. // except for Type 3 fonts
  18271. var PDF_GLYPH_SPACE_UNITS = 1000;
  18272. // Hinting is currently disabled due to unknown problems on windows
  18273. // in tracemonkey and various other pdfs with type1 fonts.
  18274. var HINTING_ENABLED = false;
  18275. // Accented charactars are not displayed properly on windows, using this flag
  18276. // to control analysis of seac charstrings.
  18277. var SEAC_ANALYSIS_ENABLED = false;
  18278. var FontFlags = {
  18279. FixedPitch: 1,
  18280. Serif: 2,
  18281. Symbolic: 4,
  18282. Script: 8,
  18283. Nonsymbolic: 32,
  18284. Italic: 64,
  18285. AllCap: 65536,
  18286. SmallCap: 131072,
  18287. ForceBold: 262144
  18288. };
  18289. var Encodings = {
  18290. ExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18291. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18292. 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle',
  18293. 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior',
  18294. 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma',
  18295. 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle',
  18296. 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle',
  18297. 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon',
  18298. 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior',
  18299. 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior',
  18300. 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior',
  18301. 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior',
  18302. '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '',
  18303. 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall',
  18304. 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
  18305. 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall',
  18306. 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall',
  18307. 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary',
  18308. 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '',
  18309. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18310. '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
  18311. '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall',
  18312. 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '',
  18313. 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall',
  18314. 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters',
  18315. 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths',
  18316. 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior',
  18317. 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior',
  18318. 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior',
  18319. 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior',
  18320. 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior',
  18321. 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior',
  18322. 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall',
  18323. 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall',
  18324. 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall',
  18325. 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
  18326. 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall',
  18327. 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
  18328. 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
  18329. 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall',
  18330. 'Ydieresissmall'],
  18331. MacExpertEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18332. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18333. 'space', 'exclamsmall', 'Hungarumlautsmall', 'centoldstyle',
  18334. 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall',
  18335. 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  18336. 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle',
  18337. 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle',
  18338. 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle',
  18339. 'nineoldstyle', 'colon', 'semicolon', '', 'threequartersemdash', '',
  18340. 'questionsmall', '', '', '', '', 'Ethsmall', '', '', 'onequarter',
  18341. 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths',
  18342. 'seveneighths', 'onethird', 'twothirds', '', '', '', '', '', '', 'ff',
  18343. 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior',
  18344. 'Circumflexsmall', 'hypheninferior', 'Gravesmall', 'Asmall', 'Bsmall',
  18345. 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
  18346. 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
  18347. 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  18348. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
  18349. 'Tildesmall', '', '', 'asuperior', 'centsuperior', '', '', '', '',
  18350. 'Aacutesmall', 'Agravesmall', 'Acircumflexsmall', 'Adieresissmall',
  18351. 'Atildesmall', 'Aringsmall', 'Ccedillasmall', 'Eacutesmall', 'Egravesmall',
  18352. 'Ecircumflexsmall', 'Edieresissmall', 'Iacutesmall', 'Igravesmall',
  18353. 'Icircumflexsmall', 'Idieresissmall', 'Ntildesmall', 'Oacutesmall',
  18354. 'Ogravesmall', 'Ocircumflexsmall', 'Odieresissmall', 'Otildesmall',
  18355. 'Uacutesmall', 'Ugravesmall', 'Ucircumflexsmall', 'Udieresissmall', '',
  18356. 'eightsuperior', 'fourinferior', 'threeinferior', 'sixinferior',
  18357. 'eightinferior', 'seveninferior', 'Scaronsmall', '', 'centinferior',
  18358. 'twoinferior', '', 'Dieresissmall', '', 'Caronsmall', 'osuperior',
  18359. 'fiveinferior', '', 'commainferior', 'periodinferior', 'Yacutesmall', '',
  18360. 'dollarinferior', '', 'Thornsmall', '', 'nineinferior', 'zeroinferior',
  18361. 'Zcaronsmall', 'AEsmall', 'Oslashsmall', 'questiondownsmall',
  18362. 'oneinferior', 'Lslashsmall', '', '', '', '', '', '', 'Cedillasmall', '',
  18363. '', '', '', '', 'OEsmall', 'figuredash', 'hyphensuperior', '', '', '', '',
  18364. 'exclamdownsmall', '', 'Ydieresissmall', '', 'onesuperior', 'twosuperior',
  18365. 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
  18366. 'sevensuperior', 'ninesuperior', 'zerosuperior', '', 'esuperior',
  18367. 'rsuperior', 'tsuperior', '', '', 'isuperior', 'ssuperior', 'dsuperior',
  18368. '', '', '', '', '', 'lsuperior', 'Ogoneksmall', 'Brevesmall',
  18369. 'Macronsmall', 'bsuperior', 'nsuperior', 'msuperior', 'commasuperior',
  18370. 'periodsuperior', 'Dotaccentsmall', 'Ringsmall'],
  18371. MacRomanEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18372. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18373. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  18374. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus',
  18375. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  18376. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  18377. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  18378. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  18379. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  18380. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  18381. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  18382. 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '',
  18383. 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis',
  18384. 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde',
  18385. 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  18386. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute',
  18387. 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave',
  18388. 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling',
  18389. 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright',
  18390. 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity',
  18391. 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff',
  18392. 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine',
  18393. 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot',
  18394. 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft',
  18395. 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE',
  18396. 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft',
  18397. 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction',
  18398. 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl',
  18399. 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand',
  18400. 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute',
  18401. 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple',
  18402. 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex',
  18403. 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut',
  18404. 'ogonek', 'caron'],
  18405. StandardEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18406. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18407. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  18408. 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
  18409. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  18410. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  18411. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  18412. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  18413. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  18414. 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f',
  18415. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
  18416. 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  18417. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18418. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdown',
  18419. 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  18420. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  18421. 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', 'daggerdbl',
  18422. 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase',
  18423. 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis',
  18424. 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex',
  18425. 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla',
  18426. '', 'hungarumlaut', 'ogonek', 'caron', 'emdash', '', '', '', '', '', '',
  18427. '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '',
  18428. '', '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae',
  18429. '', '', '', 'dotlessi', '', '', 'lslash', 'oslash', 'oe', 'germandbls'],
  18430. WinAnsiEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18431. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18432. 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  18433. 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus',
  18434. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three',
  18435. 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon',
  18436. 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F',
  18437. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  18438. 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
  18439. 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  18440. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  18441. 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
  18442. 'bullet', 'Euro', 'bullet', 'quotesinglbase', 'florin', 'quotedblbase',
  18443. 'ellipsis', 'dagger', 'daggerdbl', 'circumflex', 'perthousand', 'Scaron',
  18444. 'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', 'quoteleft',
  18445. 'quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash',
  18446. 'emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', 'oe', 'bullet',
  18447. 'zcaron', 'Ydieresis', 'space', 'exclamdown', 'cent', 'sterling',
  18448. 'currency', 'yen', 'brokenbar', 'section', 'dieresis', 'copyright',
  18449. 'ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', 'registered',
  18450. 'macron', 'degree', 'plusminus', 'twosuperior', 'threesuperior', 'acute',
  18451. 'mu', 'paragraph', 'periodcentered', 'cedilla', 'onesuperior',
  18452. 'ordmasculine', 'guillemotright', 'onequarter', 'onehalf', 'threequarters',
  18453. 'questiondown', 'Agrave', 'Aacute', 'Acircumflex', 'Atilde', 'Adieresis',
  18454. 'Aring', 'AE', 'Ccedilla', 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis',
  18455. 'Igrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve',
  18456. 'Oacute', 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash',
  18457. 'Ugrave', 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn',
  18458. 'germandbls', 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis',
  18459. 'aring', 'ae', 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis',
  18460. 'igrave', 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve',
  18461. 'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash',
  18462. 'ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn',
  18463. 'ydieresis'],
  18464. SymbolSetEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18465. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18466. 'space', 'exclam', 'universal', 'numbersign', 'existential', 'percent',
  18467. 'ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus',
  18468. 'comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
  18469. 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  18470. 'equal', 'greater', 'question', 'congruent', 'Alpha', 'Beta', 'Chi',
  18471. 'Delta', 'Epsilon', 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa',
  18472. 'Lambda', 'Mu', 'Nu', 'Omicron', 'Pi', 'Theta', 'Rho', 'Sigma', 'Tau',
  18473. 'Upsilon', 'sigma1', 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft',
  18474. 'therefore', 'bracketright', 'perpendicular', 'underscore', 'radicalex',
  18475. 'alpha', 'beta', 'chi', 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota',
  18476. 'phi1', 'kappa', 'lambda', 'mu', 'nu', 'omicron', 'pi', 'theta', 'rho',
  18477. 'sigma', 'tau', 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta',
  18478. 'braceleft', 'bar', 'braceright', 'similar', '', '', '', '', '', '', '',
  18479. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18480. '', '', '', '', '', '', '', 'Euro', 'Upsilon1', 'minute', 'lessequal',
  18481. 'fraction', 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade',
  18482. 'arrowboth', 'arrowleft', 'arrowup', 'arrowright', 'arrowdown', 'degree',
  18483. 'plusminus', 'second', 'greaterequal', 'multiply', 'proportional',
  18484. 'partialdiff', 'bullet', 'divide', 'notequal', 'equivalence',
  18485. 'approxequal', 'ellipsis', 'arrowvertex', 'arrowhorizex', 'carriagereturn',
  18486. 'aleph', 'Ifraktur', 'Rfraktur', 'weierstrass', 'circlemultiply',
  18487. 'circleplus', 'emptyset', 'intersection', 'union', 'propersuperset',
  18488. 'reflexsuperset', 'notsubset', 'propersubset', 'reflexsubset', 'element',
  18489. 'notelement', 'angle', 'gradient', 'registerserif', 'copyrightserif',
  18490. 'trademarkserif', 'product', 'radical', 'dotmath', 'logicalnot',
  18491. 'logicaland', 'logicalor', 'arrowdblboth', 'arrowdblleft', 'arrowdblup',
  18492. 'arrowdblright', 'arrowdbldown', 'lozenge', 'angleleft', 'registersans',
  18493. 'copyrightsans', 'trademarksans', 'summation', 'parenlefttp',
  18494. 'parenleftex', 'parenleftbt', 'bracketlefttp', 'bracketleftex',
  18495. 'bracketleftbt', 'bracelefttp', 'braceleftmid', 'braceleftbt', 'braceex',
  18496. '', 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt',
  18497. 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp',
  18498. 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid',
  18499. 'bracerightbt'],
  18500. ZapfDingbatsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18501. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  18502. 'space', 'a1', 'a2', 'a202', 'a3', 'a4', 'a5', 'a119', 'a118', 'a117',
  18503. 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a105', 'a17', 'a18', 'a19',
  18504. 'a20', 'a21', 'a22', 'a23', 'a24', 'a25', 'a26', 'a27', 'a28', 'a6', 'a7',
  18505. 'a8', 'a9', 'a10', 'a29', 'a30', 'a31', 'a32', 'a33', 'a34', 'a35', 'a36',
  18506. 'a37', 'a38', 'a39', 'a40', 'a41', 'a42', 'a43', 'a44', 'a45', 'a46',
  18507. 'a47', 'a48', 'a49', 'a50', 'a51', 'a52', 'a53', 'a54', 'a55', 'a56',
  18508. 'a57', 'a58', 'a59', 'a60', 'a61', 'a62', 'a63', 'a64', 'a65', 'a66',
  18509. 'a67', 'a68', 'a69', 'a70', 'a71', 'a72', 'a73', 'a74', 'a203', 'a75',
  18510. 'a204', 'a76', 'a77', 'a78', 'a79', 'a81', 'a82', 'a83', 'a84', 'a97',
  18511. 'a98', 'a99', 'a100', '', 'a89', 'a90', 'a93', 'a94', 'a91', 'a92', 'a205',
  18512. 'a85', 'a206', 'a86', 'a87', 'a88', 'a95', 'a96', '', '', '', '', '', '',
  18513. '', '', '', '', '', '', '', '', '', '', '', '', '', 'a101', 'a102', 'a103',
  18514. 'a104', 'a106', 'a107', 'a108', 'a112', 'a111', 'a110', 'a109', 'a120',
  18515. 'a121', 'a122', 'a123', 'a124', 'a125', 'a126', 'a127', 'a128', 'a129',
  18516. 'a130', 'a131', 'a132', 'a133', 'a134', 'a135', 'a136', 'a137', 'a138',
  18517. 'a139', 'a140', 'a141', 'a142', 'a143', 'a144', 'a145', 'a146', 'a147',
  18518. 'a148', 'a149', 'a150', 'a151', 'a152', 'a153', 'a154', 'a155', 'a156',
  18519. 'a157', 'a158', 'a159', 'a160', 'a161', 'a163', 'a164', 'a196', 'a165',
  18520. 'a192', 'a166', 'a167', 'a168', 'a169', 'a170', 'a171', 'a172', 'a173',
  18521. 'a162', 'a174', 'a175', 'a176', 'a177', 'a178', 'a179', 'a193', 'a180',
  18522. 'a199', 'a181', 'a200', 'a182', '', 'a201', 'a183', 'a184', 'a197', 'a185',
  18523. 'a194', 'a198', 'a186', 'a195', 'a187', 'a188', 'a189', 'a190', 'a191']
  18524. };
  18525. /**
  18526. * Hold a map of decoded fonts and of the standard fourteen Type1
  18527. * fonts and their acronyms.
  18528. */
  18529. var stdFontMap = {
  18530. 'ArialNarrow': 'Helvetica',
  18531. 'ArialNarrow-Bold': 'Helvetica-Bold',
  18532. 'ArialNarrow-BoldItalic': 'Helvetica-BoldOblique',
  18533. 'ArialNarrow-Italic': 'Helvetica-Oblique',
  18534. 'ArialBlack': 'Helvetica',
  18535. 'ArialBlack-Bold': 'Helvetica-Bold',
  18536. 'ArialBlack-BoldItalic': 'Helvetica-BoldOblique',
  18537. 'ArialBlack-Italic': 'Helvetica-Oblique',
  18538. 'Arial': 'Helvetica',
  18539. 'Arial-Bold': 'Helvetica-Bold',
  18540. 'Arial-BoldItalic': 'Helvetica-BoldOblique',
  18541. 'Arial-Italic': 'Helvetica-Oblique',
  18542. 'Arial-BoldItalicMT': 'Helvetica-BoldOblique',
  18543. 'Arial-BoldMT': 'Helvetica-Bold',
  18544. 'Arial-ItalicMT': 'Helvetica-Oblique',
  18545. 'ArialMT': 'Helvetica',
  18546. 'Courier-Bold': 'Courier-Bold',
  18547. 'Courier-BoldItalic': 'Courier-BoldOblique',
  18548. 'Courier-Italic': 'Courier-Oblique',
  18549. 'CourierNew': 'Courier',
  18550. 'CourierNew-Bold': 'Courier-Bold',
  18551. 'CourierNew-BoldItalic': 'Courier-BoldOblique',
  18552. 'CourierNew-Italic': 'Courier-Oblique',
  18553. 'CourierNewPS-BoldItalicMT': 'Courier-BoldOblique',
  18554. 'CourierNewPS-BoldMT': 'Courier-Bold',
  18555. 'CourierNewPS-ItalicMT': 'Courier-Oblique',
  18556. 'CourierNewPSMT': 'Courier',
  18557. 'Helvetica': 'Helvetica',
  18558. 'Helvetica-Bold': 'Helvetica-Bold',
  18559. 'Helvetica-BoldItalic': 'Helvetica-BoldOblique',
  18560. 'Helvetica-BoldOblique': 'Helvetica-BoldOblique',
  18561. 'Helvetica-Italic': 'Helvetica-Oblique',
  18562. 'Helvetica-Oblique':'Helvetica-Oblique',
  18563. 'Symbol-Bold': 'Symbol',
  18564. 'Symbol-BoldItalic': 'Symbol',
  18565. 'Symbol-Italic': 'Symbol',
  18566. 'TimesNewRoman': 'Times-Roman',
  18567. 'TimesNewRoman-Bold': 'Times-Bold',
  18568. 'TimesNewRoman-BoldItalic': 'Times-BoldItalic',
  18569. 'TimesNewRoman-Italic': 'Times-Italic',
  18570. 'TimesNewRomanPS': 'Times-Roman',
  18571. 'TimesNewRomanPS-Bold': 'Times-Bold',
  18572. 'TimesNewRomanPS-BoldItalic': 'Times-BoldItalic',
  18573. 'TimesNewRomanPS-BoldItalicMT': 'Times-BoldItalic',
  18574. 'TimesNewRomanPS-BoldMT': 'Times-Bold',
  18575. 'TimesNewRomanPS-Italic': 'Times-Italic',
  18576. 'TimesNewRomanPS-ItalicMT': 'Times-Italic',
  18577. 'TimesNewRomanPSMT': 'Times-Roman',
  18578. 'TimesNewRomanPSMT-Bold': 'Times-Bold',
  18579. 'TimesNewRomanPSMT-BoldItalic': 'Times-BoldItalic',
  18580. 'TimesNewRomanPSMT-Italic': 'Times-Italic'
  18581. };
  18582. /**
  18583. * Holds the map of the non-standard fonts that might be included as a standard
  18584. * fonts without glyph data.
  18585. */
  18586. var nonStdFontMap = {
  18587. 'CenturyGothic': 'Helvetica',
  18588. 'CenturyGothic-Bold': 'Helvetica-Bold',
  18589. 'CenturyGothic-BoldItalic': 'Helvetica-BoldOblique',
  18590. 'CenturyGothic-Italic': 'Helvetica-Oblique',
  18591. 'ComicSansMS': 'Comic Sans MS',
  18592. 'ComicSansMS-Bold': 'Comic Sans MS-Bold',
  18593. 'ComicSansMS-BoldItalic': 'Comic Sans MS-BoldItalic',
  18594. 'ComicSansMS-Italic': 'Comic Sans MS-Italic',
  18595. 'LucidaConsole': 'Courier',
  18596. 'LucidaConsole-Bold': 'Courier-Bold',
  18597. 'LucidaConsole-BoldItalic': 'Courier-BoldOblique',
  18598. 'LucidaConsole-Italic': 'Courier-Oblique',
  18599. 'MS-Gothic': 'MS Gothic',
  18600. 'MS-Gothic-Bold': 'MS Gothic-Bold',
  18601. 'MS-Gothic-BoldItalic': 'MS Gothic-BoldItalic',
  18602. 'MS-Gothic-Italic': 'MS Gothic-Italic',
  18603. 'MS-Mincho': 'MS Mincho',
  18604. 'MS-Mincho-Bold': 'MS Mincho-Bold',
  18605. 'MS-Mincho-BoldItalic': 'MS Mincho-BoldItalic',
  18606. 'MS-Mincho-Italic': 'MS Mincho-Italic',
  18607. 'MS-PGothic': 'MS PGothic',
  18608. 'MS-PGothic-Bold': 'MS PGothic-Bold',
  18609. 'MS-PGothic-BoldItalic': 'MS PGothic-BoldItalic',
  18610. 'MS-PGothic-Italic': 'MS PGothic-Italic',
  18611. 'MS-PMincho': 'MS PMincho',
  18612. 'MS-PMincho-Bold': 'MS PMincho-Bold',
  18613. 'MS-PMincho-BoldItalic': 'MS PMincho-BoldItalic',
  18614. 'MS-PMincho-Italic': 'MS PMincho-Italic',
  18615. 'Wingdings': 'ZapfDingbats'
  18616. };
  18617. var serifFonts = {
  18618. 'Adobe Jenson': true, 'Adobe Text': true, 'Albertus': true,
  18619. 'Aldus': true, 'Alexandria': true, 'Algerian': true,
  18620. 'American Typewriter': true, 'Antiqua': true, 'Apex': true,
  18621. 'Arno': true, 'Aster': true, 'Aurora': true,
  18622. 'Baskerville': true, 'Bell': true, 'Bembo': true,
  18623. 'Bembo Schoolbook': true, 'Benguiat': true, 'Berkeley Old Style': true,
  18624. 'Bernhard Modern': true, 'Berthold City': true, 'Bodoni': true,
  18625. 'Bauer Bodoni': true, 'Book Antiqua': true, 'Bookman': true,
  18626. 'Bordeaux Roman': true, 'Californian FB': true, 'Calisto': true,
  18627. 'Calvert': true, 'Capitals': true, 'Cambria': true,
  18628. 'Cartier': true, 'Caslon': true, 'Catull': true,
  18629. 'Centaur': true, 'Century Old Style': true, 'Century Schoolbook': true,
  18630. 'Chaparral': true, 'Charis SIL': true, 'Cheltenham': true,
  18631. 'Cholla Slab': true, 'Clarendon': true, 'Clearface': true,
  18632. 'Cochin': true, 'Colonna': true, 'Computer Modern': true,
  18633. 'Concrete Roman': true, 'Constantia': true, 'Cooper Black': true,
  18634. 'Corona': true, 'Ecotype': true, 'Egyptienne': true,
  18635. 'Elephant': true, 'Excelsior': true, 'Fairfield': true,
  18636. 'FF Scala': true, 'Folkard': true, 'Footlight': true,
  18637. 'FreeSerif': true, 'Friz Quadrata': true, 'Garamond': true,
  18638. 'Gentium': true, 'Georgia': true, 'Gloucester': true,
  18639. 'Goudy Old Style': true, 'Goudy Schoolbook': true, 'Goudy Pro Font': true,
  18640. 'Granjon': true, 'Guardian Egyptian': true, 'Heather': true,
  18641. 'Hercules': true, 'High Tower Text': true, 'Hiroshige': true,
  18642. 'Hoefler Text': true, 'Humana Serif': true, 'Imprint': true,
  18643. 'Ionic No. 5': true, 'Janson': true, 'Joanna': true,
  18644. 'Korinna': true, 'Lexicon': true, 'Liberation Serif': true,
  18645. 'Linux Libertine': true, 'Literaturnaya': true, 'Lucida': true,
  18646. 'Lucida Bright': true, 'Melior': true, 'Memphis': true,
  18647. 'Miller': true, 'Minion': true, 'Modern': true,
  18648. 'Mona Lisa': true, 'Mrs Eaves': true, 'MS Serif': true,
  18649. 'Museo Slab': true, 'New York': true, 'Nimbus Roman': true,
  18650. 'NPS Rawlinson Roadway': true, 'Palatino': true, 'Perpetua': true,
  18651. 'Plantin': true, 'Plantin Schoolbook': true, 'Playbill': true,
  18652. 'Poor Richard': true, 'Rawlinson Roadway': true, 'Renault': true,
  18653. 'Requiem': true, 'Rockwell': true, 'Roman': true,
  18654. 'Rotis Serif': true, 'Sabon': true, 'Scala': true,
  18655. 'Seagull': true, 'Sistina': true, 'Souvenir': true,
  18656. 'STIX': true, 'Stone Informal': true, 'Stone Serif': true,
  18657. 'Sylfaen': true, 'Times': true, 'Trajan': true,
  18658. 'Trinité': true, 'Trump Mediaeval': true, 'Utopia': true,
  18659. 'Vale Type': true, 'Bitstream Vera': true, 'Vera Serif': true,
  18660. 'Versailles': true, 'Wanted': true, 'Weiss': true,
  18661. 'Wide Latin': true, 'Windsor': true, 'XITS': true
  18662. };
  18663. var symbolsFonts = {
  18664. 'Dingbats': true, 'Symbol': true, 'ZapfDingbats': true
  18665. };
  18666. // Glyph map for well-known standard fonts. Sometimes Ghostscript uses CID fonts
  18667. // but does not embed the CID to GID mapping. The mapping is incomplete for all
  18668. // glyphs, but common for some set of the standard fonts.
  18669. var GlyphMapForStandardFonts = {
  18670. '2': 10, '3': 32, '4': 33, '5': 34, '6': 35, '7': 36, '8': 37, '9': 38,
  18671. '10': 39, '11': 40, '12': 41, '13': 42, '14': 43, '15': 44, '16': 45,
  18672. '17': 46, '18': 47, '19': 48, '20': 49, '21': 50, '22': 51, '23': 52,
  18673. '24': 53, '25': 54, '26': 55, '27': 56, '28': 57, '29': 58, '30': 894,
  18674. '31': 60, '32': 61, '33': 62, '34': 63, '35': 64, '36': 65, '37': 66,
  18675. '38': 67, '39': 68, '40': 69, '41': 70, '42': 71, '43': 72, '44': 73,
  18676. '45': 74, '46': 75, '47': 76, '48': 77, '49': 78, '50': 79, '51': 80,
  18677. '52': 81, '53': 82, '54': 83, '55': 84, '56': 85, '57': 86, '58': 87,
  18678. '59': 88, '60': 89, '61': 90, '62': 91, '63': 92, '64': 93, '65': 94,
  18679. '66': 95, '67': 96, '68': 97, '69': 98, '70': 99, '71': 100, '72': 101,
  18680. '73': 102, '74': 103, '75': 104, '76': 105, '77': 106, '78': 107, '79': 108,
  18681. '80': 109, '81': 110, '82': 111, '83': 112, '84': 113, '85': 114, '86': 115,
  18682. '87': 116, '88': 117, '89': 118, '90': 119, '91': 120, '92': 121, '93': 122,
  18683. '94': 123, '95': 124, '96': 125, '97': 126, '98': 196, '99': 197, '100': 199,
  18684. '101': 201, '102': 209, '103': 214, '104': 220, '105': 225, '106': 224,
  18685. '107': 226, '108': 228, '109': 227, '110': 229, '111': 231, '112': 233,
  18686. '113': 232, '114': 234, '115': 235, '116': 237, '117': 236, '118': 238,
  18687. '119': 239, '120': 241, '121': 243, '122': 242, '123': 244, '124': 246,
  18688. '125': 245, '126': 250, '127': 249, '128': 251, '129': 252, '130': 8224,
  18689. '131': 176, '132': 162, '133': 163, '134': 167, '135': 8226, '136': 182,
  18690. '137': 223, '138': 174, '139': 169, '140': 8482, '141': 180, '142': 168,
  18691. '143': 8800, '144': 198, '145': 216, '146': 8734, '147': 177, '148': 8804,
  18692. '149': 8805, '150': 165, '151': 181, '152': 8706, '153': 8721, '154': 8719,
  18693. '156': 8747, '157': 170, '158': 186, '159': 8486, '160': 230, '161': 248,
  18694. '162': 191, '163': 161, '164': 172, '165': 8730, '166': 402, '167': 8776,
  18695. '168': 8710, '169': 171, '170': 187, '171': 8230, '210': 218, '223': 711,
  18696. '224': 321, '225': 322, '227': 353, '229': 382, '234': 253, '252': 263,
  18697. '253': 268, '254': 269, '258': 258, '260': 260, '261': 261, '265': 280,
  18698. '266': 281, '268': 283, '269': 313, '275': 323, '276': 324, '278': 328,
  18699. '284': 345, '285': 346, '286': 347, '292': 367, '295': 377, '296': 378,
  18700. '298': 380, '305': 963,
  18701. '306': 964, '307': 966, '308': 8215, '309': 8252, '310': 8319, '311': 8359,
  18702. '312': 8592, '313': 8593, '337': 9552, '493': 1039, '494': 1040, '705': 1524,
  18703. '706': 8362, '710': 64288, '711': 64298, '759': 1617, '761': 1776,
  18704. '763': 1778, '775': 1652, '777': 1764, '778': 1780, '779': 1781, '780': 1782,
  18705. '782': 771, '783': 64726, '786': 8363, '788': 8532, '790': 768, '791': 769,
  18706. '792': 768, '795': 803, '797': 64336, '798': 64337, '799': 64342,
  18707. '800': 64343, '801': 64344, '802': 64345, '803': 64362, '804': 64363,
  18708. '805': 64364, '2424': 7821, '2425': 7822, '2426': 7823, '2427': 7824,
  18709. '2428': 7825, '2429': 7826, '2430': 7827, '2433': 7682, '2678': 8045,
  18710. '2679': 8046, '2830': 1552, '2838': 686, '2840': 751, '2842': 753,
  18711. '2843': 754, '2844': 755, '2846': 757, '2856': 767, '2857': 848, '2858': 849,
  18712. '2862': 853, '2863': 854, '2864': 855, '2865': 861, '2866': 862, '2906': 7460,
  18713. '2908': 7462, '2909': 7463, '2910': 7464, '2912': 7466, '2913': 7467,
  18714. '2914': 7468, '2916': 7470, '2917': 7471, '2918': 7472, '2920': 7474,
  18715. '2921': 7475, '2922': 7476, '2924': 7478, '2925': 7479, '2926': 7480,
  18716. '2928': 7482, '2929': 7483, '2930': 7484, '2932': 7486, '2933': 7487,
  18717. '2934': 7488, '2936': 7490, '2937': 7491, '2938': 7492, '2940': 7494,
  18718. '2941': 7495, '2942': 7496, '2944': 7498, '2946': 7500, '2948': 7502,
  18719. '2950': 7504, '2951': 7505, '2952': 7506, '2954': 7508, '2955': 7509,
  18720. '2956': 7510, '2958': 7512, '2959': 7513, '2960': 7514, '2962': 7516,
  18721. '2963': 7517, '2964': 7518, '2966': 7520, '2967': 7521, '2968': 7522,
  18722. '2970': 7524, '2971': 7525, '2972': 7526, '2974': 7528, '2975': 7529,
  18723. '2976': 7530, '2978': 1537, '2979': 1538, '2980': 1539, '2982': 1549,
  18724. '2983': 1551, '2984': 1552, '2986': 1554, '2987': 1555, '2988': 1556,
  18725. '2990': 1623, '2991': 1624, '2995': 1775, '2999': 1791, '3002': 64290,
  18726. '3003': 64291, '3004': 64292, '3006': 64294, '3007': 64295, '3008': 64296,
  18727. '3011': 1900, '3014': 8223, '3015': 8244, '3017': 7532, '3018': 7533,
  18728. '3019': 7534, '3075': 7590, '3076': 7591, '3079': 7594, '3080': 7595,
  18729. '3083': 7598, '3084': 7599, '3087': 7602, '3088': 7603, '3091': 7606,
  18730. '3092': 7607, '3095': 7610, '3096': 7611, '3099': 7614, '3100': 7615,
  18731. '3103': 7618, '3104': 7619, '3107': 8337, '3108': 8338, '3116': 1884,
  18732. '3119': 1885, '3120': 1885, '3123': 1886, '3124': 1886, '3127': 1887,
  18733. '3128': 1887, '3131': 1888, '3132': 1888, '3135': 1889, '3136': 1889,
  18734. '3139': 1890, '3140': 1890, '3143': 1891, '3144': 1891, '3147': 1892,
  18735. '3148': 1892, '3153': 580, '3154': 581, '3157': 584, '3158': 585, '3161': 588,
  18736. '3162': 589, '3165': 891, '3166': 892, '3169': 1274, '3170': 1275,
  18737. '3173': 1278, '3174': 1279, '3181': 7622, '3182': 7623, '3282': 11799,
  18738. '3316': 578, '3379': 42785, '3393': 1159, '3416': 8377
  18739. };
  18740. // Some characters, e.g. copyrightserif, are mapped to the private use area and
  18741. // might not be displayed using standard fonts. Mapping/hacking well-known chars
  18742. // to the similar equivalents in the normal characters range.
  18743. var SpecialPUASymbols = {
  18744. '63721': 0x00A9, // copyrightsans (0xF8E9) => copyright
  18745. '63193': 0x00A9, // copyrightserif (0xF6D9) => copyright
  18746. '63720': 0x00AE, // registersans (0xF8E8) => registered
  18747. '63194': 0x00AE, // registerserif (0xF6DA) => registered
  18748. '63722': 0x2122, // trademarksans (0xF8EA) => trademark
  18749. '63195': 0x2122, // trademarkserif (0xF6DB) => trademark
  18750. '63729': 0x23A7, // bracelefttp (0xF8F1)
  18751. '63730': 0x23A8, // braceleftmid (0xF8F2)
  18752. '63731': 0x23A9, // braceleftbt (0xF8F3)
  18753. '63740': 0x23AB, // bracerighttp (0xF8FC)
  18754. '63741': 0x23AC, // bracerightmid (0xF8FD)
  18755. '63742': 0x23AD, // bracerightmid (0xF8FE)
  18756. '63726': 0x23A1, // bracketlefttp (0xF8EE)
  18757. '63727': 0x23A2, // bracketleftex (0xF8EF)
  18758. '63728': 0x23A3, // bracketleftbt (0xF8F0)
  18759. '63737': 0x23A4, // bracketrighttp (0xF8F9)
  18760. '63738': 0x23A5, // bracketrightex (0xF8FA)
  18761. '63739': 0x23A6, // bracketrightbt (0xF8FB)
  18762. '63723': 0x239B, // parenlefttp (0xF8EB)
  18763. '63724': 0x239C, // parenleftex (0xF8EC)
  18764. '63725': 0x239D, // parenleftbt (0xF8ED)
  18765. '63734': 0x239E, // parenrighttp (0xF8F6)
  18766. '63735': 0x239F, // parenrightex (0xF8F7)
  18767. '63736': 0x23A0, // parenrightbt (0xF8F8)
  18768. };
  18769. function mapSpecialUnicodeValues(code) {
  18770. if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials unicode block.
  18771. return 0;
  18772. } else if (code >= 0xF600 && code <= 0xF8FF) {
  18773. return (SpecialPUASymbols[code] || code);
  18774. }
  18775. return code;
  18776. }
  18777. var UnicodeRanges = [
  18778. { 'begin': 0x0000, 'end': 0x007F }, // Basic Latin
  18779. { 'begin': 0x0080, 'end': 0x00FF }, // Latin-1 Supplement
  18780. { 'begin': 0x0100, 'end': 0x017F }, // Latin Extended-A
  18781. { 'begin': 0x0180, 'end': 0x024F }, // Latin Extended-B
  18782. { 'begin': 0x0250, 'end': 0x02AF }, // IPA Extensions
  18783. { 'begin': 0x02B0, 'end': 0x02FF }, // Spacing Modifier Letters
  18784. { 'begin': 0x0300, 'end': 0x036F }, // Combining Diacritical Marks
  18785. { 'begin': 0x0370, 'end': 0x03FF }, // Greek and Coptic
  18786. { 'begin': 0x2C80, 'end': 0x2CFF }, // Coptic
  18787. { 'begin': 0x0400, 'end': 0x04FF }, // Cyrillic
  18788. { 'begin': 0x0530, 'end': 0x058F }, // Armenian
  18789. { 'begin': 0x0590, 'end': 0x05FF }, // Hebrew
  18790. { 'begin': 0xA500, 'end': 0xA63F }, // Vai
  18791. { 'begin': 0x0600, 'end': 0x06FF }, // Arabic
  18792. { 'begin': 0x07C0, 'end': 0x07FF }, // NKo
  18793. { 'begin': 0x0900, 'end': 0x097F }, // Devanagari
  18794. { 'begin': 0x0980, 'end': 0x09FF }, // Bengali
  18795. { 'begin': 0x0A00, 'end': 0x0A7F }, // Gurmukhi
  18796. { 'begin': 0x0A80, 'end': 0x0AFF }, // Gujarati
  18797. { 'begin': 0x0B00, 'end': 0x0B7F }, // Oriya
  18798. { 'begin': 0x0B80, 'end': 0x0BFF }, // Tamil
  18799. { 'begin': 0x0C00, 'end': 0x0C7F }, // Telugu
  18800. { 'begin': 0x0C80, 'end': 0x0CFF }, // Kannada
  18801. { 'begin': 0x0D00, 'end': 0x0D7F }, // Malayalam
  18802. { 'begin': 0x0E00, 'end': 0x0E7F }, // Thai
  18803. { 'begin': 0x0E80, 'end': 0x0EFF }, // Lao
  18804. { 'begin': 0x10A0, 'end': 0x10FF }, // Georgian
  18805. { 'begin': 0x1B00, 'end': 0x1B7F }, // Balinese
  18806. { 'begin': 0x1100, 'end': 0x11FF }, // Hangul Jamo
  18807. { 'begin': 0x1E00, 'end': 0x1EFF }, // Latin Extended Additional
  18808. { 'begin': 0x1F00, 'end': 0x1FFF }, // Greek Extended
  18809. { 'begin': 0x2000, 'end': 0x206F }, // General Punctuation
  18810. { 'begin': 0x2070, 'end': 0x209F }, // Superscripts And Subscripts
  18811. { 'begin': 0x20A0, 'end': 0x20CF }, // Currency Symbol
  18812. { 'begin': 0x20D0, 'end': 0x20FF }, // Combining Diacritical Marks For Symbols
  18813. { 'begin': 0x2100, 'end': 0x214F }, // Letterlike Symbols
  18814. { 'begin': 0x2150, 'end': 0x218F }, // Number Forms
  18815. { 'begin': 0x2190, 'end': 0x21FF }, // Arrows
  18816. { 'begin': 0x2200, 'end': 0x22FF }, // Mathematical Operators
  18817. { 'begin': 0x2300, 'end': 0x23FF }, // Miscellaneous Technical
  18818. { 'begin': 0x2400, 'end': 0x243F }, // Control Pictures
  18819. { 'begin': 0x2440, 'end': 0x245F }, // Optical Character Recognition
  18820. { 'begin': 0x2460, 'end': 0x24FF }, // Enclosed Alphanumerics
  18821. { 'begin': 0x2500, 'end': 0x257F }, // Box Drawing
  18822. { 'begin': 0x2580, 'end': 0x259F }, // Block Elements
  18823. { 'begin': 0x25A0, 'end': 0x25FF }, // Geometric Shapes
  18824. { 'begin': 0x2600, 'end': 0x26FF }, // Miscellaneous Symbols
  18825. { 'begin': 0x2700, 'end': 0x27BF }, // Dingbats
  18826. { 'begin': 0x3000, 'end': 0x303F }, // CJK Symbols And Punctuation
  18827. { 'begin': 0x3040, 'end': 0x309F }, // Hiragana
  18828. { 'begin': 0x30A0, 'end': 0x30FF }, // Katakana
  18829. { 'begin': 0x3100, 'end': 0x312F }, // Bopomofo
  18830. { 'begin': 0x3130, 'end': 0x318F }, // Hangul Compatibility Jamo
  18831. { 'begin': 0xA840, 'end': 0xA87F }, // Phags-pa
  18832. { 'begin': 0x3200, 'end': 0x32FF }, // Enclosed CJK Letters And Months
  18833. { 'begin': 0x3300, 'end': 0x33FF }, // CJK Compatibility
  18834. { 'begin': 0xAC00, 'end': 0xD7AF }, // Hangul Syllables
  18835. { 'begin': 0xD800, 'end': 0xDFFF }, // Non-Plane 0 *
  18836. { 'begin': 0x10900, 'end': 0x1091F }, // Phoenicia
  18837. { 'begin': 0x4E00, 'end': 0x9FFF }, // CJK Unified Ideographs
  18838. { 'begin': 0xE000, 'end': 0xF8FF }, // Private Use Area (plane 0)
  18839. { 'begin': 0x31C0, 'end': 0x31EF }, // CJK Strokes
  18840. { 'begin': 0xFB00, 'end': 0xFB4F }, // Alphabetic Presentation Forms
  18841. { 'begin': 0xFB50, 'end': 0xFDFF }, // Arabic Presentation Forms-A
  18842. { 'begin': 0xFE20, 'end': 0xFE2F }, // Combining Half Marks
  18843. { 'begin': 0xFE10, 'end': 0xFE1F }, // Vertical Forms
  18844. { 'begin': 0xFE50, 'end': 0xFE6F }, // Small Form Variants
  18845. { 'begin': 0xFE70, 'end': 0xFEFF }, // Arabic Presentation Forms-B
  18846. { 'begin': 0xFF00, 'end': 0xFFEF }, // Halfwidth And Fullwidth Forms
  18847. { 'begin': 0xFFF0, 'end': 0xFFFF }, // Specials
  18848. { 'begin': 0x0F00, 'end': 0x0FFF }, // Tibetan
  18849. { 'begin': 0x0700, 'end': 0x074F }, // Syriac
  18850. { 'begin': 0x0780, 'end': 0x07BF }, // Thaana
  18851. { 'begin': 0x0D80, 'end': 0x0DFF }, // Sinhala
  18852. { 'begin': 0x1000, 'end': 0x109F }, // Myanmar
  18853. { 'begin': 0x1200, 'end': 0x137F }, // Ethiopic
  18854. { 'begin': 0x13A0, 'end': 0x13FF }, // Cherokee
  18855. { 'begin': 0x1400, 'end': 0x167F }, // Unified Canadian Aboriginal Syllabics
  18856. { 'begin': 0x1680, 'end': 0x169F }, // Ogham
  18857. { 'begin': 0x16A0, 'end': 0x16FF }, // Runic
  18858. { 'begin': 0x1780, 'end': 0x17FF }, // Khmer
  18859. { 'begin': 0x1800, 'end': 0x18AF }, // Mongolian
  18860. { 'begin': 0x2800, 'end': 0x28FF }, // Braille Patterns
  18861. { 'begin': 0xA000, 'end': 0xA48F }, // Yi Syllables
  18862. { 'begin': 0x1700, 'end': 0x171F }, // Tagalog
  18863. { 'begin': 0x10300, 'end': 0x1032F }, // Old Italic
  18864. { 'begin': 0x10330, 'end': 0x1034F }, // Gothic
  18865. { 'begin': 0x10400, 'end': 0x1044F }, // Deseret
  18866. { 'begin': 0x1D000, 'end': 0x1D0FF }, // Byzantine Musical Symbols
  18867. { 'begin': 0x1D400, 'end': 0x1D7FF }, // Mathematical Alphanumeric Symbols
  18868. { 'begin': 0xFF000, 'end': 0xFFFFD }, // Private Use (plane 15)
  18869. { 'begin': 0xFE00, 'end': 0xFE0F }, // Variation Selectors
  18870. { 'begin': 0xE0000, 'end': 0xE007F }, // Tags
  18871. { 'begin': 0x1900, 'end': 0x194F }, // Limbu
  18872. { 'begin': 0x1950, 'end': 0x197F }, // Tai Le
  18873. { 'begin': 0x1980, 'end': 0x19DF }, // New Tai Lue
  18874. { 'begin': 0x1A00, 'end': 0x1A1F }, // Buginese
  18875. { 'begin': 0x2C00, 'end': 0x2C5F }, // Glagolitic
  18876. { 'begin': 0x2D30, 'end': 0x2D7F }, // Tifinagh
  18877. { 'begin': 0x4DC0, 'end': 0x4DFF }, // Yijing Hexagram Symbols
  18878. { 'begin': 0xA800, 'end': 0xA82F }, // Syloti Nagri
  18879. { 'begin': 0x10000, 'end': 0x1007F }, // Linear B Syllabary
  18880. { 'begin': 0x10140, 'end': 0x1018F }, // Ancient Greek Numbers
  18881. { 'begin': 0x10380, 'end': 0x1039F }, // Ugaritic
  18882. { 'begin': 0x103A0, 'end': 0x103DF }, // Old Persian
  18883. { 'begin': 0x10450, 'end': 0x1047F }, // Shavian
  18884. { 'begin': 0x10480, 'end': 0x104AF }, // Osmanya
  18885. { 'begin': 0x10800, 'end': 0x1083F }, // Cypriot Syllabary
  18886. { 'begin': 0x10A00, 'end': 0x10A5F }, // Kharoshthi
  18887. { 'begin': 0x1D300, 'end': 0x1D35F }, // Tai Xuan Jing Symbols
  18888. { 'begin': 0x12000, 'end': 0x123FF }, // Cuneiform
  18889. { 'begin': 0x1D360, 'end': 0x1D37F }, // Counting Rod Numerals
  18890. { 'begin': 0x1B80, 'end': 0x1BBF }, // Sundanese
  18891. { 'begin': 0x1C00, 'end': 0x1C4F }, // Lepcha
  18892. { 'begin': 0x1C50, 'end': 0x1C7F }, // Ol Chiki
  18893. { 'begin': 0xA880, 'end': 0xA8DF }, // Saurashtra
  18894. { 'begin': 0xA900, 'end': 0xA92F }, // Kayah Li
  18895. { 'begin': 0xA930, 'end': 0xA95F }, // Rejang
  18896. { 'begin': 0xAA00, 'end': 0xAA5F }, // Cham
  18897. { 'begin': 0x10190, 'end': 0x101CF }, // Ancient Symbols
  18898. { 'begin': 0x101D0, 'end': 0x101FF }, // Phaistos Disc
  18899. { 'begin': 0x102A0, 'end': 0x102DF }, // Carian
  18900. { 'begin': 0x1F030, 'end': 0x1F09F } // Domino Tiles
  18901. ];
  18902. var MacStandardGlyphOrdering = [
  18903. '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl',
  18904. 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft',
  18905. 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash',
  18906. 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
  18907. 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at',
  18908. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  18909. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft',
  18910. 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b',
  18911. 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
  18912. 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright',
  18913. 'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde',
  18914. 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis',
  18915. 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
  18916. 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve',
  18917. 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex',
  18918. 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet',
  18919. 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute',
  18920. 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal',
  18921. 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi',
  18922. 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash',
  18923. 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin',
  18924. 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis',
  18925. 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash',
  18926. 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright',
  18927. 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency',
  18928. 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered',
  18929. 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex',
  18930. 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex',
  18931. 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute',
  18932. 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron',
  18933. 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron',
  18934. 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar',
  18935. 'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply',
  18936. 'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter',
  18937. 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla',
  18938. 'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
  18939. function getUnicodeRangeFor(value) {
  18940. for (var i = 0, ii = UnicodeRanges.length; i < ii; i++) {
  18941. var range = UnicodeRanges[i];
  18942. if (value >= range.begin && value < range.end) {
  18943. return i;
  18944. }
  18945. }
  18946. return -1;
  18947. }
  18948. function isRTLRangeFor(value) {
  18949. var range = UnicodeRanges[13];
  18950. if (value >= range.begin && value < range.end) {
  18951. return true;
  18952. }
  18953. range = UnicodeRanges[11];
  18954. if (value >= range.begin && value < range.end) {
  18955. return true;
  18956. }
  18957. return false;
  18958. }
  18959. // The normalization table is obtained by filtering the Unicode characters
  18960. // database with <compat> entries.
  18961. var NormalizedUnicodes = {
  18962. '\u00A8': '\u0020\u0308',
  18963. '\u00AF': '\u0020\u0304',
  18964. '\u00B4': '\u0020\u0301',
  18965. '\u00B5': '\u03BC',
  18966. '\u00B8': '\u0020\u0327',
  18967. '\u0132': '\u0049\u004A',
  18968. '\u0133': '\u0069\u006A',
  18969. '\u013F': '\u004C\u00B7',
  18970. '\u0140': '\u006C\u00B7',
  18971. '\u0149': '\u02BC\u006E',
  18972. '\u017F': '\u0073',
  18973. '\u01C4': '\u0044\u017D',
  18974. '\u01C5': '\u0044\u017E',
  18975. '\u01C6': '\u0064\u017E',
  18976. '\u01C7': '\u004C\u004A',
  18977. '\u01C8': '\u004C\u006A',
  18978. '\u01C9': '\u006C\u006A',
  18979. '\u01CA': '\u004E\u004A',
  18980. '\u01CB': '\u004E\u006A',
  18981. '\u01CC': '\u006E\u006A',
  18982. '\u01F1': '\u0044\u005A',
  18983. '\u01F2': '\u0044\u007A',
  18984. '\u01F3': '\u0064\u007A',
  18985. '\u02D8': '\u0020\u0306',
  18986. '\u02D9': '\u0020\u0307',
  18987. '\u02DA': '\u0020\u030A',
  18988. '\u02DB': '\u0020\u0328',
  18989. '\u02DC': '\u0020\u0303',
  18990. '\u02DD': '\u0020\u030B',
  18991. '\u037A': '\u0020\u0345',
  18992. '\u0384': '\u0020\u0301',
  18993. '\u03D0': '\u03B2',
  18994. '\u03D1': '\u03B8',
  18995. '\u03D2': '\u03A5',
  18996. '\u03D5': '\u03C6',
  18997. '\u03D6': '\u03C0',
  18998. '\u03F0': '\u03BA',
  18999. '\u03F1': '\u03C1',
  19000. '\u03F2': '\u03C2',
  19001. '\u03F4': '\u0398',
  19002. '\u03F5': '\u03B5',
  19003. '\u03F9': '\u03A3',
  19004. '\u0587': '\u0565\u0582',
  19005. '\u0675': '\u0627\u0674',
  19006. '\u0676': '\u0648\u0674',
  19007. '\u0677': '\u06C7\u0674',
  19008. '\u0678': '\u064A\u0674',
  19009. '\u0E33': '\u0E4D\u0E32',
  19010. '\u0EB3': '\u0ECD\u0EB2',
  19011. '\u0EDC': '\u0EAB\u0E99',
  19012. '\u0EDD': '\u0EAB\u0EA1',
  19013. '\u0F77': '\u0FB2\u0F81',
  19014. '\u0F79': '\u0FB3\u0F81',
  19015. '\u1E9A': '\u0061\u02BE',
  19016. '\u1FBD': '\u0020\u0313',
  19017. '\u1FBF': '\u0020\u0313',
  19018. '\u1FC0': '\u0020\u0342',
  19019. '\u1FFE': '\u0020\u0314',
  19020. '\u2002': '\u0020',
  19021. '\u2003': '\u0020',
  19022. '\u2004': '\u0020',
  19023. '\u2005': '\u0020',
  19024. '\u2006': '\u0020',
  19025. '\u2008': '\u0020',
  19026. '\u2009': '\u0020',
  19027. '\u200A': '\u0020',
  19028. '\u2017': '\u0020\u0333',
  19029. '\u2024': '\u002E',
  19030. '\u2025': '\u002E\u002E',
  19031. '\u2026': '\u002E\u002E\u002E',
  19032. '\u2033': '\u2032\u2032',
  19033. '\u2034': '\u2032\u2032\u2032',
  19034. '\u2036': '\u2035\u2035',
  19035. '\u2037': '\u2035\u2035\u2035',
  19036. '\u203C': '\u0021\u0021',
  19037. '\u203E': '\u0020\u0305',
  19038. '\u2047': '\u003F\u003F',
  19039. '\u2048': '\u003F\u0021',
  19040. '\u2049': '\u0021\u003F',
  19041. '\u2057': '\u2032\u2032\u2032\u2032',
  19042. '\u205F': '\u0020',
  19043. '\u20A8': '\u0052\u0073',
  19044. '\u2100': '\u0061\u002F\u0063',
  19045. '\u2101': '\u0061\u002F\u0073',
  19046. '\u2103': '\u00B0\u0043',
  19047. '\u2105': '\u0063\u002F\u006F',
  19048. '\u2106': '\u0063\u002F\u0075',
  19049. '\u2107': '\u0190',
  19050. '\u2109': '\u00B0\u0046',
  19051. '\u2116': '\u004E\u006F',
  19052. '\u2121': '\u0054\u0045\u004C',
  19053. '\u2135': '\u05D0',
  19054. '\u2136': '\u05D1',
  19055. '\u2137': '\u05D2',
  19056. '\u2138': '\u05D3',
  19057. '\u213B': '\u0046\u0041\u0058',
  19058. '\u2160': '\u0049',
  19059. '\u2161': '\u0049\u0049',
  19060. '\u2162': '\u0049\u0049\u0049',
  19061. '\u2163': '\u0049\u0056',
  19062. '\u2164': '\u0056',
  19063. '\u2165': '\u0056\u0049',
  19064. '\u2166': '\u0056\u0049\u0049',
  19065. '\u2167': '\u0056\u0049\u0049\u0049',
  19066. '\u2168': '\u0049\u0058',
  19067. '\u2169': '\u0058',
  19068. '\u216A': '\u0058\u0049',
  19069. '\u216B': '\u0058\u0049\u0049',
  19070. '\u216C': '\u004C',
  19071. '\u216D': '\u0043',
  19072. '\u216E': '\u0044',
  19073. '\u216F': '\u004D',
  19074. '\u2170': '\u0069',
  19075. '\u2171': '\u0069\u0069',
  19076. '\u2172': '\u0069\u0069\u0069',
  19077. '\u2173': '\u0069\u0076',
  19078. '\u2174': '\u0076',
  19079. '\u2175': '\u0076\u0069',
  19080. '\u2176': '\u0076\u0069\u0069',
  19081. '\u2177': '\u0076\u0069\u0069\u0069',
  19082. '\u2178': '\u0069\u0078',
  19083. '\u2179': '\u0078',
  19084. '\u217A': '\u0078\u0069',
  19085. '\u217B': '\u0078\u0069\u0069',
  19086. '\u217C': '\u006C',
  19087. '\u217D': '\u0063',
  19088. '\u217E': '\u0064',
  19089. '\u217F': '\u006D',
  19090. '\u222C': '\u222B\u222B',
  19091. '\u222D': '\u222B\u222B\u222B',
  19092. '\u222F': '\u222E\u222E',
  19093. '\u2230': '\u222E\u222E\u222E',
  19094. '\u2474': '\u0028\u0031\u0029',
  19095. '\u2475': '\u0028\u0032\u0029',
  19096. '\u2476': '\u0028\u0033\u0029',
  19097. '\u2477': '\u0028\u0034\u0029',
  19098. '\u2478': '\u0028\u0035\u0029',
  19099. '\u2479': '\u0028\u0036\u0029',
  19100. '\u247A': '\u0028\u0037\u0029',
  19101. '\u247B': '\u0028\u0038\u0029',
  19102. '\u247C': '\u0028\u0039\u0029',
  19103. '\u247D': '\u0028\u0031\u0030\u0029',
  19104. '\u247E': '\u0028\u0031\u0031\u0029',
  19105. '\u247F': '\u0028\u0031\u0032\u0029',
  19106. '\u2480': '\u0028\u0031\u0033\u0029',
  19107. '\u2481': '\u0028\u0031\u0034\u0029',
  19108. '\u2482': '\u0028\u0031\u0035\u0029',
  19109. '\u2483': '\u0028\u0031\u0036\u0029',
  19110. '\u2484': '\u0028\u0031\u0037\u0029',
  19111. '\u2485': '\u0028\u0031\u0038\u0029',
  19112. '\u2486': '\u0028\u0031\u0039\u0029',
  19113. '\u2487': '\u0028\u0032\u0030\u0029',
  19114. '\u2488': '\u0031\u002E',
  19115. '\u2489': '\u0032\u002E',
  19116. '\u248A': '\u0033\u002E',
  19117. '\u248B': '\u0034\u002E',
  19118. '\u248C': '\u0035\u002E',
  19119. '\u248D': '\u0036\u002E',
  19120. '\u248E': '\u0037\u002E',
  19121. '\u248F': '\u0038\u002E',
  19122. '\u2490': '\u0039\u002E',
  19123. '\u2491': '\u0031\u0030\u002E',
  19124. '\u2492': '\u0031\u0031\u002E',
  19125. '\u2493': '\u0031\u0032\u002E',
  19126. '\u2494': '\u0031\u0033\u002E',
  19127. '\u2495': '\u0031\u0034\u002E',
  19128. '\u2496': '\u0031\u0035\u002E',
  19129. '\u2497': '\u0031\u0036\u002E',
  19130. '\u2498': '\u0031\u0037\u002E',
  19131. '\u2499': '\u0031\u0038\u002E',
  19132. '\u249A': '\u0031\u0039\u002E',
  19133. '\u249B': '\u0032\u0030\u002E',
  19134. '\u249C': '\u0028\u0061\u0029',
  19135. '\u249D': '\u0028\u0062\u0029',
  19136. '\u249E': '\u0028\u0063\u0029',
  19137. '\u249F': '\u0028\u0064\u0029',
  19138. '\u24A0': '\u0028\u0065\u0029',
  19139. '\u24A1': '\u0028\u0066\u0029',
  19140. '\u24A2': '\u0028\u0067\u0029',
  19141. '\u24A3': '\u0028\u0068\u0029',
  19142. '\u24A4': '\u0028\u0069\u0029',
  19143. '\u24A5': '\u0028\u006A\u0029',
  19144. '\u24A6': '\u0028\u006B\u0029',
  19145. '\u24A7': '\u0028\u006C\u0029',
  19146. '\u24A8': '\u0028\u006D\u0029',
  19147. '\u24A9': '\u0028\u006E\u0029',
  19148. '\u24AA': '\u0028\u006F\u0029',
  19149. '\u24AB': '\u0028\u0070\u0029',
  19150. '\u24AC': '\u0028\u0071\u0029',
  19151. '\u24AD': '\u0028\u0072\u0029',
  19152. '\u24AE': '\u0028\u0073\u0029',
  19153. '\u24AF': '\u0028\u0074\u0029',
  19154. '\u24B0': '\u0028\u0075\u0029',
  19155. '\u24B1': '\u0028\u0076\u0029',
  19156. '\u24B2': '\u0028\u0077\u0029',
  19157. '\u24B3': '\u0028\u0078\u0029',
  19158. '\u24B4': '\u0028\u0079\u0029',
  19159. '\u24B5': '\u0028\u007A\u0029',
  19160. '\u2A0C': '\u222B\u222B\u222B\u222B',
  19161. '\u2A74': '\u003A\u003A\u003D',
  19162. '\u2A75': '\u003D\u003D',
  19163. '\u2A76': '\u003D\u003D\u003D',
  19164. '\u2E9F': '\u6BCD',
  19165. '\u2EF3': '\u9F9F',
  19166. '\u2F00': '\u4E00',
  19167. '\u2F01': '\u4E28',
  19168. '\u2F02': '\u4E36',
  19169. '\u2F03': '\u4E3F',
  19170. '\u2F04': '\u4E59',
  19171. '\u2F05': '\u4E85',
  19172. '\u2F06': '\u4E8C',
  19173. '\u2F07': '\u4EA0',
  19174. '\u2F08': '\u4EBA',
  19175. '\u2F09': '\u513F',
  19176. '\u2F0A': '\u5165',
  19177. '\u2F0B': '\u516B',
  19178. '\u2F0C': '\u5182',
  19179. '\u2F0D': '\u5196',
  19180. '\u2F0E': '\u51AB',
  19181. '\u2F0F': '\u51E0',
  19182. '\u2F10': '\u51F5',
  19183. '\u2F11': '\u5200',
  19184. '\u2F12': '\u529B',
  19185. '\u2F13': '\u52F9',
  19186. '\u2F14': '\u5315',
  19187. '\u2F15': '\u531A',
  19188. '\u2F16': '\u5338',
  19189. '\u2F17': '\u5341',
  19190. '\u2F18': '\u535C',
  19191. '\u2F19': '\u5369',
  19192. '\u2F1A': '\u5382',
  19193. '\u2F1B': '\u53B6',
  19194. '\u2F1C': '\u53C8',
  19195. '\u2F1D': '\u53E3',
  19196. '\u2F1E': '\u56D7',
  19197. '\u2F1F': '\u571F',
  19198. '\u2F20': '\u58EB',
  19199. '\u2F21': '\u5902',
  19200. '\u2F22': '\u590A',
  19201. '\u2F23': '\u5915',
  19202. '\u2F24': '\u5927',
  19203. '\u2F25': '\u5973',
  19204. '\u2F26': '\u5B50',
  19205. '\u2F27': '\u5B80',
  19206. '\u2F28': '\u5BF8',
  19207. '\u2F29': '\u5C0F',
  19208. '\u2F2A': '\u5C22',
  19209. '\u2F2B': '\u5C38',
  19210. '\u2F2C': '\u5C6E',
  19211. '\u2F2D': '\u5C71',
  19212. '\u2F2E': '\u5DDB',
  19213. '\u2F2F': '\u5DE5',
  19214. '\u2F30': '\u5DF1',
  19215. '\u2F31': '\u5DFE',
  19216. '\u2F32': '\u5E72',
  19217. '\u2F33': '\u5E7A',
  19218. '\u2F34': '\u5E7F',
  19219. '\u2F35': '\u5EF4',
  19220. '\u2F36': '\u5EFE',
  19221. '\u2F37': '\u5F0B',
  19222. '\u2F38': '\u5F13',
  19223. '\u2F39': '\u5F50',
  19224. '\u2F3A': '\u5F61',
  19225. '\u2F3B': '\u5F73',
  19226. '\u2F3C': '\u5FC3',
  19227. '\u2F3D': '\u6208',
  19228. '\u2F3E': '\u6236',
  19229. '\u2F3F': '\u624B',
  19230. '\u2F40': '\u652F',
  19231. '\u2F41': '\u6534',
  19232. '\u2F42': '\u6587',
  19233. '\u2F43': '\u6597',
  19234. '\u2F44': '\u65A4',
  19235. '\u2F45': '\u65B9',
  19236. '\u2F46': '\u65E0',
  19237. '\u2F47': '\u65E5',
  19238. '\u2F48': '\u66F0',
  19239. '\u2F49': '\u6708',
  19240. '\u2F4A': '\u6728',
  19241. '\u2F4B': '\u6B20',
  19242. '\u2F4C': '\u6B62',
  19243. '\u2F4D': '\u6B79',
  19244. '\u2F4E': '\u6BB3',
  19245. '\u2F4F': '\u6BCB',
  19246. '\u2F50': '\u6BD4',
  19247. '\u2F51': '\u6BDB',
  19248. '\u2F52': '\u6C0F',
  19249. '\u2F53': '\u6C14',
  19250. '\u2F54': '\u6C34',
  19251. '\u2F55': '\u706B',
  19252. '\u2F56': '\u722A',
  19253. '\u2F57': '\u7236',
  19254. '\u2F58': '\u723B',
  19255. '\u2F59': '\u723F',
  19256. '\u2F5A': '\u7247',
  19257. '\u2F5B': '\u7259',
  19258. '\u2F5C': '\u725B',
  19259. '\u2F5D': '\u72AC',
  19260. '\u2F5E': '\u7384',
  19261. '\u2F5F': '\u7389',
  19262. '\u2F60': '\u74DC',
  19263. '\u2F61': '\u74E6',
  19264. '\u2F62': '\u7518',
  19265. '\u2F63': '\u751F',
  19266. '\u2F64': '\u7528',
  19267. '\u2F65': '\u7530',
  19268. '\u2F66': '\u758B',
  19269. '\u2F67': '\u7592',
  19270. '\u2F68': '\u7676',
  19271. '\u2F69': '\u767D',
  19272. '\u2F6A': '\u76AE',
  19273. '\u2F6B': '\u76BF',
  19274. '\u2F6C': '\u76EE',
  19275. '\u2F6D': '\u77DB',
  19276. '\u2F6E': '\u77E2',
  19277. '\u2F6F': '\u77F3',
  19278. '\u2F70': '\u793A',
  19279. '\u2F71': '\u79B8',
  19280. '\u2F72': '\u79BE',
  19281. '\u2F73': '\u7A74',
  19282. '\u2F74': '\u7ACB',
  19283. '\u2F75': '\u7AF9',
  19284. '\u2F76': '\u7C73',
  19285. '\u2F77': '\u7CF8',
  19286. '\u2F78': '\u7F36',
  19287. '\u2F79': '\u7F51',
  19288. '\u2F7A': '\u7F8A',
  19289. '\u2F7B': '\u7FBD',
  19290. '\u2F7C': '\u8001',
  19291. '\u2F7D': '\u800C',
  19292. '\u2F7E': '\u8012',
  19293. '\u2F7F': '\u8033',
  19294. '\u2F80': '\u807F',
  19295. '\u2F81': '\u8089',
  19296. '\u2F82': '\u81E3',
  19297. '\u2F83': '\u81EA',
  19298. '\u2F84': '\u81F3',
  19299. '\u2F85': '\u81FC',
  19300. '\u2F86': '\u820C',
  19301. '\u2F87': '\u821B',
  19302. '\u2F88': '\u821F',
  19303. '\u2F89': '\u826E',
  19304. '\u2F8A': '\u8272',
  19305. '\u2F8B': '\u8278',
  19306. '\u2F8C': '\u864D',
  19307. '\u2F8D': '\u866B',
  19308. '\u2F8E': '\u8840',
  19309. '\u2F8F': '\u884C',
  19310. '\u2F90': '\u8863',
  19311. '\u2F91': '\u897E',
  19312. '\u2F92': '\u898B',
  19313. '\u2F93': '\u89D2',
  19314. '\u2F94': '\u8A00',
  19315. '\u2F95': '\u8C37',
  19316. '\u2F96': '\u8C46',
  19317. '\u2F97': '\u8C55',
  19318. '\u2F98': '\u8C78',
  19319. '\u2F99': '\u8C9D',
  19320. '\u2F9A': '\u8D64',
  19321. '\u2F9B': '\u8D70',
  19322. '\u2F9C': '\u8DB3',
  19323. '\u2F9D': '\u8EAB',
  19324. '\u2F9E': '\u8ECA',
  19325. '\u2F9F': '\u8F9B',
  19326. '\u2FA0': '\u8FB0',
  19327. '\u2FA1': '\u8FB5',
  19328. '\u2FA2': '\u9091',
  19329. '\u2FA3': '\u9149',
  19330. '\u2FA4': '\u91C6',
  19331. '\u2FA5': '\u91CC',
  19332. '\u2FA6': '\u91D1',
  19333. '\u2FA7': '\u9577',
  19334. '\u2FA8': '\u9580',
  19335. '\u2FA9': '\u961C',
  19336. '\u2FAA': '\u96B6',
  19337. '\u2FAB': '\u96B9',
  19338. '\u2FAC': '\u96E8',
  19339. '\u2FAD': '\u9751',
  19340. '\u2FAE': '\u975E',
  19341. '\u2FAF': '\u9762',
  19342. '\u2FB0': '\u9769',
  19343. '\u2FB1': '\u97CB',
  19344. '\u2FB2': '\u97ED',
  19345. '\u2FB3': '\u97F3',
  19346. '\u2FB4': '\u9801',
  19347. '\u2FB5': '\u98A8',
  19348. '\u2FB6': '\u98DB',
  19349. '\u2FB7': '\u98DF',
  19350. '\u2FB8': '\u9996',
  19351. '\u2FB9': '\u9999',
  19352. '\u2FBA': '\u99AC',
  19353. '\u2FBB': '\u9AA8',
  19354. '\u2FBC': '\u9AD8',
  19355. '\u2FBD': '\u9ADF',
  19356. '\u2FBE': '\u9B25',
  19357. '\u2FBF': '\u9B2F',
  19358. '\u2FC0': '\u9B32',
  19359. '\u2FC1': '\u9B3C',
  19360. '\u2FC2': '\u9B5A',
  19361. '\u2FC3': '\u9CE5',
  19362. '\u2FC4': '\u9E75',
  19363. '\u2FC5': '\u9E7F',
  19364. '\u2FC6': '\u9EA5',
  19365. '\u2FC7': '\u9EBB',
  19366. '\u2FC8': '\u9EC3',
  19367. '\u2FC9': '\u9ECD',
  19368. '\u2FCA': '\u9ED1',
  19369. '\u2FCB': '\u9EF9',
  19370. '\u2FCC': '\u9EFD',
  19371. '\u2FCD': '\u9F0E',
  19372. '\u2FCE': '\u9F13',
  19373. '\u2FCF': '\u9F20',
  19374. '\u2FD0': '\u9F3B',
  19375. '\u2FD1': '\u9F4A',
  19376. '\u2FD2': '\u9F52',
  19377. '\u2FD3': '\u9F8D',
  19378. '\u2FD4': '\u9F9C',
  19379. '\u2FD5': '\u9FA0',
  19380. '\u3036': '\u3012',
  19381. '\u3038': '\u5341',
  19382. '\u3039': '\u5344',
  19383. '\u303A': '\u5345',
  19384. '\u309B': '\u0020\u3099',
  19385. '\u309C': '\u0020\u309A',
  19386. '\u3131': '\u1100',
  19387. '\u3132': '\u1101',
  19388. '\u3133': '\u11AA',
  19389. '\u3134': '\u1102',
  19390. '\u3135': '\u11AC',
  19391. '\u3136': '\u11AD',
  19392. '\u3137': '\u1103',
  19393. '\u3138': '\u1104',
  19394. '\u3139': '\u1105',
  19395. '\u313A': '\u11B0',
  19396. '\u313B': '\u11B1',
  19397. '\u313C': '\u11B2',
  19398. '\u313D': '\u11B3',
  19399. '\u313E': '\u11B4',
  19400. '\u313F': '\u11B5',
  19401. '\u3140': '\u111A',
  19402. '\u3141': '\u1106',
  19403. '\u3142': '\u1107',
  19404. '\u3143': '\u1108',
  19405. '\u3144': '\u1121',
  19406. '\u3145': '\u1109',
  19407. '\u3146': '\u110A',
  19408. '\u3147': '\u110B',
  19409. '\u3148': '\u110C',
  19410. '\u3149': '\u110D',
  19411. '\u314A': '\u110E',
  19412. '\u314B': '\u110F',
  19413. '\u314C': '\u1110',
  19414. '\u314D': '\u1111',
  19415. '\u314E': '\u1112',
  19416. '\u314F': '\u1161',
  19417. '\u3150': '\u1162',
  19418. '\u3151': '\u1163',
  19419. '\u3152': '\u1164',
  19420. '\u3153': '\u1165',
  19421. '\u3154': '\u1166',
  19422. '\u3155': '\u1167',
  19423. '\u3156': '\u1168',
  19424. '\u3157': '\u1169',
  19425. '\u3158': '\u116A',
  19426. '\u3159': '\u116B',
  19427. '\u315A': '\u116C',
  19428. '\u315B': '\u116D',
  19429. '\u315C': '\u116E',
  19430. '\u315D': '\u116F',
  19431. '\u315E': '\u1170',
  19432. '\u315F': '\u1171',
  19433. '\u3160': '\u1172',
  19434. '\u3161': '\u1173',
  19435. '\u3162': '\u1174',
  19436. '\u3163': '\u1175',
  19437. '\u3164': '\u1160',
  19438. '\u3165': '\u1114',
  19439. '\u3166': '\u1115',
  19440. '\u3167': '\u11C7',
  19441. '\u3168': '\u11C8',
  19442. '\u3169': '\u11CC',
  19443. '\u316A': '\u11CE',
  19444. '\u316B': '\u11D3',
  19445. '\u316C': '\u11D7',
  19446. '\u316D': '\u11D9',
  19447. '\u316E': '\u111C',
  19448. '\u316F': '\u11DD',
  19449. '\u3170': '\u11DF',
  19450. '\u3171': '\u111D',
  19451. '\u3172': '\u111E',
  19452. '\u3173': '\u1120',
  19453. '\u3174': '\u1122',
  19454. '\u3175': '\u1123',
  19455. '\u3176': '\u1127',
  19456. '\u3177': '\u1129',
  19457. '\u3178': '\u112B',
  19458. '\u3179': '\u112C',
  19459. '\u317A': '\u112D',
  19460. '\u317B': '\u112E',
  19461. '\u317C': '\u112F',
  19462. '\u317D': '\u1132',
  19463. '\u317E': '\u1136',
  19464. '\u317F': '\u1140',
  19465. '\u3180': '\u1147',
  19466. '\u3181': '\u114C',
  19467. '\u3182': '\u11F1',
  19468. '\u3183': '\u11F2',
  19469. '\u3184': '\u1157',
  19470. '\u3185': '\u1158',
  19471. '\u3186': '\u1159',
  19472. '\u3187': '\u1184',
  19473. '\u3188': '\u1185',
  19474. '\u3189': '\u1188',
  19475. '\u318A': '\u1191',
  19476. '\u318B': '\u1192',
  19477. '\u318C': '\u1194',
  19478. '\u318D': '\u119E',
  19479. '\u318E': '\u11A1',
  19480. '\u3200': '\u0028\u1100\u0029',
  19481. '\u3201': '\u0028\u1102\u0029',
  19482. '\u3202': '\u0028\u1103\u0029',
  19483. '\u3203': '\u0028\u1105\u0029',
  19484. '\u3204': '\u0028\u1106\u0029',
  19485. '\u3205': '\u0028\u1107\u0029',
  19486. '\u3206': '\u0028\u1109\u0029',
  19487. '\u3207': '\u0028\u110B\u0029',
  19488. '\u3208': '\u0028\u110C\u0029',
  19489. '\u3209': '\u0028\u110E\u0029',
  19490. '\u320A': '\u0028\u110F\u0029',
  19491. '\u320B': '\u0028\u1110\u0029',
  19492. '\u320C': '\u0028\u1111\u0029',
  19493. '\u320D': '\u0028\u1112\u0029',
  19494. '\u320E': '\u0028\u1100\u1161\u0029',
  19495. '\u320F': '\u0028\u1102\u1161\u0029',
  19496. '\u3210': '\u0028\u1103\u1161\u0029',
  19497. '\u3211': '\u0028\u1105\u1161\u0029',
  19498. '\u3212': '\u0028\u1106\u1161\u0029',
  19499. '\u3213': '\u0028\u1107\u1161\u0029',
  19500. '\u3214': '\u0028\u1109\u1161\u0029',
  19501. '\u3215': '\u0028\u110B\u1161\u0029',
  19502. '\u3216': '\u0028\u110C\u1161\u0029',
  19503. '\u3217': '\u0028\u110E\u1161\u0029',
  19504. '\u3218': '\u0028\u110F\u1161\u0029',
  19505. '\u3219': '\u0028\u1110\u1161\u0029',
  19506. '\u321A': '\u0028\u1111\u1161\u0029',
  19507. '\u321B': '\u0028\u1112\u1161\u0029',
  19508. '\u321C': '\u0028\u110C\u116E\u0029',
  19509. '\u321D': '\u0028\u110B\u1169\u110C\u1165\u11AB\u0029',
  19510. '\u321E': '\u0028\u110B\u1169\u1112\u116E\u0029',
  19511. '\u3220': '\u0028\u4E00\u0029',
  19512. '\u3221': '\u0028\u4E8C\u0029',
  19513. '\u3222': '\u0028\u4E09\u0029',
  19514. '\u3223': '\u0028\u56DB\u0029',
  19515. '\u3224': '\u0028\u4E94\u0029',
  19516. '\u3225': '\u0028\u516D\u0029',
  19517. '\u3226': '\u0028\u4E03\u0029',
  19518. '\u3227': '\u0028\u516B\u0029',
  19519. '\u3228': '\u0028\u4E5D\u0029',
  19520. '\u3229': '\u0028\u5341\u0029',
  19521. '\u322A': '\u0028\u6708\u0029',
  19522. '\u322B': '\u0028\u706B\u0029',
  19523. '\u322C': '\u0028\u6C34\u0029',
  19524. '\u322D': '\u0028\u6728\u0029',
  19525. '\u322E': '\u0028\u91D1\u0029',
  19526. '\u322F': '\u0028\u571F\u0029',
  19527. '\u3230': '\u0028\u65E5\u0029',
  19528. '\u3231': '\u0028\u682A\u0029',
  19529. '\u3232': '\u0028\u6709\u0029',
  19530. '\u3233': '\u0028\u793E\u0029',
  19531. '\u3234': '\u0028\u540D\u0029',
  19532. '\u3235': '\u0028\u7279\u0029',
  19533. '\u3236': '\u0028\u8CA1\u0029',
  19534. '\u3237': '\u0028\u795D\u0029',
  19535. '\u3238': '\u0028\u52B4\u0029',
  19536. '\u3239': '\u0028\u4EE3\u0029',
  19537. '\u323A': '\u0028\u547C\u0029',
  19538. '\u323B': '\u0028\u5B66\u0029',
  19539. '\u323C': '\u0028\u76E3\u0029',
  19540. '\u323D': '\u0028\u4F01\u0029',
  19541. '\u323E': '\u0028\u8CC7\u0029',
  19542. '\u323F': '\u0028\u5354\u0029',
  19543. '\u3240': '\u0028\u796D\u0029',
  19544. '\u3241': '\u0028\u4F11\u0029',
  19545. '\u3242': '\u0028\u81EA\u0029',
  19546. '\u3243': '\u0028\u81F3\u0029',
  19547. '\u32C0': '\u0031\u6708',
  19548. '\u32C1': '\u0032\u6708',
  19549. '\u32C2': '\u0033\u6708',
  19550. '\u32C3': '\u0034\u6708',
  19551. '\u32C4': '\u0035\u6708',
  19552. '\u32C5': '\u0036\u6708',
  19553. '\u32C6': '\u0037\u6708',
  19554. '\u32C7': '\u0038\u6708',
  19555. '\u32C8': '\u0039\u6708',
  19556. '\u32C9': '\u0031\u0030\u6708',
  19557. '\u32CA': '\u0031\u0031\u6708',
  19558. '\u32CB': '\u0031\u0032\u6708',
  19559. '\u3358': '\u0030\u70B9',
  19560. '\u3359': '\u0031\u70B9',
  19561. '\u335A': '\u0032\u70B9',
  19562. '\u335B': '\u0033\u70B9',
  19563. '\u335C': '\u0034\u70B9',
  19564. '\u335D': '\u0035\u70B9',
  19565. '\u335E': '\u0036\u70B9',
  19566. '\u335F': '\u0037\u70B9',
  19567. '\u3360': '\u0038\u70B9',
  19568. '\u3361': '\u0039\u70B9',
  19569. '\u3362': '\u0031\u0030\u70B9',
  19570. '\u3363': '\u0031\u0031\u70B9',
  19571. '\u3364': '\u0031\u0032\u70B9',
  19572. '\u3365': '\u0031\u0033\u70B9',
  19573. '\u3366': '\u0031\u0034\u70B9',
  19574. '\u3367': '\u0031\u0035\u70B9',
  19575. '\u3368': '\u0031\u0036\u70B9',
  19576. '\u3369': '\u0031\u0037\u70B9',
  19577. '\u336A': '\u0031\u0038\u70B9',
  19578. '\u336B': '\u0031\u0039\u70B9',
  19579. '\u336C': '\u0032\u0030\u70B9',
  19580. '\u336D': '\u0032\u0031\u70B9',
  19581. '\u336E': '\u0032\u0032\u70B9',
  19582. '\u336F': '\u0032\u0033\u70B9',
  19583. '\u3370': '\u0032\u0034\u70B9',
  19584. '\u33E0': '\u0031\u65E5',
  19585. '\u33E1': '\u0032\u65E5',
  19586. '\u33E2': '\u0033\u65E5',
  19587. '\u33E3': '\u0034\u65E5',
  19588. '\u33E4': '\u0035\u65E5',
  19589. '\u33E5': '\u0036\u65E5',
  19590. '\u33E6': '\u0037\u65E5',
  19591. '\u33E7': '\u0038\u65E5',
  19592. '\u33E8': '\u0039\u65E5',
  19593. '\u33E9': '\u0031\u0030\u65E5',
  19594. '\u33EA': '\u0031\u0031\u65E5',
  19595. '\u33EB': '\u0031\u0032\u65E5',
  19596. '\u33EC': '\u0031\u0033\u65E5',
  19597. '\u33ED': '\u0031\u0034\u65E5',
  19598. '\u33EE': '\u0031\u0035\u65E5',
  19599. '\u33EF': '\u0031\u0036\u65E5',
  19600. '\u33F0': '\u0031\u0037\u65E5',
  19601. '\u33F1': '\u0031\u0038\u65E5',
  19602. '\u33F2': '\u0031\u0039\u65E5',
  19603. '\u33F3': '\u0032\u0030\u65E5',
  19604. '\u33F4': '\u0032\u0031\u65E5',
  19605. '\u33F5': '\u0032\u0032\u65E5',
  19606. '\u33F6': '\u0032\u0033\u65E5',
  19607. '\u33F7': '\u0032\u0034\u65E5',
  19608. '\u33F8': '\u0032\u0035\u65E5',
  19609. '\u33F9': '\u0032\u0036\u65E5',
  19610. '\u33FA': '\u0032\u0037\u65E5',
  19611. '\u33FB': '\u0032\u0038\u65E5',
  19612. '\u33FC': '\u0032\u0039\u65E5',
  19613. '\u33FD': '\u0033\u0030\u65E5',
  19614. '\u33FE': '\u0033\u0031\u65E5',
  19615. '\uFB00': '\u0066\u0066',
  19616. '\uFB01': '\u0066\u0069',
  19617. '\uFB02': '\u0066\u006C',
  19618. '\uFB03': '\u0066\u0066\u0069',
  19619. '\uFB04': '\u0066\u0066\u006C',
  19620. '\uFB05': '\u017F\u0074',
  19621. '\uFB06': '\u0073\u0074',
  19622. '\uFB13': '\u0574\u0576',
  19623. '\uFB14': '\u0574\u0565',
  19624. '\uFB15': '\u0574\u056B',
  19625. '\uFB16': '\u057E\u0576',
  19626. '\uFB17': '\u0574\u056D',
  19627. '\uFB4F': '\u05D0\u05DC',
  19628. '\uFB50': '\u0671',
  19629. '\uFB51': '\u0671',
  19630. '\uFB52': '\u067B',
  19631. '\uFB53': '\u067B',
  19632. '\uFB54': '\u067B',
  19633. '\uFB55': '\u067B',
  19634. '\uFB56': '\u067E',
  19635. '\uFB57': '\u067E',
  19636. '\uFB58': '\u067E',
  19637. '\uFB59': '\u067E',
  19638. '\uFB5A': '\u0680',
  19639. '\uFB5B': '\u0680',
  19640. '\uFB5C': '\u0680',
  19641. '\uFB5D': '\u0680',
  19642. '\uFB5E': '\u067A',
  19643. '\uFB5F': '\u067A',
  19644. '\uFB60': '\u067A',
  19645. '\uFB61': '\u067A',
  19646. '\uFB62': '\u067F',
  19647. '\uFB63': '\u067F',
  19648. '\uFB64': '\u067F',
  19649. '\uFB65': '\u067F',
  19650. '\uFB66': '\u0679',
  19651. '\uFB67': '\u0679',
  19652. '\uFB68': '\u0679',
  19653. '\uFB69': '\u0679',
  19654. '\uFB6A': '\u06A4',
  19655. '\uFB6B': '\u06A4',
  19656. '\uFB6C': '\u06A4',
  19657. '\uFB6D': '\u06A4',
  19658. '\uFB6E': '\u06A6',
  19659. '\uFB6F': '\u06A6',
  19660. '\uFB70': '\u06A6',
  19661. '\uFB71': '\u06A6',
  19662. '\uFB72': '\u0684',
  19663. '\uFB73': '\u0684',
  19664. '\uFB74': '\u0684',
  19665. '\uFB75': '\u0684',
  19666. '\uFB76': '\u0683',
  19667. '\uFB77': '\u0683',
  19668. '\uFB78': '\u0683',
  19669. '\uFB79': '\u0683',
  19670. '\uFB7A': '\u0686',
  19671. '\uFB7B': '\u0686',
  19672. '\uFB7C': '\u0686',
  19673. '\uFB7D': '\u0686',
  19674. '\uFB7E': '\u0687',
  19675. '\uFB7F': '\u0687',
  19676. '\uFB80': '\u0687',
  19677. '\uFB81': '\u0687',
  19678. '\uFB82': '\u068D',
  19679. '\uFB83': '\u068D',
  19680. '\uFB84': '\u068C',
  19681. '\uFB85': '\u068C',
  19682. '\uFB86': '\u068E',
  19683. '\uFB87': '\u068E',
  19684. '\uFB88': '\u0688',
  19685. '\uFB89': '\u0688',
  19686. '\uFB8A': '\u0698',
  19687. '\uFB8B': '\u0698',
  19688. '\uFB8C': '\u0691',
  19689. '\uFB8D': '\u0691',
  19690. '\uFB8E': '\u06A9',
  19691. '\uFB8F': '\u06A9',
  19692. '\uFB90': '\u06A9',
  19693. '\uFB91': '\u06A9',
  19694. '\uFB92': '\u06AF',
  19695. '\uFB93': '\u06AF',
  19696. '\uFB94': '\u06AF',
  19697. '\uFB95': '\u06AF',
  19698. '\uFB96': '\u06B3',
  19699. '\uFB97': '\u06B3',
  19700. '\uFB98': '\u06B3',
  19701. '\uFB99': '\u06B3',
  19702. '\uFB9A': '\u06B1',
  19703. '\uFB9B': '\u06B1',
  19704. '\uFB9C': '\u06B1',
  19705. '\uFB9D': '\u06B1',
  19706. '\uFB9E': '\u06BA',
  19707. '\uFB9F': '\u06BA',
  19708. '\uFBA0': '\u06BB',
  19709. '\uFBA1': '\u06BB',
  19710. '\uFBA2': '\u06BB',
  19711. '\uFBA3': '\u06BB',
  19712. '\uFBA4': '\u06C0',
  19713. '\uFBA5': '\u06C0',
  19714. '\uFBA6': '\u06C1',
  19715. '\uFBA7': '\u06C1',
  19716. '\uFBA8': '\u06C1',
  19717. '\uFBA9': '\u06C1',
  19718. '\uFBAA': '\u06BE',
  19719. '\uFBAB': '\u06BE',
  19720. '\uFBAC': '\u06BE',
  19721. '\uFBAD': '\u06BE',
  19722. '\uFBAE': '\u06D2',
  19723. '\uFBAF': '\u06D2',
  19724. '\uFBB0': '\u06D3',
  19725. '\uFBB1': '\u06D3',
  19726. '\uFBD3': '\u06AD',
  19727. '\uFBD4': '\u06AD',
  19728. '\uFBD5': '\u06AD',
  19729. '\uFBD6': '\u06AD',
  19730. '\uFBD7': '\u06C7',
  19731. '\uFBD8': '\u06C7',
  19732. '\uFBD9': '\u06C6',
  19733. '\uFBDA': '\u06C6',
  19734. '\uFBDB': '\u06C8',
  19735. '\uFBDC': '\u06C8',
  19736. '\uFBDD': '\u0677',
  19737. '\uFBDE': '\u06CB',
  19738. '\uFBDF': '\u06CB',
  19739. '\uFBE0': '\u06C5',
  19740. '\uFBE1': '\u06C5',
  19741. '\uFBE2': '\u06C9',
  19742. '\uFBE3': '\u06C9',
  19743. '\uFBE4': '\u06D0',
  19744. '\uFBE5': '\u06D0',
  19745. '\uFBE6': '\u06D0',
  19746. '\uFBE7': '\u06D0',
  19747. '\uFBE8': '\u0649',
  19748. '\uFBE9': '\u0649',
  19749. '\uFBEA': '\u0626\u0627',
  19750. '\uFBEB': '\u0626\u0627',
  19751. '\uFBEC': '\u0626\u06D5',
  19752. '\uFBED': '\u0626\u06D5',
  19753. '\uFBEE': '\u0626\u0648',
  19754. '\uFBEF': '\u0626\u0648',
  19755. '\uFBF0': '\u0626\u06C7',
  19756. '\uFBF1': '\u0626\u06C7',
  19757. '\uFBF2': '\u0626\u06C6',
  19758. '\uFBF3': '\u0626\u06C6',
  19759. '\uFBF4': '\u0626\u06C8',
  19760. '\uFBF5': '\u0626\u06C8',
  19761. '\uFBF6': '\u0626\u06D0',
  19762. '\uFBF7': '\u0626\u06D0',
  19763. '\uFBF8': '\u0626\u06D0',
  19764. '\uFBF9': '\u0626\u0649',
  19765. '\uFBFA': '\u0626\u0649',
  19766. '\uFBFB': '\u0626\u0649',
  19767. '\uFBFC': '\u06CC',
  19768. '\uFBFD': '\u06CC',
  19769. '\uFBFE': '\u06CC',
  19770. '\uFBFF': '\u06CC',
  19771. '\uFC00': '\u0626\u062C',
  19772. '\uFC01': '\u0626\u062D',
  19773. '\uFC02': '\u0626\u0645',
  19774. '\uFC03': '\u0626\u0649',
  19775. '\uFC04': '\u0626\u064A',
  19776. '\uFC05': '\u0628\u062C',
  19777. '\uFC06': '\u0628\u062D',
  19778. '\uFC07': '\u0628\u062E',
  19779. '\uFC08': '\u0628\u0645',
  19780. '\uFC09': '\u0628\u0649',
  19781. '\uFC0A': '\u0628\u064A',
  19782. '\uFC0B': '\u062A\u062C',
  19783. '\uFC0C': '\u062A\u062D',
  19784. '\uFC0D': '\u062A\u062E',
  19785. '\uFC0E': '\u062A\u0645',
  19786. '\uFC0F': '\u062A\u0649',
  19787. '\uFC10': '\u062A\u064A',
  19788. '\uFC11': '\u062B\u062C',
  19789. '\uFC12': '\u062B\u0645',
  19790. '\uFC13': '\u062B\u0649',
  19791. '\uFC14': '\u062B\u064A',
  19792. '\uFC15': '\u062C\u062D',
  19793. '\uFC16': '\u062C\u0645',
  19794. '\uFC17': '\u062D\u062C',
  19795. '\uFC18': '\u062D\u0645',
  19796. '\uFC19': '\u062E\u062C',
  19797. '\uFC1A': '\u062E\u062D',
  19798. '\uFC1B': '\u062E\u0645',
  19799. '\uFC1C': '\u0633\u062C',
  19800. '\uFC1D': '\u0633\u062D',
  19801. '\uFC1E': '\u0633\u062E',
  19802. '\uFC1F': '\u0633\u0645',
  19803. '\uFC20': '\u0635\u062D',
  19804. '\uFC21': '\u0635\u0645',
  19805. '\uFC22': '\u0636\u062C',
  19806. '\uFC23': '\u0636\u062D',
  19807. '\uFC24': '\u0636\u062E',
  19808. '\uFC25': '\u0636\u0645',
  19809. '\uFC26': '\u0637\u062D',
  19810. '\uFC27': '\u0637\u0645',
  19811. '\uFC28': '\u0638\u0645',
  19812. '\uFC29': '\u0639\u062C',
  19813. '\uFC2A': '\u0639\u0645',
  19814. '\uFC2B': '\u063A\u062C',
  19815. '\uFC2C': '\u063A\u0645',
  19816. '\uFC2D': '\u0641\u062C',
  19817. '\uFC2E': '\u0641\u062D',
  19818. '\uFC2F': '\u0641\u062E',
  19819. '\uFC30': '\u0641\u0645',
  19820. '\uFC31': '\u0641\u0649',
  19821. '\uFC32': '\u0641\u064A',
  19822. '\uFC33': '\u0642\u062D',
  19823. '\uFC34': '\u0642\u0645',
  19824. '\uFC35': '\u0642\u0649',
  19825. '\uFC36': '\u0642\u064A',
  19826. '\uFC37': '\u0643\u0627',
  19827. '\uFC38': '\u0643\u062C',
  19828. '\uFC39': '\u0643\u062D',
  19829. '\uFC3A': '\u0643\u062E',
  19830. '\uFC3B': '\u0643\u0644',
  19831. '\uFC3C': '\u0643\u0645',
  19832. '\uFC3D': '\u0643\u0649',
  19833. '\uFC3E': '\u0643\u064A',
  19834. '\uFC3F': '\u0644\u062C',
  19835. '\uFC40': '\u0644\u062D',
  19836. '\uFC41': '\u0644\u062E',
  19837. '\uFC42': '\u0644\u0645',
  19838. '\uFC43': '\u0644\u0649',
  19839. '\uFC44': '\u0644\u064A',
  19840. '\uFC45': '\u0645\u062C',
  19841. '\uFC46': '\u0645\u062D',
  19842. '\uFC47': '\u0645\u062E',
  19843. '\uFC48': '\u0645\u0645',
  19844. '\uFC49': '\u0645\u0649',
  19845. '\uFC4A': '\u0645\u064A',
  19846. '\uFC4B': '\u0646\u062C',
  19847. '\uFC4C': '\u0646\u062D',
  19848. '\uFC4D': '\u0646\u062E',
  19849. '\uFC4E': '\u0646\u0645',
  19850. '\uFC4F': '\u0646\u0649',
  19851. '\uFC50': '\u0646\u064A',
  19852. '\uFC51': '\u0647\u062C',
  19853. '\uFC52': '\u0647\u0645',
  19854. '\uFC53': '\u0647\u0649',
  19855. '\uFC54': '\u0647\u064A',
  19856. '\uFC55': '\u064A\u062C',
  19857. '\uFC56': '\u064A\u062D',
  19858. '\uFC57': '\u064A\u062E',
  19859. '\uFC58': '\u064A\u0645',
  19860. '\uFC59': '\u064A\u0649',
  19861. '\uFC5A': '\u064A\u064A',
  19862. '\uFC5B': '\u0630\u0670',
  19863. '\uFC5C': '\u0631\u0670',
  19864. '\uFC5D': '\u0649\u0670',
  19865. '\uFC5E': '\u0020\u064C\u0651',
  19866. '\uFC5F': '\u0020\u064D\u0651',
  19867. '\uFC60': '\u0020\u064E\u0651',
  19868. '\uFC61': '\u0020\u064F\u0651',
  19869. '\uFC62': '\u0020\u0650\u0651',
  19870. '\uFC63': '\u0020\u0651\u0670',
  19871. '\uFC64': '\u0626\u0631',
  19872. '\uFC65': '\u0626\u0632',
  19873. '\uFC66': '\u0626\u0645',
  19874. '\uFC67': '\u0626\u0646',
  19875. '\uFC68': '\u0626\u0649',
  19876. '\uFC69': '\u0626\u064A',
  19877. '\uFC6A': '\u0628\u0631',
  19878. '\uFC6B': '\u0628\u0632',
  19879. '\uFC6C': '\u0628\u0645',
  19880. '\uFC6D': '\u0628\u0646',
  19881. '\uFC6E': '\u0628\u0649',
  19882. '\uFC6F': '\u0628\u064A',
  19883. '\uFC70': '\u062A\u0631',
  19884. '\uFC71': '\u062A\u0632',
  19885. '\uFC72': '\u062A\u0645',
  19886. '\uFC73': '\u062A\u0646',
  19887. '\uFC74': '\u062A\u0649',
  19888. '\uFC75': '\u062A\u064A',
  19889. '\uFC76': '\u062B\u0631',
  19890. '\uFC77': '\u062B\u0632',
  19891. '\uFC78': '\u062B\u0645',
  19892. '\uFC79': '\u062B\u0646',
  19893. '\uFC7A': '\u062B\u0649',
  19894. '\uFC7B': '\u062B\u064A',
  19895. '\uFC7C': '\u0641\u0649',
  19896. '\uFC7D': '\u0641\u064A',
  19897. '\uFC7E': '\u0642\u0649',
  19898. '\uFC7F': '\u0642\u064A',
  19899. '\uFC80': '\u0643\u0627',
  19900. '\uFC81': '\u0643\u0644',
  19901. '\uFC82': '\u0643\u0645',
  19902. '\uFC83': '\u0643\u0649',
  19903. '\uFC84': '\u0643\u064A',
  19904. '\uFC85': '\u0644\u0645',
  19905. '\uFC86': '\u0644\u0649',
  19906. '\uFC87': '\u0644\u064A',
  19907. '\uFC88': '\u0645\u0627',
  19908. '\uFC89': '\u0645\u0645',
  19909. '\uFC8A': '\u0646\u0631',
  19910. '\uFC8B': '\u0646\u0632',
  19911. '\uFC8C': '\u0646\u0645',
  19912. '\uFC8D': '\u0646\u0646',
  19913. '\uFC8E': '\u0646\u0649',
  19914. '\uFC8F': '\u0646\u064A',
  19915. '\uFC90': '\u0649\u0670',
  19916. '\uFC91': '\u064A\u0631',
  19917. '\uFC92': '\u064A\u0632',
  19918. '\uFC93': '\u064A\u0645',
  19919. '\uFC94': '\u064A\u0646',
  19920. '\uFC95': '\u064A\u0649',
  19921. '\uFC96': '\u064A\u064A',
  19922. '\uFC97': '\u0626\u062C',
  19923. '\uFC98': '\u0626\u062D',
  19924. '\uFC99': '\u0626\u062E',
  19925. '\uFC9A': '\u0626\u0645',
  19926. '\uFC9B': '\u0626\u0647',
  19927. '\uFC9C': '\u0628\u062C',
  19928. '\uFC9D': '\u0628\u062D',
  19929. '\uFC9E': '\u0628\u062E',
  19930. '\uFC9F': '\u0628\u0645',
  19931. '\uFCA0': '\u0628\u0647',
  19932. '\uFCA1': '\u062A\u062C',
  19933. '\uFCA2': '\u062A\u062D',
  19934. '\uFCA3': '\u062A\u062E',
  19935. '\uFCA4': '\u062A\u0645',
  19936. '\uFCA5': '\u062A\u0647',
  19937. '\uFCA6': '\u062B\u0645',
  19938. '\uFCA7': '\u062C\u062D',
  19939. '\uFCA8': '\u062C\u0645',
  19940. '\uFCA9': '\u062D\u062C',
  19941. '\uFCAA': '\u062D\u0645',
  19942. '\uFCAB': '\u062E\u062C',
  19943. '\uFCAC': '\u062E\u0645',
  19944. '\uFCAD': '\u0633\u062C',
  19945. '\uFCAE': '\u0633\u062D',
  19946. '\uFCAF': '\u0633\u062E',
  19947. '\uFCB0': '\u0633\u0645',
  19948. '\uFCB1': '\u0635\u062D',
  19949. '\uFCB2': '\u0635\u062E',
  19950. '\uFCB3': '\u0635\u0645',
  19951. '\uFCB4': '\u0636\u062C',
  19952. '\uFCB5': '\u0636\u062D',
  19953. '\uFCB6': '\u0636\u062E',
  19954. '\uFCB7': '\u0636\u0645',
  19955. '\uFCB8': '\u0637\u062D',
  19956. '\uFCB9': '\u0638\u0645',
  19957. '\uFCBA': '\u0639\u062C',
  19958. '\uFCBB': '\u0639\u0645',
  19959. '\uFCBC': '\u063A\u062C',
  19960. '\uFCBD': '\u063A\u0645',
  19961. '\uFCBE': '\u0641\u062C',
  19962. '\uFCBF': '\u0641\u062D',
  19963. '\uFCC0': '\u0641\u062E',
  19964. '\uFCC1': '\u0641\u0645',
  19965. '\uFCC2': '\u0642\u062D',
  19966. '\uFCC3': '\u0642\u0645',
  19967. '\uFCC4': '\u0643\u062C',
  19968. '\uFCC5': '\u0643\u062D',
  19969. '\uFCC6': '\u0643\u062E',
  19970. '\uFCC7': '\u0643\u0644',
  19971. '\uFCC8': '\u0643\u0645',
  19972. '\uFCC9': '\u0644\u062C',
  19973. '\uFCCA': '\u0644\u062D',
  19974. '\uFCCB': '\u0644\u062E',
  19975. '\uFCCC': '\u0644\u0645',
  19976. '\uFCCD': '\u0644\u0647',
  19977. '\uFCCE': '\u0645\u062C',
  19978. '\uFCCF': '\u0645\u062D',
  19979. '\uFCD0': '\u0645\u062E',
  19980. '\uFCD1': '\u0645\u0645',
  19981. '\uFCD2': '\u0646\u062C',
  19982. '\uFCD3': '\u0646\u062D',
  19983. '\uFCD4': '\u0646\u062E',
  19984. '\uFCD5': '\u0646\u0645',
  19985. '\uFCD6': '\u0646\u0647',
  19986. '\uFCD7': '\u0647\u062C',
  19987. '\uFCD8': '\u0647\u0645',
  19988. '\uFCD9': '\u0647\u0670',
  19989. '\uFCDA': '\u064A\u062C',
  19990. '\uFCDB': '\u064A\u062D',
  19991. '\uFCDC': '\u064A\u062E',
  19992. '\uFCDD': '\u064A\u0645',
  19993. '\uFCDE': '\u064A\u0647',
  19994. '\uFCDF': '\u0626\u0645',
  19995. '\uFCE0': '\u0626\u0647',
  19996. '\uFCE1': '\u0628\u0645',
  19997. '\uFCE2': '\u0628\u0647',
  19998. '\uFCE3': '\u062A\u0645',
  19999. '\uFCE4': '\u062A\u0647',
  20000. '\uFCE5': '\u062B\u0645',
  20001. '\uFCE6': '\u062B\u0647',
  20002. '\uFCE7': '\u0633\u0645',
  20003. '\uFCE8': '\u0633\u0647',
  20004. '\uFCE9': '\u0634\u0645',
  20005. '\uFCEA': '\u0634\u0647',
  20006. '\uFCEB': '\u0643\u0644',
  20007. '\uFCEC': '\u0643\u0645',
  20008. '\uFCED': '\u0644\u0645',
  20009. '\uFCEE': '\u0646\u0645',
  20010. '\uFCEF': '\u0646\u0647',
  20011. '\uFCF0': '\u064A\u0645',
  20012. '\uFCF1': '\u064A\u0647',
  20013. '\uFCF2': '\u0640\u064E\u0651',
  20014. '\uFCF3': '\u0640\u064F\u0651',
  20015. '\uFCF4': '\u0640\u0650\u0651',
  20016. '\uFCF5': '\u0637\u0649',
  20017. '\uFCF6': '\u0637\u064A',
  20018. '\uFCF7': '\u0639\u0649',
  20019. '\uFCF8': '\u0639\u064A',
  20020. '\uFCF9': '\u063A\u0649',
  20021. '\uFCFA': '\u063A\u064A',
  20022. '\uFCFB': '\u0633\u0649',
  20023. '\uFCFC': '\u0633\u064A',
  20024. '\uFCFD': '\u0634\u0649',
  20025. '\uFCFE': '\u0634\u064A',
  20026. '\uFCFF': '\u062D\u0649',
  20027. '\uFD00': '\u062D\u064A',
  20028. '\uFD01': '\u062C\u0649',
  20029. '\uFD02': '\u062C\u064A',
  20030. '\uFD03': '\u062E\u0649',
  20031. '\uFD04': '\u062E\u064A',
  20032. '\uFD05': '\u0635\u0649',
  20033. '\uFD06': '\u0635\u064A',
  20034. '\uFD07': '\u0636\u0649',
  20035. '\uFD08': '\u0636\u064A',
  20036. '\uFD09': '\u0634\u062C',
  20037. '\uFD0A': '\u0634\u062D',
  20038. '\uFD0B': '\u0634\u062E',
  20039. '\uFD0C': '\u0634\u0645',
  20040. '\uFD0D': '\u0634\u0631',
  20041. '\uFD0E': '\u0633\u0631',
  20042. '\uFD0F': '\u0635\u0631',
  20043. '\uFD10': '\u0636\u0631',
  20044. '\uFD11': '\u0637\u0649',
  20045. '\uFD12': '\u0637\u064A',
  20046. '\uFD13': '\u0639\u0649',
  20047. '\uFD14': '\u0639\u064A',
  20048. '\uFD15': '\u063A\u0649',
  20049. '\uFD16': '\u063A\u064A',
  20050. '\uFD17': '\u0633\u0649',
  20051. '\uFD18': '\u0633\u064A',
  20052. '\uFD19': '\u0634\u0649',
  20053. '\uFD1A': '\u0634\u064A',
  20054. '\uFD1B': '\u062D\u0649',
  20055. '\uFD1C': '\u062D\u064A',
  20056. '\uFD1D': '\u062C\u0649',
  20057. '\uFD1E': '\u062C\u064A',
  20058. '\uFD1F': '\u062E\u0649',
  20059. '\uFD20': '\u062E\u064A',
  20060. '\uFD21': '\u0635\u0649',
  20061. '\uFD22': '\u0635\u064A',
  20062. '\uFD23': '\u0636\u0649',
  20063. '\uFD24': '\u0636\u064A',
  20064. '\uFD25': '\u0634\u062C',
  20065. '\uFD26': '\u0634\u062D',
  20066. '\uFD27': '\u0634\u062E',
  20067. '\uFD28': '\u0634\u0645',
  20068. '\uFD29': '\u0634\u0631',
  20069. '\uFD2A': '\u0633\u0631',
  20070. '\uFD2B': '\u0635\u0631',
  20071. '\uFD2C': '\u0636\u0631',
  20072. '\uFD2D': '\u0634\u062C',
  20073. '\uFD2E': '\u0634\u062D',
  20074. '\uFD2F': '\u0634\u062E',
  20075. '\uFD30': '\u0634\u0645',
  20076. '\uFD31': '\u0633\u0647',
  20077. '\uFD32': '\u0634\u0647',
  20078. '\uFD33': '\u0637\u0645',
  20079. '\uFD34': '\u0633\u062C',
  20080. '\uFD35': '\u0633\u062D',
  20081. '\uFD36': '\u0633\u062E',
  20082. '\uFD37': '\u0634\u062C',
  20083. '\uFD38': '\u0634\u062D',
  20084. '\uFD39': '\u0634\u062E',
  20085. '\uFD3A': '\u0637\u0645',
  20086. '\uFD3B': '\u0638\u0645',
  20087. '\uFD3C': '\u0627\u064B',
  20088. '\uFD3D': '\u0627\u064B',
  20089. '\uFD50': '\u062A\u062C\u0645',
  20090. '\uFD51': '\u062A\u062D\u062C',
  20091. '\uFD52': '\u062A\u062D\u062C',
  20092. '\uFD53': '\u062A\u062D\u0645',
  20093. '\uFD54': '\u062A\u062E\u0645',
  20094. '\uFD55': '\u062A\u0645\u062C',
  20095. '\uFD56': '\u062A\u0645\u062D',
  20096. '\uFD57': '\u062A\u0645\u062E',
  20097. '\uFD58': '\u062C\u0645\u062D',
  20098. '\uFD59': '\u062C\u0645\u062D',
  20099. '\uFD5A': '\u062D\u0645\u064A',
  20100. '\uFD5B': '\u062D\u0645\u0649',
  20101. '\uFD5C': '\u0633\u062D\u062C',
  20102. '\uFD5D': '\u0633\u062C\u062D',
  20103. '\uFD5E': '\u0633\u062C\u0649',
  20104. '\uFD5F': '\u0633\u0645\u062D',
  20105. '\uFD60': '\u0633\u0645\u062D',
  20106. '\uFD61': '\u0633\u0645\u062C',
  20107. '\uFD62': '\u0633\u0645\u0645',
  20108. '\uFD63': '\u0633\u0645\u0645',
  20109. '\uFD64': '\u0635\u062D\u062D',
  20110. '\uFD65': '\u0635\u062D\u062D',
  20111. '\uFD66': '\u0635\u0645\u0645',
  20112. '\uFD67': '\u0634\u062D\u0645',
  20113. '\uFD68': '\u0634\u062D\u0645',
  20114. '\uFD69': '\u0634\u062C\u064A',
  20115. '\uFD6A': '\u0634\u0645\u062E',
  20116. '\uFD6B': '\u0634\u0645\u062E',
  20117. '\uFD6C': '\u0634\u0645\u0645',
  20118. '\uFD6D': '\u0634\u0645\u0645',
  20119. '\uFD6E': '\u0636\u062D\u0649',
  20120. '\uFD6F': '\u0636\u062E\u0645',
  20121. '\uFD70': '\u0636\u062E\u0645',
  20122. '\uFD71': '\u0637\u0645\u062D',
  20123. '\uFD72': '\u0637\u0645\u062D',
  20124. '\uFD73': '\u0637\u0645\u0645',
  20125. '\uFD74': '\u0637\u0645\u064A',
  20126. '\uFD75': '\u0639\u062C\u0645',
  20127. '\uFD76': '\u0639\u0645\u0645',
  20128. '\uFD77': '\u0639\u0645\u0645',
  20129. '\uFD78': '\u0639\u0645\u0649',
  20130. '\uFD79': '\u063A\u0645\u0645',
  20131. '\uFD7A': '\u063A\u0645\u064A',
  20132. '\uFD7B': '\u063A\u0645\u0649',
  20133. '\uFD7C': '\u0641\u062E\u0645',
  20134. '\uFD7D': '\u0641\u062E\u0645',
  20135. '\uFD7E': '\u0642\u0645\u062D',
  20136. '\uFD7F': '\u0642\u0645\u0645',
  20137. '\uFD80': '\u0644\u062D\u0645',
  20138. '\uFD81': '\u0644\u062D\u064A',
  20139. '\uFD82': '\u0644\u062D\u0649',
  20140. '\uFD83': '\u0644\u062C\u062C',
  20141. '\uFD84': '\u0644\u062C\u062C',
  20142. '\uFD85': '\u0644\u062E\u0645',
  20143. '\uFD86': '\u0644\u062E\u0645',
  20144. '\uFD87': '\u0644\u0645\u062D',
  20145. '\uFD88': '\u0644\u0645\u062D',
  20146. '\uFD89': '\u0645\u062D\u062C',
  20147. '\uFD8A': '\u0645\u062D\u0645',
  20148. '\uFD8B': '\u0645\u062D\u064A',
  20149. '\uFD8C': '\u0645\u062C\u062D',
  20150. '\uFD8D': '\u0645\u062C\u0645',
  20151. '\uFD8E': '\u0645\u062E\u062C',
  20152. '\uFD8F': '\u0645\u062E\u0645',
  20153. '\uFD92': '\u0645\u062C\u062E',
  20154. '\uFD93': '\u0647\u0645\u062C',
  20155. '\uFD94': '\u0647\u0645\u0645',
  20156. '\uFD95': '\u0646\u062D\u0645',
  20157. '\uFD96': '\u0646\u062D\u0649',
  20158. '\uFD97': '\u0646\u062C\u0645',
  20159. '\uFD98': '\u0646\u062C\u0645',
  20160. '\uFD99': '\u0646\u062C\u0649',
  20161. '\uFD9A': '\u0646\u0645\u064A',
  20162. '\uFD9B': '\u0646\u0645\u0649',
  20163. '\uFD9C': '\u064A\u0645\u0645',
  20164. '\uFD9D': '\u064A\u0645\u0645',
  20165. '\uFD9E': '\u0628\u062E\u064A',
  20166. '\uFD9F': '\u062A\u062C\u064A',
  20167. '\uFDA0': '\u062A\u062C\u0649',
  20168. '\uFDA1': '\u062A\u062E\u064A',
  20169. '\uFDA2': '\u062A\u062E\u0649',
  20170. '\uFDA3': '\u062A\u0645\u064A',
  20171. '\uFDA4': '\u062A\u0645\u0649',
  20172. '\uFDA5': '\u062C\u0645\u064A',
  20173. '\uFDA6': '\u062C\u062D\u0649',
  20174. '\uFDA7': '\u062C\u0645\u0649',
  20175. '\uFDA8': '\u0633\u062E\u0649',
  20176. '\uFDA9': '\u0635\u062D\u064A',
  20177. '\uFDAA': '\u0634\u062D\u064A',
  20178. '\uFDAB': '\u0636\u062D\u064A',
  20179. '\uFDAC': '\u0644\u062C\u064A',
  20180. '\uFDAD': '\u0644\u0645\u064A',
  20181. '\uFDAE': '\u064A\u062D\u064A',
  20182. '\uFDAF': '\u064A\u062C\u064A',
  20183. '\uFDB0': '\u064A\u0645\u064A',
  20184. '\uFDB1': '\u0645\u0645\u064A',
  20185. '\uFDB2': '\u0642\u0645\u064A',
  20186. '\uFDB3': '\u0646\u062D\u064A',
  20187. '\uFDB4': '\u0642\u0645\u062D',
  20188. '\uFDB5': '\u0644\u062D\u0645',
  20189. '\uFDB6': '\u0639\u0645\u064A',
  20190. '\uFDB7': '\u0643\u0645\u064A',
  20191. '\uFDB8': '\u0646\u062C\u062D',
  20192. '\uFDB9': '\u0645\u062E\u064A',
  20193. '\uFDBA': '\u0644\u062C\u0645',
  20194. '\uFDBB': '\u0643\u0645\u0645',
  20195. '\uFDBC': '\u0644\u062C\u0645',
  20196. '\uFDBD': '\u0646\u062C\u062D',
  20197. '\uFDBE': '\u062C\u062D\u064A',
  20198. '\uFDBF': '\u062D\u062C\u064A',
  20199. '\uFDC0': '\u0645\u062C\u064A',
  20200. '\uFDC1': '\u0641\u0645\u064A',
  20201. '\uFDC2': '\u0628\u062D\u064A',
  20202. '\uFDC3': '\u0643\u0645\u0645',
  20203. '\uFDC4': '\u0639\u062C\u0645',
  20204. '\uFDC5': '\u0635\u0645\u0645',
  20205. '\uFDC6': '\u0633\u062E\u064A',
  20206. '\uFDC7': '\u0646\u062C\u064A',
  20207. '\uFE49': '\u203E',
  20208. '\uFE4A': '\u203E',
  20209. '\uFE4B': '\u203E',
  20210. '\uFE4C': '\u203E',
  20211. '\uFE4D': '\u005F',
  20212. '\uFE4E': '\u005F',
  20213. '\uFE4F': '\u005F',
  20214. '\uFE80': '\u0621',
  20215. '\uFE81': '\u0622',
  20216. '\uFE82': '\u0622',
  20217. '\uFE83': '\u0623',
  20218. '\uFE84': '\u0623',
  20219. '\uFE85': '\u0624',
  20220. '\uFE86': '\u0624',
  20221. '\uFE87': '\u0625',
  20222. '\uFE88': '\u0625',
  20223. '\uFE89': '\u0626',
  20224. '\uFE8A': '\u0626',
  20225. '\uFE8B': '\u0626',
  20226. '\uFE8C': '\u0626',
  20227. '\uFE8D': '\u0627',
  20228. '\uFE8E': '\u0627',
  20229. '\uFE8F': '\u0628',
  20230. '\uFE90': '\u0628',
  20231. '\uFE91': '\u0628',
  20232. '\uFE92': '\u0628',
  20233. '\uFE93': '\u0629',
  20234. '\uFE94': '\u0629',
  20235. '\uFE95': '\u062A',
  20236. '\uFE96': '\u062A',
  20237. '\uFE97': '\u062A',
  20238. '\uFE98': '\u062A',
  20239. '\uFE99': '\u062B',
  20240. '\uFE9A': '\u062B',
  20241. '\uFE9B': '\u062B',
  20242. '\uFE9C': '\u062B',
  20243. '\uFE9D': '\u062C',
  20244. '\uFE9E': '\u062C',
  20245. '\uFE9F': '\u062C',
  20246. '\uFEA0': '\u062C',
  20247. '\uFEA1': '\u062D',
  20248. '\uFEA2': '\u062D',
  20249. '\uFEA3': '\u062D',
  20250. '\uFEA4': '\u062D',
  20251. '\uFEA5': '\u062E',
  20252. '\uFEA6': '\u062E',
  20253. '\uFEA7': '\u062E',
  20254. '\uFEA8': '\u062E',
  20255. '\uFEA9': '\u062F',
  20256. '\uFEAA': '\u062F',
  20257. '\uFEAB': '\u0630',
  20258. '\uFEAC': '\u0630',
  20259. '\uFEAD': '\u0631',
  20260. '\uFEAE': '\u0631',
  20261. '\uFEAF': '\u0632',
  20262. '\uFEB0': '\u0632',
  20263. '\uFEB1': '\u0633',
  20264. '\uFEB2': '\u0633',
  20265. '\uFEB3': '\u0633',
  20266. '\uFEB4': '\u0633',
  20267. '\uFEB5': '\u0634',
  20268. '\uFEB6': '\u0634',
  20269. '\uFEB7': '\u0634',
  20270. '\uFEB8': '\u0634',
  20271. '\uFEB9': '\u0635',
  20272. '\uFEBA': '\u0635',
  20273. '\uFEBB': '\u0635',
  20274. '\uFEBC': '\u0635',
  20275. '\uFEBD': '\u0636',
  20276. '\uFEBE': '\u0636',
  20277. '\uFEBF': '\u0636',
  20278. '\uFEC0': '\u0636',
  20279. '\uFEC1': '\u0637',
  20280. '\uFEC2': '\u0637',
  20281. '\uFEC3': '\u0637',
  20282. '\uFEC4': '\u0637',
  20283. '\uFEC5': '\u0638',
  20284. '\uFEC6': '\u0638',
  20285. '\uFEC7': '\u0638',
  20286. '\uFEC8': '\u0638',
  20287. '\uFEC9': '\u0639',
  20288. '\uFECA': '\u0639',
  20289. '\uFECB': '\u0639',
  20290. '\uFECC': '\u0639',
  20291. '\uFECD': '\u063A',
  20292. '\uFECE': '\u063A',
  20293. '\uFECF': '\u063A',
  20294. '\uFED0': '\u063A',
  20295. '\uFED1': '\u0641',
  20296. '\uFED2': '\u0641',
  20297. '\uFED3': '\u0641',
  20298. '\uFED4': '\u0641',
  20299. '\uFED5': '\u0642',
  20300. '\uFED6': '\u0642',
  20301. '\uFED7': '\u0642',
  20302. '\uFED8': '\u0642',
  20303. '\uFED9': '\u0643',
  20304. '\uFEDA': '\u0643',
  20305. '\uFEDB': '\u0643',
  20306. '\uFEDC': '\u0643',
  20307. '\uFEDD': '\u0644',
  20308. '\uFEDE': '\u0644',
  20309. '\uFEDF': '\u0644',
  20310. '\uFEE0': '\u0644',
  20311. '\uFEE1': '\u0645',
  20312. '\uFEE2': '\u0645',
  20313. '\uFEE3': '\u0645',
  20314. '\uFEE4': '\u0645',
  20315. '\uFEE5': '\u0646',
  20316. '\uFEE6': '\u0646',
  20317. '\uFEE7': '\u0646',
  20318. '\uFEE8': '\u0646',
  20319. '\uFEE9': '\u0647',
  20320. '\uFEEA': '\u0647',
  20321. '\uFEEB': '\u0647',
  20322. '\uFEEC': '\u0647',
  20323. '\uFEED': '\u0648',
  20324. '\uFEEE': '\u0648',
  20325. '\uFEEF': '\u0649',
  20326. '\uFEF0': '\u0649',
  20327. '\uFEF1': '\u064A',
  20328. '\uFEF2': '\u064A',
  20329. '\uFEF3': '\u064A',
  20330. '\uFEF4': '\u064A',
  20331. '\uFEF5': '\u0644\u0622',
  20332. '\uFEF6': '\u0644\u0622',
  20333. '\uFEF7': '\u0644\u0623',
  20334. '\uFEF8': '\u0644\u0623',
  20335. '\uFEF9': '\u0644\u0625',
  20336. '\uFEFA': '\u0644\u0625',
  20337. '\uFEFB': '\u0644\u0627',
  20338. '\uFEFC': '\u0644\u0627'
  20339. };
  20340. function reverseIfRtl(chars) {
  20341. var charsLength = chars.length;
  20342. //reverse an arabic ligature
  20343. if (charsLength <= 1 || !isRTLRangeFor(chars.charCodeAt(0))) {
  20344. return chars;
  20345. }
  20346. var s = '';
  20347. for (var ii = charsLength - 1; ii >= 0; ii--) {
  20348. s += chars[ii];
  20349. }
  20350. return s;
  20351. }
  20352. function adjustWidths(properties) {
  20353. if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
  20354. return;
  20355. }
  20356. // adjusting width to fontMatrix scale
  20357. var scale = 0.001 / properties.fontMatrix[0];
  20358. var glyphsWidths = properties.widths;
  20359. for (var glyph in glyphsWidths) {
  20360. glyphsWidths[glyph] *= scale;
  20361. }
  20362. properties.defaultWidth *= scale;
  20363. }
  20364. function getFontType(type, subtype) {
  20365. switch (type) {
  20366. case 'Type1':
  20367. return subtype === 'Type1C' ? FontType.TYPE1C : FontType.TYPE1;
  20368. case 'CIDFontType0':
  20369. return subtype === 'CIDFontType0C' ? FontType.CIDFONTTYPE0C :
  20370. FontType.CIDFONTTYPE0;
  20371. case 'OpenType':
  20372. return FontType.OPENTYPE;
  20373. case 'TrueType':
  20374. return FontType.TRUETYPE;
  20375. case 'CIDFontType2':
  20376. return FontType.CIDFONTTYPE2;
  20377. case 'MMType1':
  20378. return FontType.MMTYPE1;
  20379. case 'Type0':
  20380. return FontType.TYPE0;
  20381. default:
  20382. return FontType.UNKNOWN;
  20383. }
  20384. }
  20385. var Glyph = (function GlyphClosure() {
  20386. function Glyph(fontChar, unicode, accent, width, vmetric, operatorListId) {
  20387. this.fontChar = fontChar;
  20388. this.unicode = unicode;
  20389. this.accent = accent;
  20390. this.width = width;
  20391. this.vmetric = vmetric;
  20392. this.operatorListId = operatorListId;
  20393. }
  20394. Glyph.prototype.matchesForCache =
  20395. function(fontChar, unicode, accent, width, vmetric, operatorListId) {
  20396. return this.fontChar === fontChar &&
  20397. this.unicode === unicode &&
  20398. this.accent === accent &&
  20399. this.width === width &&
  20400. this.vmetric === vmetric &&
  20401. this.operatorListId === operatorListId;
  20402. };
  20403. return Glyph;
  20404. })();
  20405. var ToUnicodeMap = (function ToUnicodeMapClosure() {
  20406. function ToUnicodeMap(cmap) {
  20407. // The elements of this._map can be integers or strings, depending on how
  20408. // |cmap| was created.
  20409. this._map = cmap;
  20410. }
  20411. ToUnicodeMap.prototype = {
  20412. get length() {
  20413. return this._map.length;
  20414. },
  20415. forEach: function(callback) {
  20416. for (var charCode in this._map) {
  20417. callback(charCode, this._map[charCode].charCodeAt(0));
  20418. }
  20419. },
  20420. get: function(i) {
  20421. return this._map[i];
  20422. },
  20423. charCodeOf: function(v) {
  20424. return this._map.indexOf(v);
  20425. }
  20426. };
  20427. return ToUnicodeMap;
  20428. })();
  20429. var IdentityToUnicodeMap = (function IdentityToUnicodeMapClosure() {
  20430. function IdentityToUnicodeMap(firstChar, lastChar) {
  20431. this.firstChar = firstChar;
  20432. this.lastChar = lastChar;
  20433. }
  20434. IdentityToUnicodeMap.prototype = {
  20435. get length() {
  20436. error('should not access .length');
  20437. },
  20438. forEach: function (callback) {
  20439. for (var i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
  20440. callback(i, i);
  20441. }
  20442. },
  20443. get: function (i) {
  20444. if (this.firstChar <= i && i <= this.lastChar) {
  20445. return String.fromCharCode(i);
  20446. }
  20447. return undefined;
  20448. },
  20449. charCodeOf: function (v) {
  20450. error('should not call .charCodeOf');
  20451. }
  20452. };
  20453. return IdentityToUnicodeMap;
  20454. })();
  20455. var OpenTypeFileBuilder = (function OpenTypeFileBuilderClosure() {
  20456. function writeInt16(dest, offset, num) {
  20457. dest[offset] = (num >> 8) & 0xFF;
  20458. dest[offset + 1] = num & 0xFF;
  20459. }
  20460. function writeInt32(dest, offset, num) {
  20461. dest[offset] = (num >> 24) & 0xFF;
  20462. dest[offset + 1] = (num >> 16) & 0xFF;
  20463. dest[offset + 2] = (num >> 8) & 0xFF;
  20464. dest[offset + 3] = num & 0xFF;
  20465. }
  20466. function writeData(dest, offset, data) {
  20467. var i, ii;
  20468. if (data instanceof Uint8Array) {
  20469. dest.set(data, offset);
  20470. } else if (typeof data === 'string') {
  20471. for (i = 0, ii = data.length; i < ii; i++) {
  20472. dest[offset++] = data.charCodeAt(i) & 0xFF;
  20473. }
  20474. } else {
  20475. // treating everything else as array
  20476. for (i = 0, ii = data.length; i < ii; i++) {
  20477. dest[offset++] = data[i] & 0xFF;
  20478. }
  20479. }
  20480. }
  20481. function OpenTypeFileBuilder(sfnt) {
  20482. this.sfnt = sfnt;
  20483. this.tables = Object.create(null);
  20484. }
  20485. OpenTypeFileBuilder.getSearchParams =
  20486. function OpenTypeFileBuilder_getSearchParams(entriesCount, entrySize) {
  20487. var maxPower2 = 1, log2 = 0;
  20488. while ((maxPower2 ^ entriesCount) > maxPower2) {
  20489. maxPower2 <<= 1;
  20490. log2++;
  20491. }
  20492. var searchRange = maxPower2 * entrySize;
  20493. return {
  20494. range: searchRange,
  20495. entry: log2,
  20496. rangeShift: entrySize * entriesCount - searchRange
  20497. };
  20498. };
  20499. var OTF_HEADER_SIZE = 12;
  20500. var OTF_TABLE_ENTRY_SIZE = 16;
  20501. OpenTypeFileBuilder.prototype = {
  20502. toArray: function OpenTypeFileBuilder_toArray() {
  20503. var sfnt = this.sfnt;
  20504. // Tables needs to be written by ascendant alphabetic order
  20505. var tables = this.tables;
  20506. var tablesNames = Object.keys(tables);
  20507. tablesNames.sort();
  20508. var numTables = tablesNames.length;
  20509. var i, j, jj, table, tableName;
  20510. // layout the tables data
  20511. var offset = OTF_HEADER_SIZE + numTables * OTF_TABLE_ENTRY_SIZE;
  20512. var tableOffsets = [offset];
  20513. for (i = 0; i < numTables; i++) {
  20514. table = tables[tablesNames[i]];
  20515. var paddedLength = ((table.length + 3) & ~3) >>> 0;
  20516. offset += paddedLength;
  20517. tableOffsets.push(offset);
  20518. }
  20519. var file = new Uint8Array(offset);
  20520. // write the table data first (mostly for checksum)
  20521. for (i = 0; i < numTables; i++) {
  20522. table = tables[tablesNames[i]];
  20523. writeData(file, tableOffsets[i], table);
  20524. }
  20525. // sfnt version (4 bytes)
  20526. if (sfnt === 'true') {
  20527. // Windows hates the Mac TrueType sfnt version number
  20528. sfnt = string32(0x00010000);
  20529. }
  20530. file[0] = sfnt.charCodeAt(0) & 0xFF;
  20531. file[1] = sfnt.charCodeAt(1) & 0xFF;
  20532. file[2] = sfnt.charCodeAt(2) & 0xFF;
  20533. file[3] = sfnt.charCodeAt(3) & 0xFF;
  20534. // numTables (2 bytes)
  20535. writeInt16(file, 4, numTables);
  20536. var searchParams = OpenTypeFileBuilder.getSearchParams(numTables, 16);
  20537. // searchRange (2 bytes)
  20538. writeInt16(file, 6, searchParams.range);
  20539. // entrySelector (2 bytes)
  20540. writeInt16(file, 8, searchParams.entry);
  20541. // rangeShift (2 bytes)
  20542. writeInt16(file, 10, searchParams.rangeShift);
  20543. offset = OTF_HEADER_SIZE;
  20544. // writing table entries
  20545. for (i = 0; i < numTables; i++) {
  20546. tableName = tablesNames[i];
  20547. file[offset] = tableName.charCodeAt(0) & 0xFF;
  20548. file[offset + 1] = tableName.charCodeAt(1) & 0xFF;
  20549. file[offset + 2] = tableName.charCodeAt(2) & 0xFF;
  20550. file[offset + 3] = tableName.charCodeAt(3) & 0xFF;
  20551. // checksum
  20552. var checksum = 0;
  20553. for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
  20554. var quad = (file[j] << 24) + (file[j + 1] << 16) +
  20555. (file[j + 2] << 8) + file[j + 3];
  20556. checksum = (checksum + quad) | 0;
  20557. }
  20558. writeInt32(file, offset + 4, checksum);
  20559. // offset
  20560. writeInt32(file, offset + 8, tableOffsets[i]);
  20561. // length
  20562. writeInt32(file, offset + 12, tables[tableName].length);
  20563. offset += OTF_TABLE_ENTRY_SIZE;
  20564. }
  20565. return file;
  20566. },
  20567. addTable: function OpenTypeFileBuilder_addTable(tag, data) {
  20568. if (tag in this.tables) {
  20569. throw new Error('Table ' + tag + ' already exists');
  20570. }
  20571. this.tables[tag] = data;
  20572. }
  20573. };
  20574. return OpenTypeFileBuilder;
  20575. })();
  20576. /**
  20577. * 'Font' is the class the outside world should use, it encapsulate all the font
  20578. * decoding logics whatever type it is (assuming the font type is supported).
  20579. *
  20580. * For example to read a Type1 font and to attach it to the document:
  20581. * var type1Font = new Font("MyFontName", binaryFile, propertiesObject);
  20582. * type1Font.bind();
  20583. */
  20584. var Font = (function FontClosure() {
  20585. function Font(name, file, properties) {
  20586. var charCode, glyphName, fontChar;
  20587. this.name = name;
  20588. this.loadedName = properties.loadedName;
  20589. this.isType3Font = properties.isType3Font;
  20590. this.sizes = [];
  20591. this.glyphCache = {};
  20592. var names = name.split('+');
  20593. names = names.length > 1 ? names[1] : names[0];
  20594. names = names.split(/[-,_]/g)[0];
  20595. this.isSerifFont = !!(properties.flags & FontFlags.Serif);
  20596. this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  20597. this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);
  20598. var type = properties.type;
  20599. var subtype = properties.subtype;
  20600. this.type = type;
  20601. this.fallbackName = (this.isMonospace ? 'monospace' :
  20602. (this.isSerifFont ? 'serif' : 'sans-serif'));
  20603. this.differences = properties.differences;
  20604. this.widths = properties.widths;
  20605. this.defaultWidth = properties.defaultWidth;
  20606. this.composite = properties.composite;
  20607. this.wideChars = properties.wideChars;
  20608. this.cMap = properties.cMap;
  20609. this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
  20610. this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
  20611. this.fontMatrix = properties.fontMatrix;
  20612. this.toUnicode = properties.toUnicode = this.buildToUnicode(properties);
  20613. this.toFontChar = [];
  20614. if (properties.type === 'Type3') {
  20615. for (charCode = 0; charCode < 256; charCode++) {
  20616. this.toFontChar[charCode] = (this.differences[charCode] ||
  20617. properties.defaultEncoding[charCode]);
  20618. }
  20619. this.fontType = FontType.TYPE3;
  20620. return;
  20621. }
  20622. this.cidEncoding = properties.cidEncoding;
  20623. this.vertical = properties.vertical;
  20624. if (this.vertical) {
  20625. this.vmetrics = properties.vmetrics;
  20626. this.defaultVMetrics = properties.defaultVMetrics;
  20627. }
  20628. if (!file || file.isEmpty) {
  20629. if (file) {
  20630. // Some bad PDF generators will include empty font files,
  20631. // attempting to recover by assuming that no file exists.
  20632. warn('Font file is empty in "' + name + '" (' + this.loadedName + ')');
  20633. }
  20634. this.missingFile = true;
  20635. // The file data is not specified. Trying to fix the font name
  20636. // to be used with the canvas.font.
  20637. var fontName = name.replace(/[,_]/g, '-');
  20638. var isStandardFont = !!stdFontMap[fontName] ||
  20639. (nonStdFontMap[fontName] && !!stdFontMap[nonStdFontMap[fontName]]);
  20640. fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
  20641. this.bold = (fontName.search(/bold/gi) !== -1);
  20642. this.italic = ((fontName.search(/oblique/gi) !== -1) ||
  20643. (fontName.search(/italic/gi) !== -1));
  20644. // Use 'name' instead of 'fontName' here because the original
  20645. // name ArialBlack for example will be replaced by Helvetica.
  20646. this.black = (name.search(/Black/g) !== -1);
  20647. // if at least one width is present, remeasure all chars when exists
  20648. this.remeasure = Object.keys(this.widths).length > 0;
  20649. if (isStandardFont && type === 'CIDFontType2' &&
  20650. properties.cidEncoding.indexOf('Identity-') === 0) {
  20651. // Standard fonts might be embedded as CID font without glyph mapping.
  20652. // Building one based on GlyphMapForStandardFonts.
  20653. var map = [];
  20654. for (var code in GlyphMapForStandardFonts) {
  20655. map[+code] = GlyphMapForStandardFonts[code];
  20656. }
  20657. var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
  20658. if (!isIdentityUnicode) {
  20659. this.toUnicode.forEach(function(charCode, unicodeCharCode) {
  20660. map[+charCode] = unicodeCharCode;
  20661. });
  20662. }
  20663. this.toFontChar = map;
  20664. this.toUnicode = new ToUnicodeMap(map);
  20665. } else if (/Symbol/i.test(fontName)) {
  20666. var symbols = Encodings.SymbolSetEncoding;
  20667. for (charCode in symbols) {
  20668. fontChar = GlyphsUnicode[symbols[charCode]];
  20669. if (!fontChar) {
  20670. continue;
  20671. }
  20672. this.toFontChar[charCode] = fontChar;
  20673. }
  20674. for (charCode in properties.differences) {
  20675. fontChar = GlyphsUnicode[properties.differences[charCode]];
  20676. if (!fontChar) {
  20677. continue;
  20678. }
  20679. this.toFontChar[charCode] = fontChar;
  20680. }
  20681. } else if (/Dingbats/i.test(fontName)) {
  20682. if (/Wingdings/i.test(name)) {
  20683. warn('Wingdings font without embedded font file, ' +
  20684. 'falling back to the ZapfDingbats encoding.');
  20685. }
  20686. var dingbats = Encodings.ZapfDingbatsEncoding;
  20687. for (charCode in dingbats) {
  20688. fontChar = DingbatsGlyphsUnicode[dingbats[charCode]];
  20689. if (!fontChar) {
  20690. continue;
  20691. }
  20692. this.toFontChar[charCode] = fontChar;
  20693. }
  20694. for (charCode in properties.differences) {
  20695. fontChar = DingbatsGlyphsUnicode[properties.differences[charCode]];
  20696. if (!fontChar) {
  20697. continue;
  20698. }
  20699. this.toFontChar[charCode] = fontChar;
  20700. }
  20701. } else if (isStandardFont) {
  20702. this.toFontChar = [];
  20703. for (charCode in properties.defaultEncoding) {
  20704. glyphName = (properties.differences[charCode] ||
  20705. properties.defaultEncoding[charCode]);
  20706. this.toFontChar[charCode] = GlyphsUnicode[glyphName];
  20707. }
  20708. } else {
  20709. var unicodeCharCode, notCidFont = (type.indexOf('CIDFontType') === -1);
  20710. this.toUnicode.forEach(function(charCode, unicodeCharCode) {
  20711. if (notCidFont) {
  20712. glyphName = (properties.differences[charCode] ||
  20713. properties.defaultEncoding[charCode]);
  20714. unicodeCharCode = (GlyphsUnicode[glyphName] || unicodeCharCode);
  20715. }
  20716. this.toFontChar[charCode] = unicodeCharCode;
  20717. }.bind(this));
  20718. }
  20719. this.loadedName = fontName.split('-')[0];
  20720. this.loading = false;
  20721. this.fontType = getFontType(type, subtype);
  20722. return;
  20723. }
  20724. // Some fonts might use wrong font types for Type1C or CIDFontType0C
  20725. if (subtype === 'Type1C' && (type !== 'Type1' && type !== 'MMType1')) {
  20726. // Some TrueType fonts by mistake claim Type1C
  20727. if (isTrueTypeFile(file)) {
  20728. subtype = 'TrueType';
  20729. } else {
  20730. type = 'Type1';
  20731. }
  20732. }
  20733. if (subtype === 'CIDFontType0C' && type !== 'CIDFontType0') {
  20734. type = 'CIDFontType0';
  20735. }
  20736. // XXX: Temporarily change the type for open type so we trigger a warning.
  20737. // This should be removed when we add support for open type.
  20738. if (subtype === 'OpenType') {
  20739. type = 'OpenType';
  20740. }
  20741. var data;
  20742. switch (type) {
  20743. case 'MMType1':
  20744. info('MMType1 font (' + name + '), falling back to Type1.');
  20745. /* falls through */
  20746. case 'Type1':
  20747. case 'CIDFontType0':
  20748. this.mimetype = 'font/opentype';
  20749. var cff = (subtype === 'Type1C' || subtype === 'CIDFontType0C') ?
  20750. new CFFFont(file, properties) : new Type1Font(name, file, properties);
  20751. adjustWidths(properties);
  20752. // Wrap the CFF data inside an OTF font file
  20753. data = this.convert(name, cff, properties);
  20754. break;
  20755. case 'OpenType':
  20756. case 'TrueType':
  20757. case 'CIDFontType2':
  20758. this.mimetype = 'font/opentype';
  20759. // Repair the TrueType file. It is can be damaged in the point of
  20760. // view of the sanitizer
  20761. data = this.checkAndRepair(name, file, properties);
  20762. if (this.isOpenType) {
  20763. type = 'OpenType';
  20764. }
  20765. break;
  20766. default:
  20767. error('Font ' + type + ' is not supported');
  20768. break;
  20769. }
  20770. this.data = data;
  20771. this.fontType = getFontType(type, subtype);
  20772. // Transfer some properties again that could change during font conversion
  20773. this.fontMatrix = properties.fontMatrix;
  20774. this.widths = properties.widths;
  20775. this.defaultWidth = properties.defaultWidth;
  20776. this.encoding = properties.baseEncoding;
  20777. this.seacMap = properties.seacMap;
  20778. this.loading = true;
  20779. }
  20780. Font.getFontID = (function () {
  20781. var ID = 1;
  20782. return function Font_getFontID() {
  20783. return String(ID++);
  20784. };
  20785. })();
  20786. function int16(b0, b1) {
  20787. return (b0 << 8) + b1;
  20788. }
  20789. function int32(b0, b1, b2, b3) {
  20790. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  20791. }
  20792. function string16(value) {
  20793. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  20794. }
  20795. function safeString16(value) {
  20796. // clamp value to the 16-bit int range
  20797. value = (value > 0x7FFF ? 0x7FFF : (value < -0x8000 ? -0x8000 : value));
  20798. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  20799. }
  20800. function isTrueTypeFile(file) {
  20801. var header = file.peekBytes(4);
  20802. return readUint32(header, 0) === 0x00010000;
  20803. }
  20804. /**
  20805. * Rebuilds the char code to glyph ID map by trying to replace the char codes
  20806. * with their unicode value. It also moves char codes that are in known
  20807. * problematic locations.
  20808. * @return {Object} Two properties:
  20809. * 'toFontChar' - maps original char codes(the value that will be read
  20810. * from commands such as show text) to the char codes that will be used in the
  20811. * font that we build
  20812. * 'charCodeToGlyphId' - maps the new font char codes to glyph ids
  20813. */
  20814. function adjustMapping(charCodeToGlyphId, properties) {
  20815. var toUnicode = properties.toUnicode;
  20816. var isSymbolic = !!(properties.flags & FontFlags.Symbolic);
  20817. var isIdentityUnicode =
  20818. properties.toUnicode instanceof IdentityToUnicodeMap;
  20819. var isCidFontType2 = (properties.type === 'CIDFontType2');
  20820. var newMap = Object.create(null);
  20821. var toFontChar = [];
  20822. var usedFontCharCodes = [];
  20823. var nextAvailableFontCharCode = PRIVATE_USE_OFFSET_START;
  20824. for (var originalCharCode in charCodeToGlyphId) {
  20825. originalCharCode |= 0;
  20826. var glyphId = charCodeToGlyphId[originalCharCode];
  20827. var fontCharCode = originalCharCode;
  20828. // First try to map the value to a unicode position if a non identity map
  20829. // was created.
  20830. if (!isIdentityUnicode) {
  20831. if (toUnicode.get(originalCharCode) !== undefined) {
  20832. var unicode = toUnicode.get(fontCharCode);
  20833. // TODO: Try to map ligatures to the correct spot.
  20834. if (unicode.length === 1) {
  20835. fontCharCode = unicode.charCodeAt(0);
  20836. }
  20837. } else if (isCidFontType2) {
  20838. // For CIDFontType2, move characters not present in toUnicode
  20839. // to the private use area (fixes bug 1028735 and issue 4881).
  20840. fontCharCode = nextAvailableFontCharCode;
  20841. }
  20842. }
  20843. // Try to move control characters, special characters and already mapped
  20844. // characters to the private use area since they will not be drawn by
  20845. // canvas if left in their current position. Also, move characters if the
  20846. // font was symbolic and there is only an identity unicode map since the
  20847. // characters probably aren't in the correct position (fixes an issue
  20848. // with firefox and thuluthfont).
  20849. if ((usedFontCharCodes[fontCharCode] !== undefined ||
  20850. fontCharCode <= 0x1f || // Control chars
  20851. fontCharCode === 0x7F || // Control char
  20852. fontCharCode === 0xAD || // Soft hyphen
  20853. fontCharCode === 0xA0 || // Non breaking space
  20854. (fontCharCode >= 0x80 && fontCharCode <= 0x9F) || // Control chars
  20855. // Prevent drawing characters in the specials unicode block.
  20856. (fontCharCode >= 0xFFF0 && fontCharCode <= 0xFFFF) ||
  20857. (isSymbolic && isIdentityUnicode)) &&
  20858. nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END) { // Room left.
  20859. // Loop to try and find a free spot in the private use area.
  20860. do {
  20861. fontCharCode = nextAvailableFontCharCode++;
  20862. if (SKIP_PRIVATE_USE_RANGE_F000_TO_F01F && fontCharCode === 0xF000) {
  20863. fontCharCode = 0xF020;
  20864. nextAvailableFontCharCode = fontCharCode + 1;
  20865. }
  20866. } while (usedFontCharCodes[fontCharCode] !== undefined &&
  20867. nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END);
  20868. }
  20869. newMap[fontCharCode] = glyphId;
  20870. toFontChar[originalCharCode] = fontCharCode;
  20871. usedFontCharCodes[fontCharCode] = true;
  20872. }
  20873. return {
  20874. toFontChar: toFontChar,
  20875. charCodeToGlyphId: newMap,
  20876. nextAvailableFontCharCode: nextAvailableFontCharCode
  20877. };
  20878. }
  20879. function getRanges(glyphs) {
  20880. // Array.sort() sorts by characters, not numerically, so convert to an
  20881. // array of characters.
  20882. var codes = [];
  20883. for (var charCode in glyphs) {
  20884. codes.push({ fontCharCode: charCode | 0, glyphId: glyphs[charCode] });
  20885. }
  20886. codes.sort(function fontGetRangesSort(a, b) {
  20887. return a.fontCharCode - b.fontCharCode;
  20888. });
  20889. // Split the sorted codes into ranges.
  20890. var ranges = [];
  20891. var length = codes.length;
  20892. for (var n = 0; n < length; ) {
  20893. var start = codes[n].fontCharCode;
  20894. var codeIndices = [codes[n].glyphId];
  20895. ++n;
  20896. var end = start;
  20897. while (n < length && end + 1 === codes[n].fontCharCode) {
  20898. codeIndices.push(codes[n].glyphId);
  20899. ++end;
  20900. ++n;
  20901. if (end === 0xFFFF) {
  20902. break;
  20903. }
  20904. }
  20905. ranges.push([start, end, codeIndices]);
  20906. }
  20907. return ranges;
  20908. }
  20909. function createCmapTable(glyphs) {
  20910. var ranges = getRanges(glyphs);
  20911. var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1;
  20912. var cmap = '\x00\x00' + // version
  20913. string16(numTables) + // numTables
  20914. '\x00\x03' + // platformID
  20915. '\x00\x01' + // encodingID
  20916. string32(4 + numTables * 8); // start of the table record
  20917. var i, ii, j, jj;
  20918. for (i = ranges.length - 1; i >= 0; --i) {
  20919. if (ranges[i][0] <= 0xFFFF) { break; }
  20920. }
  20921. var bmpLength = i + 1;
  20922. if (ranges[i][0] < 0xFFFF && ranges[i][1] === 0xFFFF) {
  20923. ranges[i][1] = 0xFFFE;
  20924. }
  20925. var trailingRangesCount = ranges[i][1] < 0xFFFF ? 1 : 0;
  20926. var segCount = bmpLength + trailingRangesCount;
  20927. var searchParams = OpenTypeFileBuilder.getSearchParams(segCount, 2);
  20928. // Fill up the 4 parallel arrays describing the segments.
  20929. var startCount = '';
  20930. var endCount = '';
  20931. var idDeltas = '';
  20932. var idRangeOffsets = '';
  20933. var glyphsIds = '';
  20934. var bias = 0;
  20935. var range, start, end, codes;
  20936. for (i = 0, ii = bmpLength; i < ii; i++) {
  20937. range = ranges[i];
  20938. start = range[0];
  20939. end = range[1];
  20940. startCount += string16(start);
  20941. endCount += string16(end);
  20942. codes = range[2];
  20943. var contiguous = true;
  20944. for (j = 1, jj = codes.length; j < jj; ++j) {
  20945. if (codes[j] !== codes[j - 1] + 1) {
  20946. contiguous = false;
  20947. break;
  20948. }
  20949. }
  20950. if (!contiguous) {
  20951. var offset = (segCount - i) * 2 + bias * 2;
  20952. bias += (end - start + 1);
  20953. idDeltas += string16(0);
  20954. idRangeOffsets += string16(offset);
  20955. for (j = 0, jj = codes.length; j < jj; ++j) {
  20956. glyphsIds += string16(codes[j]);
  20957. }
  20958. } else {
  20959. var startCode = codes[0];
  20960. idDeltas += string16((startCode - start) & 0xFFFF);
  20961. idRangeOffsets += string16(0);
  20962. }
  20963. }
  20964. if (trailingRangesCount > 0) {
  20965. endCount += '\xFF\xFF';
  20966. startCount += '\xFF\xFF';
  20967. idDeltas += '\x00\x01';
  20968. idRangeOffsets += '\x00\x00';
  20969. }
  20970. var format314 = '\x00\x00' + // language
  20971. string16(2 * segCount) +
  20972. string16(searchParams.range) +
  20973. string16(searchParams.entry) +
  20974. string16(searchParams.rangeShift) +
  20975. endCount + '\x00\x00' + startCount +
  20976. idDeltas + idRangeOffsets + glyphsIds;
  20977. var format31012 = '';
  20978. var header31012 = '';
  20979. if (numTables > 1) {
  20980. cmap += '\x00\x03' + // platformID
  20981. '\x00\x0A' + // encodingID
  20982. string32(4 + numTables * 8 +
  20983. 4 + format314.length); // start of the table record
  20984. format31012 = '';
  20985. for (i = 0, ii = ranges.length; i < ii; i++) {
  20986. range = ranges[i];
  20987. start = range[0];
  20988. codes = range[2];
  20989. var code = codes[0];
  20990. for (j = 1, jj = codes.length; j < jj; ++j) {
  20991. if (codes[j] !== codes[j - 1] + 1) {
  20992. end = range[0] + j - 1;
  20993. format31012 += string32(start) + // startCharCode
  20994. string32(end) + // endCharCode
  20995. string32(code); // startGlyphID
  20996. start = end + 1;
  20997. code = codes[j];
  20998. }
  20999. }
  21000. format31012 += string32(start) + // startCharCode
  21001. string32(range[1]) + // endCharCode
  21002. string32(code); // startGlyphID
  21003. }
  21004. header31012 = '\x00\x0C' + // format
  21005. '\x00\x00' + // reserved
  21006. string32(format31012.length + 16) + // length
  21007. '\x00\x00\x00\x00' + // language
  21008. string32(format31012.length / 12); // nGroups
  21009. }
  21010. return cmap + '\x00\x04' + // format
  21011. string16(format314.length + 4) + // length
  21012. format314 + header31012 + format31012;
  21013. }
  21014. function validateOS2Table(os2) {
  21015. var stream = new Stream(os2.data);
  21016. var version = stream.getUint16();
  21017. // TODO verify all OS/2 tables fields, but currently we validate only those
  21018. // that give us issues
  21019. stream.getBytes(60); // skipping type, misc sizes, panose, unicode ranges
  21020. var selection = stream.getUint16();
  21021. if (version < 4 && (selection & 0x0300)) {
  21022. return false;
  21023. }
  21024. var firstChar = stream.getUint16();
  21025. var lastChar = stream.getUint16();
  21026. if (firstChar > lastChar) {
  21027. return false;
  21028. }
  21029. stream.getBytes(6); // skipping sTypoAscender/Descender/LineGap
  21030. var usWinAscent = stream.getUint16();
  21031. if (usWinAscent === 0) { // makes font unreadable by windows
  21032. return false;
  21033. }
  21034. // OS/2 appears to be valid, resetting some fields
  21035. os2.data[8] = os2.data[9] = 0; // IE rejects fonts if fsType != 0
  21036. return true;
  21037. }
  21038. function createOS2Table(properties, charstrings, override) {
  21039. override = override || {
  21040. unitsPerEm: 0,
  21041. yMax: 0,
  21042. yMin: 0,
  21043. ascent: 0,
  21044. descent: 0
  21045. };
  21046. var ulUnicodeRange1 = 0;
  21047. var ulUnicodeRange2 = 0;
  21048. var ulUnicodeRange3 = 0;
  21049. var ulUnicodeRange4 = 0;
  21050. var firstCharIndex = null;
  21051. var lastCharIndex = 0;
  21052. if (charstrings) {
  21053. for (var code in charstrings) {
  21054. code |= 0;
  21055. if (firstCharIndex > code || !firstCharIndex) {
  21056. firstCharIndex = code;
  21057. }
  21058. if (lastCharIndex < code) {
  21059. lastCharIndex = code;
  21060. }
  21061. var position = getUnicodeRangeFor(code);
  21062. if (position < 32) {
  21063. ulUnicodeRange1 |= 1 << position;
  21064. } else if (position < 64) {
  21065. ulUnicodeRange2 |= 1 << position - 32;
  21066. } else if (position < 96) {
  21067. ulUnicodeRange3 |= 1 << position - 64;
  21068. } else if (position < 123) {
  21069. ulUnicodeRange4 |= 1 << position - 96;
  21070. } else {
  21071. error('Unicode ranges Bits > 123 are reserved for internal usage');
  21072. }
  21073. }
  21074. } else {
  21075. // TODO
  21076. firstCharIndex = 0;
  21077. lastCharIndex = 255;
  21078. }
  21079. var bbox = properties.bbox || [0, 0, 0, 0];
  21080. var unitsPerEm = (override.unitsPerEm ||
  21081. 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0]);
  21082. // if the font units differ to the PDF glyph space units
  21083. // then scale up the values
  21084. var scale = (properties.ascentScaled ? 1.0 :
  21085. unitsPerEm / PDF_GLYPH_SPACE_UNITS);
  21086. var typoAscent = (override.ascent ||
  21087. Math.round(scale * (properties.ascent || bbox[3])));
  21088. var typoDescent = (override.descent ||
  21089. Math.round(scale * (properties.descent || bbox[1])));
  21090. if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
  21091. typoDescent = -typoDescent; // fixing incorrect descent
  21092. }
  21093. var winAscent = override.yMax || typoAscent;
  21094. var winDescent = -override.yMin || -typoDescent;
  21095. return '\x00\x03' + // version
  21096. '\x02\x24' + // xAvgCharWidth
  21097. '\x01\xF4' + // usWeightClass
  21098. '\x00\x05' + // usWidthClass
  21099. '\x00\x00' + // fstype (0 to let the font loads via font-face on IE)
  21100. '\x02\x8A' + // ySubscriptXSize
  21101. '\x02\xBB' + // ySubscriptYSize
  21102. '\x00\x00' + // ySubscriptXOffset
  21103. '\x00\x8C' + // ySubscriptYOffset
  21104. '\x02\x8A' + // ySuperScriptXSize
  21105. '\x02\xBB' + // ySuperScriptYSize
  21106. '\x00\x00' + // ySuperScriptXOffset
  21107. '\x01\xDF' + // ySuperScriptYOffset
  21108. '\x00\x31' + // yStrikeOutSize
  21109. '\x01\x02' + // yStrikeOutPosition
  21110. '\x00\x00' + // sFamilyClass
  21111. '\x00\x00\x06' +
  21112. String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) +
  21113. '\x00\x00\x00\x00\x00\x00' + // Panose
  21114. string32(ulUnicodeRange1) + // ulUnicodeRange1 (Bits 0-31)
  21115. string32(ulUnicodeRange2) + // ulUnicodeRange2 (Bits 32-63)
  21116. string32(ulUnicodeRange3) + // ulUnicodeRange3 (Bits 64-95)
  21117. string32(ulUnicodeRange4) + // ulUnicodeRange4 (Bits 96-127)
  21118. '\x2A\x32\x31\x2A' + // achVendID
  21119. string16(properties.italicAngle ? 1 : 0) + // fsSelection
  21120. string16(firstCharIndex ||
  21121. properties.firstChar) + // usFirstCharIndex
  21122. string16(lastCharIndex || properties.lastChar) + // usLastCharIndex
  21123. string16(typoAscent) + // sTypoAscender
  21124. string16(typoDescent) + // sTypoDescender
  21125. '\x00\x64' + // sTypoLineGap (7%-10% of the unitsPerEM value)
  21126. string16(winAscent) + // usWinAscent
  21127. string16(winDescent) + // usWinDescent
  21128. '\x00\x00\x00\x00' + // ulCodePageRange1 (Bits 0-31)
  21129. '\x00\x00\x00\x00' + // ulCodePageRange2 (Bits 32-63)
  21130. string16(properties.xHeight) + // sxHeight
  21131. string16(properties.capHeight) + // sCapHeight
  21132. string16(0) + // usDefaultChar
  21133. string16(firstCharIndex || properties.firstChar) + // usBreakChar
  21134. '\x00\x03'; // usMaxContext
  21135. }
  21136. function createPostTable(properties) {
  21137. var angle = Math.floor(properties.italicAngle * (Math.pow(2, 16)));
  21138. return ('\x00\x03\x00\x00' + // Version number
  21139. string32(angle) + // italicAngle
  21140. '\x00\x00' + // underlinePosition
  21141. '\x00\x00' + // underlineThickness
  21142. string32(properties.fixedPitch) + // isFixedPitch
  21143. '\x00\x00\x00\x00' + // minMemType42
  21144. '\x00\x00\x00\x00' + // maxMemType42
  21145. '\x00\x00\x00\x00' + // minMemType1
  21146. '\x00\x00\x00\x00'); // maxMemType1
  21147. }
  21148. function createNameTable(name, proto) {
  21149. if (!proto) {
  21150. proto = [[], []]; // no strings and unicode strings
  21151. }
  21152. var strings = [
  21153. proto[0][0] || 'Original licence', // 0.Copyright
  21154. proto[0][1] || name, // 1.Font family
  21155. proto[0][2] || 'Unknown', // 2.Font subfamily (font weight)
  21156. proto[0][3] || 'uniqueID', // 3.Unique ID
  21157. proto[0][4] || name, // 4.Full font name
  21158. proto[0][5] || 'Version 0.11', // 5.Version
  21159. proto[0][6] || '', // 6.Postscript name
  21160. proto[0][7] || 'Unknown', // 7.Trademark
  21161. proto[0][8] || 'Unknown', // 8.Manufacturer
  21162. proto[0][9] || 'Unknown' // 9.Designer
  21163. ];
  21164. // Mac want 1-byte per character strings while Windows want
  21165. // 2-bytes per character, so duplicate the names table
  21166. var stringsUnicode = [];
  21167. var i, ii, j, jj, str;
  21168. for (i = 0, ii = strings.length; i < ii; i++) {
  21169. str = proto[1][i] || strings[i];
  21170. var strBufUnicode = [];
  21171. for (j = 0, jj = str.length; j < jj; j++) {
  21172. strBufUnicode.push(string16(str.charCodeAt(j)));
  21173. }
  21174. stringsUnicode.push(strBufUnicode.join(''));
  21175. }
  21176. var names = [strings, stringsUnicode];
  21177. var platforms = ['\x00\x01', '\x00\x03'];
  21178. var encodings = ['\x00\x00', '\x00\x01'];
  21179. var languages = ['\x00\x00', '\x04\x09'];
  21180. var namesRecordCount = strings.length * platforms.length;
  21181. var nameTable =
  21182. '\x00\x00' + // format
  21183. string16(namesRecordCount) + // Number of names Record
  21184. string16(namesRecordCount * 12 + 6); // Storage
  21185. // Build the name records field
  21186. var strOffset = 0;
  21187. for (i = 0, ii = platforms.length; i < ii; i++) {
  21188. var strs = names[i];
  21189. for (j = 0, jj = strs.length; j < jj; j++) {
  21190. str = strs[j];
  21191. var nameRecord =
  21192. platforms[i] + // platform ID
  21193. encodings[i] + // encoding ID
  21194. languages[i] + // language ID
  21195. string16(j) + // name ID
  21196. string16(str.length) +
  21197. string16(strOffset);
  21198. nameTable += nameRecord;
  21199. strOffset += str.length;
  21200. }
  21201. }
  21202. nameTable += strings.join('') + stringsUnicode.join('');
  21203. return nameTable;
  21204. }
  21205. Font.prototype = {
  21206. name: null,
  21207. font: null,
  21208. mimetype: null,
  21209. encoding: null,
  21210. get renderer() {
  21211. var renderer = FontRendererFactory.create(this);
  21212. return shadow(this, 'renderer', renderer);
  21213. },
  21214. exportData: function Font_exportData() {
  21215. var data = {};
  21216. for (var i in this) {
  21217. if (this.hasOwnProperty(i)) {
  21218. data[i] = this[i];
  21219. }
  21220. }
  21221. return data;
  21222. },
  21223. checkAndRepair: function Font_checkAndRepair(name, font, properties) {
  21224. function readTableEntry(file) {
  21225. var tag = bytesToString(file.getBytes(4));
  21226. var checksum = file.getInt32();
  21227. var offset = file.getInt32() >>> 0;
  21228. var length = file.getInt32() >>> 0;
  21229. // Read the table associated data
  21230. var previousPosition = file.pos;
  21231. file.pos = file.start ? file.start : 0;
  21232. file.skip(offset);
  21233. var data = file.getBytes(length);
  21234. file.pos = previousPosition;
  21235. if (tag === 'head') {
  21236. // clearing checksum adjustment
  21237. data[8] = data[9] = data[10] = data[11] = 0;
  21238. data[17] |= 0x20; //Set font optimized for cleartype flag
  21239. }
  21240. return {
  21241. tag: tag,
  21242. checksum: checksum,
  21243. length: length,
  21244. offset: offset,
  21245. data: data
  21246. };
  21247. }
  21248. function readOpenTypeHeader(ttf) {
  21249. return {
  21250. version: bytesToString(ttf.getBytes(4)),
  21251. numTables: ttf.getUint16(),
  21252. searchRange: ttf.getUint16(),
  21253. entrySelector: ttf.getUint16(),
  21254. rangeShift: ttf.getUint16()
  21255. };
  21256. }
  21257. /**
  21258. * Read the appropriate subtable from the cmap according to 9.6.6.4 from
  21259. * PDF spec
  21260. */
  21261. function readCmapTable(cmap, font, isSymbolicFont) {
  21262. var segment;
  21263. var start = (font.start ? font.start : 0) + cmap.offset;
  21264. font.pos = start;
  21265. var version = font.getUint16();
  21266. var numTables = font.getUint16();
  21267. var potentialTable;
  21268. var canBreak = false;
  21269. // There's an order of preference in terms of which cmap subtable to
  21270. // use:
  21271. // - non-symbolic fonts the preference is a 3,1 table then a 1,0 table
  21272. // - symbolic fonts the preference is a 3,0 table then a 1,0 table
  21273. // The following takes advantage of the fact that the tables are sorted
  21274. // to work.
  21275. for (var i = 0; i < numTables; i++) {
  21276. var platformId = font.getUint16();
  21277. var encodingId = font.getUint16();
  21278. var offset = font.getInt32() >>> 0;
  21279. var useTable = false;
  21280. if (platformId === 1 && encodingId === 0) {
  21281. useTable = true;
  21282. // Continue the loop since there still may be a higher priority
  21283. // table.
  21284. } else if (!isSymbolicFont && platformId === 3 && encodingId === 1) {
  21285. useTable = true;
  21286. canBreak = true;
  21287. } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
  21288. useTable = true;
  21289. canBreak = true;
  21290. }
  21291. if (useTable) {
  21292. potentialTable = {
  21293. platformId: platformId,
  21294. encodingId: encodingId,
  21295. offset: offset
  21296. };
  21297. }
  21298. if (canBreak) {
  21299. break;
  21300. }
  21301. }
  21302. if (!potentialTable) {
  21303. warn('Could not find a preferred cmap table.');
  21304. return {
  21305. platformId: -1,
  21306. encodingId: -1,
  21307. mappings: [],
  21308. hasShortCmap: false
  21309. };
  21310. }
  21311. font.pos = start + potentialTable.offset;
  21312. var format = font.getUint16();
  21313. var length = font.getUint16();
  21314. var language = font.getUint16();
  21315. var hasShortCmap = false;
  21316. var mappings = [];
  21317. var j, glyphId;
  21318. // TODO(mack): refactor this cmap subtable reading logic out
  21319. if (format === 0) {
  21320. for (j = 0; j < 256; j++) {
  21321. var index = font.getByte();
  21322. if (!index) {
  21323. continue;
  21324. }
  21325. mappings.push({
  21326. charCode: j,
  21327. glyphId: index
  21328. });
  21329. }
  21330. hasShortCmap = true;
  21331. } else if (format === 4) {
  21332. // re-creating the table in format 4 since the encoding
  21333. // might be changed
  21334. var segCount = (font.getUint16() >> 1);
  21335. font.getBytes(6); // skipping range fields
  21336. var segIndex, segments = [];
  21337. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21338. segments.push({ end: font.getUint16() });
  21339. }
  21340. font.getUint16();
  21341. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21342. segments[segIndex].start = font.getUint16();
  21343. }
  21344. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21345. segments[segIndex].delta = font.getUint16();
  21346. }
  21347. var offsetsCount = 0;
  21348. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21349. segment = segments[segIndex];
  21350. var rangeOffset = font.getUint16();
  21351. if (!rangeOffset) {
  21352. segment.offsetIndex = -1;
  21353. continue;
  21354. }
  21355. var offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
  21356. segment.offsetIndex = offsetIndex;
  21357. offsetsCount = Math.max(offsetsCount, offsetIndex +
  21358. segment.end - segment.start + 1);
  21359. }
  21360. var offsets = [];
  21361. for (j = 0; j < offsetsCount; j++) {
  21362. offsets.push(font.getUint16());
  21363. }
  21364. for (segIndex = 0; segIndex < segCount; segIndex++) {
  21365. segment = segments[segIndex];
  21366. start = segment.start;
  21367. var end = segment.end;
  21368. var delta = segment.delta;
  21369. offsetIndex = segment.offsetIndex;
  21370. for (j = start; j <= end; j++) {
  21371. if (j === 0xFFFF) {
  21372. continue;
  21373. }
  21374. glyphId = (offsetIndex < 0 ?
  21375. j : offsets[offsetIndex + j - start]);
  21376. glyphId = (glyphId + delta) & 0xFFFF;
  21377. if (glyphId === 0) {
  21378. continue;
  21379. }
  21380. mappings.push({
  21381. charCode: j,
  21382. glyphId: glyphId
  21383. });
  21384. }
  21385. }
  21386. } else if (format === 6) {
  21387. // Format 6 is a 2-bytes dense mapping, which means the font data
  21388. // lives glue together even if they are pretty far in the unicode
  21389. // table. (This looks weird, so I can have missed something), this
  21390. // works on Linux but seems to fails on Mac so let's rewrite the
  21391. // cmap table to a 3-1-4 style
  21392. var firstCode = font.getUint16();
  21393. var entryCount = font.getUint16();
  21394. for (j = 0; j < entryCount; j++) {
  21395. glyphId = font.getUint16();
  21396. var charCode = firstCode + j;
  21397. mappings.push({
  21398. charCode: charCode,
  21399. glyphId: glyphId
  21400. });
  21401. }
  21402. } else {
  21403. error('cmap table has unsupported format: ' + format);
  21404. }
  21405. // removing duplicate entries
  21406. mappings.sort(function (a, b) {
  21407. return a.charCode - b.charCode;
  21408. });
  21409. for (i = 1; i < mappings.length; i++) {
  21410. if (mappings[i - 1].charCode === mappings[i].charCode) {
  21411. mappings.splice(i, 1);
  21412. i--;
  21413. }
  21414. }
  21415. return {
  21416. platformId: potentialTable.platformId,
  21417. encodingId: potentialTable.encodingId,
  21418. mappings: mappings,
  21419. hasShortCmap: hasShortCmap
  21420. };
  21421. }
  21422. function sanitizeMetrics(font, header, metrics, numGlyphs) {
  21423. if (!header) {
  21424. if (metrics) {
  21425. metrics.data = null;
  21426. }
  21427. return;
  21428. }
  21429. font.pos = (font.start ? font.start : 0) + header.offset;
  21430. font.pos += header.length - 2;
  21431. var numOfMetrics = font.getUint16();
  21432. if (numOfMetrics > numGlyphs) {
  21433. info('The numOfMetrics (' + numOfMetrics + ') should not be ' +
  21434. 'greater than the numGlyphs (' + numGlyphs + ')');
  21435. // Reduce numOfMetrics if it is greater than numGlyphs
  21436. numOfMetrics = numGlyphs;
  21437. header.data[34] = (numOfMetrics & 0xff00) >> 8;
  21438. header.data[35] = numOfMetrics & 0x00ff;
  21439. }
  21440. var numOfSidebearings = numGlyphs - numOfMetrics;
  21441. var numMissing = numOfSidebearings -
  21442. ((metrics.length - numOfMetrics * 4) >> 1);
  21443. if (numMissing > 0) {
  21444. // For each missing glyph, we set both the width and lsb to 0 (zero).
  21445. // Since we need to add two properties for each glyph, this explains
  21446. // the use of |numMissing * 2| when initializing the typed array.
  21447. var entries = new Uint8Array(metrics.length + numMissing * 2);
  21448. entries.set(metrics.data);
  21449. metrics.data = entries;
  21450. }
  21451. }
  21452. function sanitizeGlyph(source, sourceStart, sourceEnd, dest, destStart,
  21453. hintsValid) {
  21454. if (sourceEnd - sourceStart <= 12) {
  21455. // glyph with data less than 12 is invalid one
  21456. return 0;
  21457. }
  21458. var glyf = source.subarray(sourceStart, sourceEnd);
  21459. var contoursCount = (glyf[0] << 8) | glyf[1];
  21460. if (contoursCount & 0x8000) {
  21461. // complex glyph, writing as is
  21462. dest.set(glyf, destStart);
  21463. return glyf.length;
  21464. }
  21465. var i, j = 10, flagsCount = 0;
  21466. for (i = 0; i < contoursCount; i++) {
  21467. var endPoint = (glyf[j] << 8) | glyf[j + 1];
  21468. flagsCount = endPoint + 1;
  21469. j += 2;
  21470. }
  21471. // skipping instructions
  21472. var instructionsStart = j;
  21473. var instructionsLength = (glyf[j] << 8) | glyf[j + 1];
  21474. j += 2 + instructionsLength;
  21475. var instructionsEnd = j;
  21476. // validating flags
  21477. var coordinatesLength = 0;
  21478. for (i = 0; i < flagsCount; i++) {
  21479. var flag = glyf[j++];
  21480. if (flag & 0xC0) {
  21481. // reserved flags must be zero, cleaning up
  21482. glyf[j - 1] = flag & 0x3F;
  21483. }
  21484. var xyLength = ((flag & 2) ? 1 : (flag & 16) ? 0 : 2) +
  21485. ((flag & 4) ? 1 : (flag & 32) ? 0 : 2);
  21486. coordinatesLength += xyLength;
  21487. if (flag & 8) {
  21488. var repeat = glyf[j++];
  21489. i += repeat;
  21490. coordinatesLength += repeat * xyLength;
  21491. }
  21492. }
  21493. // glyph without coordinates will be rejected
  21494. if (coordinatesLength === 0) {
  21495. return 0;
  21496. }
  21497. var glyphDataLength = j + coordinatesLength;
  21498. if (glyphDataLength > glyf.length) {
  21499. // not enough data for coordinates
  21500. return 0;
  21501. }
  21502. if (!hintsValid && instructionsLength > 0) {
  21503. dest.set(glyf.subarray(0, instructionsStart), destStart);
  21504. dest.set([0, 0], destStart + instructionsStart);
  21505. dest.set(glyf.subarray(instructionsEnd, glyphDataLength),
  21506. destStart + instructionsStart + 2);
  21507. glyphDataLength -= instructionsLength;
  21508. if (glyf.length - glyphDataLength > 3) {
  21509. glyphDataLength = (glyphDataLength + 3) & ~3;
  21510. }
  21511. return glyphDataLength;
  21512. }
  21513. if (glyf.length - glyphDataLength > 3) {
  21514. // truncating and aligning to 4 bytes the long glyph data
  21515. glyphDataLength = (glyphDataLength + 3) & ~3;
  21516. dest.set(glyf.subarray(0, glyphDataLength), destStart);
  21517. return glyphDataLength;
  21518. }
  21519. // glyph data is fine
  21520. dest.set(glyf, destStart);
  21521. return glyf.length;
  21522. }
  21523. function sanitizeHead(head, numGlyphs, locaLength) {
  21524. var data = head.data;
  21525. // Validate version:
  21526. // Should always be 0x00010000
  21527. var version = int32(data[0], data[1], data[2], data[3]);
  21528. if (version >> 16 !== 1) {
  21529. info('Attempting to fix invalid version in head table: ' + version);
  21530. data[0] = 0;
  21531. data[1] = 1;
  21532. data[2] = 0;
  21533. data[3] = 0;
  21534. }
  21535. var indexToLocFormat = int16(data[50], data[51]);
  21536. if (indexToLocFormat < 0 || indexToLocFormat > 1) {
  21537. info('Attempting to fix invalid indexToLocFormat in head table: ' +
  21538. indexToLocFormat);
  21539. // The value of indexToLocFormat should be 0 if the loca table
  21540. // consists of short offsets, and should be 1 if the loca table
  21541. // consists of long offsets.
  21542. //
  21543. // The number of entries in the loca table should be numGlyphs + 1.
  21544. //
  21545. // Using this information, we can work backwards to deduce if the
  21546. // size of each offset in the loca table, and thus figure out the
  21547. // appropriate value for indexToLocFormat.
  21548. var numGlyphsPlusOne = numGlyphs + 1;
  21549. if (locaLength === numGlyphsPlusOne << 1) {
  21550. // 0x0000 indicates the loca table consists of short offsets
  21551. data[50] = 0;
  21552. data[51] = 0;
  21553. } else if (locaLength === numGlyphsPlusOne << 2) {
  21554. // 0x0001 indicates the loca table consists of long offsets
  21555. data[50] = 0;
  21556. data[51] = 1;
  21557. } else {
  21558. warn('Could not fix indexToLocFormat: ' + indexToLocFormat);
  21559. }
  21560. }
  21561. }
  21562. function sanitizeGlyphLocations(loca, glyf, numGlyphs,
  21563. isGlyphLocationsLong, hintsValid,
  21564. dupFirstEntry) {
  21565. var itemSize, itemDecode, itemEncode;
  21566. if (isGlyphLocationsLong) {
  21567. itemSize = 4;
  21568. itemDecode = function fontItemDecodeLong(data, offset) {
  21569. return (data[offset] << 24) | (data[offset + 1] << 16) |
  21570. (data[offset + 2] << 8) | data[offset + 3];
  21571. };
  21572. itemEncode = function fontItemEncodeLong(data, offset, value) {
  21573. data[offset] = (value >>> 24) & 0xFF;
  21574. data[offset + 1] = (value >> 16) & 0xFF;
  21575. data[offset + 2] = (value >> 8) & 0xFF;
  21576. data[offset + 3] = value & 0xFF;
  21577. };
  21578. } else {
  21579. itemSize = 2;
  21580. itemDecode = function fontItemDecode(data, offset) {
  21581. return (data[offset] << 9) | (data[offset + 1] << 1);
  21582. };
  21583. itemEncode = function fontItemEncode(data, offset, value) {
  21584. data[offset] = (value >> 9) & 0xFF;
  21585. data[offset + 1] = (value >> 1) & 0xFF;
  21586. };
  21587. }
  21588. var locaData = loca.data;
  21589. var locaDataSize = itemSize * (1 + numGlyphs);
  21590. // is loca.data too short or long?
  21591. if (locaData.length !== locaDataSize) {
  21592. locaData = new Uint8Array(locaDataSize);
  21593. locaData.set(loca.data.subarray(0, locaDataSize));
  21594. loca.data = locaData;
  21595. }
  21596. // removing the invalid glyphs
  21597. var oldGlyfData = glyf.data;
  21598. var oldGlyfDataLength = oldGlyfData.length;
  21599. var newGlyfData = new Uint8Array(oldGlyfDataLength);
  21600. var startOffset = itemDecode(locaData, 0);
  21601. var writeOffset = 0;
  21602. itemEncode(locaData, 0, writeOffset);
  21603. var i, j;
  21604. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  21605. var endOffset = itemDecode(locaData, j);
  21606. if (endOffset > oldGlyfDataLength &&
  21607. ((oldGlyfDataLength + 3) & ~3) === endOffset) {
  21608. // Aspose breaks fonts by aligning the glyphs to the qword, but not
  21609. // the glyf table size, which makes last glyph out of range.
  21610. endOffset = oldGlyfDataLength;
  21611. }
  21612. if (endOffset > oldGlyfDataLength) {
  21613. // glyph end offset points outside glyf data, rejecting the glyph
  21614. itemEncode(locaData, j, writeOffset);
  21615. startOffset = endOffset;
  21616. continue;
  21617. }
  21618. var newLength = sanitizeGlyph(oldGlyfData, startOffset, endOffset,
  21619. newGlyfData, writeOffset, hintsValid);
  21620. writeOffset += newLength;
  21621. itemEncode(locaData, j, writeOffset);
  21622. startOffset = endOffset;
  21623. }
  21624. if (writeOffset === 0) {
  21625. // glyf table cannot be empty -- redoing the glyf and loca tables
  21626. // to have single glyph with one point
  21627. var simpleGlyph = new Uint8Array(
  21628. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);
  21629. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  21630. itemEncode(locaData, j, simpleGlyph.length);
  21631. }
  21632. glyf.data = simpleGlyph;
  21633. return;
  21634. }
  21635. if (dupFirstEntry) {
  21636. var firstEntryLength = itemDecode(locaData, itemSize);
  21637. if (newGlyfData.length > firstEntryLength + writeOffset) {
  21638. glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);
  21639. } else {
  21640. glyf.data = new Uint8Array(firstEntryLength + writeOffset);
  21641. glyf.data.set(newGlyfData.subarray(0, writeOffset));
  21642. }
  21643. glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);
  21644. itemEncode(loca.data, locaData.length - itemSize,
  21645. writeOffset + firstEntryLength);
  21646. } else {
  21647. glyf.data = newGlyfData.subarray(0, writeOffset);
  21648. }
  21649. }
  21650. function readPostScriptTable(post, properties, maxpNumGlyphs) {
  21651. var start = (font.start ? font.start : 0) + post.offset;
  21652. font.pos = start;
  21653. var length = post.length, end = start + length;
  21654. var version = font.getInt32();
  21655. // skip rest to the tables
  21656. font.getBytes(28);
  21657. var glyphNames;
  21658. var valid = true;
  21659. var i;
  21660. switch (version) {
  21661. case 0x00010000:
  21662. glyphNames = MacStandardGlyphOrdering;
  21663. break;
  21664. case 0x00020000:
  21665. var numGlyphs = font.getUint16();
  21666. if (numGlyphs !== maxpNumGlyphs) {
  21667. valid = false;
  21668. break;
  21669. }
  21670. var glyphNameIndexes = [];
  21671. for (i = 0; i < numGlyphs; ++i) {
  21672. var index = font.getUint16();
  21673. if (index >= 32768) {
  21674. valid = false;
  21675. break;
  21676. }
  21677. glyphNameIndexes.push(index);
  21678. }
  21679. if (!valid) {
  21680. break;
  21681. }
  21682. var customNames = [];
  21683. var strBuf = [];
  21684. while (font.pos < end) {
  21685. var stringLength = font.getByte();
  21686. strBuf.length = stringLength;
  21687. for (i = 0; i < stringLength; ++i) {
  21688. strBuf[i] = String.fromCharCode(font.getByte());
  21689. }
  21690. customNames.push(strBuf.join(''));
  21691. }
  21692. glyphNames = [];
  21693. for (i = 0; i < numGlyphs; ++i) {
  21694. var j = glyphNameIndexes[i];
  21695. if (j < 258) {
  21696. glyphNames.push(MacStandardGlyphOrdering[j]);
  21697. continue;
  21698. }
  21699. glyphNames.push(customNames[j - 258]);
  21700. }
  21701. break;
  21702. case 0x00030000:
  21703. break;
  21704. default:
  21705. warn('Unknown/unsupported post table version ' + version);
  21706. valid = false;
  21707. break;
  21708. }
  21709. properties.glyphNames = glyphNames;
  21710. return valid;
  21711. }
  21712. function readNameTable(nameTable) {
  21713. var start = (font.start ? font.start : 0) + nameTable.offset;
  21714. font.pos = start;
  21715. var names = [[], []];
  21716. var length = nameTable.length, end = start + length;
  21717. var format = font.getUint16();
  21718. var FORMAT_0_HEADER_LENGTH = 6;
  21719. if (format !== 0 || length < FORMAT_0_HEADER_LENGTH) {
  21720. // unsupported name table format or table "too" small
  21721. return names;
  21722. }
  21723. var numRecords = font.getUint16();
  21724. var stringsStart = font.getUint16();
  21725. var records = [];
  21726. var NAME_RECORD_LENGTH = 12;
  21727. var i, ii;
  21728. for (i = 0; i < numRecords &&
  21729. font.pos + NAME_RECORD_LENGTH <= end; i++) {
  21730. var r = {
  21731. platform: font.getUint16(),
  21732. encoding: font.getUint16(),
  21733. language: font.getUint16(),
  21734. name: font.getUint16(),
  21735. length: font.getUint16(),
  21736. offset: font.getUint16()
  21737. };
  21738. // using only Macintosh and Windows platform/encoding names
  21739. if ((r.platform === 1 && r.encoding === 0 && r.language === 0) ||
  21740. (r.platform === 3 && r.encoding === 1 && r.language === 0x409)) {
  21741. records.push(r);
  21742. }
  21743. }
  21744. for (i = 0, ii = records.length; i < ii; i++) {
  21745. var record = records[i];
  21746. var pos = start + stringsStart + record.offset;
  21747. if (pos + record.length > end) {
  21748. continue; // outside of name table, ignoring
  21749. }
  21750. font.pos = pos;
  21751. var nameIndex = record.name;
  21752. if (record.encoding) {
  21753. // unicode
  21754. var str = '';
  21755. for (var j = 0, jj = record.length; j < jj; j += 2) {
  21756. str += String.fromCharCode(font.getUint16());
  21757. }
  21758. names[1][nameIndex] = str;
  21759. } else {
  21760. names[0][nameIndex] = bytesToString(font.getBytes(record.length));
  21761. }
  21762. }
  21763. return names;
  21764. }
  21765. var TTOpsStackDeltas = [
  21766. 0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, 0, 0, -2, -5,
  21767. -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, -1, -1,
  21768. 1, -1, -999, 0, 1, 0, -1, -2, 0, -1, -2, -1, -1, 0, -1, -1,
  21769. 0, 0, -999, -999, -1, -1, -1, -1, -2, -999, -2, -2, -999, 0, -2, -2,
  21770. 0, 0, -2, 0, -2, 0, 0, 0, -2, -1, -1, 1, 1, 0, 0, -1,
  21771. -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, -999, -1, -1,
  21772. -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  21773. -2, -999, -999, -999, -999, -999, -1, -1, -2, -2, 0, 0, 0, 0, -1, -1,
  21774. -999, -2, -2, 0, 0, -1, -2, -2, 0, 0, 0, -1, -1, -1, -2];
  21775. // 0xC0-DF == -1 and 0xE0-FF == -2
  21776. function sanitizeTTProgram(table, ttContext) {
  21777. var data = table.data;
  21778. var i = 0, j, n, b, funcId, pc, lastEndf = 0, lastDeff = 0;
  21779. var stack = [];
  21780. var callstack = [];
  21781. var functionsCalled = [];
  21782. var tooComplexToFollowFunctions =
  21783. ttContext.tooComplexToFollowFunctions;
  21784. var inFDEF = false, ifLevel = 0, inELSE = 0;
  21785. for (var ii = data.length; i < ii;) {
  21786. var op = data[i++];
  21787. // The TrueType instruction set docs can be found at
  21788. // https://developer.apple.com/fonts/TTRefMan/RM05/Chap5.html
  21789. if (op === 0x40) { // NPUSHB - pushes n bytes
  21790. n = data[i++];
  21791. if (inFDEF || inELSE) {
  21792. i += n;
  21793. } else {
  21794. for (j = 0; j < n; j++) {
  21795. stack.push(data[i++]);
  21796. }
  21797. }
  21798. } else if (op === 0x41) { // NPUSHW - pushes n words
  21799. n = data[i++];
  21800. if (inFDEF || inELSE) {
  21801. i += n * 2;
  21802. } else {
  21803. for (j = 0; j < n; j++) {
  21804. b = data[i++];
  21805. stack.push((b << 8) | data[i++]);
  21806. }
  21807. }
  21808. } else if ((op & 0xF8) === 0xB0) { // PUSHB - pushes bytes
  21809. n = op - 0xB0 + 1;
  21810. if (inFDEF || inELSE) {
  21811. i += n;
  21812. } else {
  21813. for (j = 0; j < n; j++) {
  21814. stack.push(data[i++]);
  21815. }
  21816. }
  21817. } else if ((op & 0xF8) === 0xB8) { // PUSHW - pushes words
  21818. n = op - 0xB8 + 1;
  21819. if (inFDEF || inELSE) {
  21820. i += n * 2;
  21821. } else {
  21822. for (j = 0; j < n; j++) {
  21823. b = data[i++];
  21824. stack.push((b << 8) | data[i++]);
  21825. }
  21826. }
  21827. } else if (op === 0x2B && !tooComplexToFollowFunctions) { // CALL
  21828. if (!inFDEF && !inELSE) {
  21829. // collecting inforamtion about which functions are used
  21830. funcId = stack[stack.length - 1];
  21831. ttContext.functionsUsed[funcId] = true;
  21832. if (funcId in ttContext.functionsStackDeltas) {
  21833. stack.length += ttContext.functionsStackDeltas[funcId];
  21834. } else if (funcId in ttContext.functionsDefined &&
  21835. functionsCalled.indexOf(funcId) < 0) {
  21836. callstack.push({data: data, i: i, stackTop: stack.length - 1});
  21837. functionsCalled.push(funcId);
  21838. pc = ttContext.functionsDefined[funcId];
  21839. if (!pc) {
  21840. warn('TT: CALL non-existent function');
  21841. ttContext.hintsValid = false;
  21842. return;
  21843. }
  21844. data = pc.data;
  21845. i = pc.i;
  21846. }
  21847. }
  21848. } else if (op === 0x2C && !tooComplexToFollowFunctions) { // FDEF
  21849. if (inFDEF || inELSE) {
  21850. warn('TT: nested FDEFs not allowed');
  21851. tooComplexToFollowFunctions = true;
  21852. }
  21853. inFDEF = true;
  21854. // collecting inforamtion about which functions are defined
  21855. lastDeff = i;
  21856. funcId = stack.pop();
  21857. ttContext.functionsDefined[funcId] = {data: data, i: i};
  21858. } else if (op === 0x2D) { // ENDF - end of function
  21859. if (inFDEF) {
  21860. inFDEF = false;
  21861. lastEndf = i;
  21862. } else {
  21863. pc = callstack.pop();
  21864. if (!pc) {
  21865. warn('TT: ENDF bad stack');
  21866. ttContext.hintsValid = false;
  21867. return;
  21868. }
  21869. funcId = functionsCalled.pop();
  21870. data = pc.data;
  21871. i = pc.i;
  21872. ttContext.functionsStackDeltas[funcId] =
  21873. stack.length - pc.stackTop;
  21874. }
  21875. } else if (op === 0x89) { // IDEF - instruction definition
  21876. if (inFDEF || inELSE) {
  21877. warn('TT: nested IDEFs not allowed');
  21878. tooComplexToFollowFunctions = true;
  21879. }
  21880. inFDEF = true;
  21881. // recording it as a function to track ENDF
  21882. lastDeff = i;
  21883. } else if (op === 0x58) { // IF
  21884. ++ifLevel;
  21885. } else if (op === 0x1B) { // ELSE
  21886. inELSE = ifLevel;
  21887. } else if (op === 0x59) { // EIF
  21888. if (inELSE === ifLevel) {
  21889. inELSE = 0;
  21890. }
  21891. --ifLevel;
  21892. } else if (op === 0x1C) { // JMPR
  21893. if (!inFDEF && !inELSE) {
  21894. var offset = stack[stack.length - 1];
  21895. // only jumping forward to prevent infinite loop
  21896. if (offset > 0) {
  21897. i += offset - 1;
  21898. }
  21899. }
  21900. }
  21901. // Adjusting stack not extactly, but just enough to get function id
  21902. if (!inFDEF && !inELSE) {
  21903. var stackDelta = op <= 0x8E ? TTOpsStackDeltas[op] :
  21904. op >= 0xC0 && op <= 0xDF ? -1 : op >= 0xE0 ? -2 : 0;
  21905. if (op >= 0x71 && op <= 0x75) {
  21906. n = stack.pop();
  21907. if (n === n) {
  21908. stackDelta = -n * 2;
  21909. }
  21910. }
  21911. while (stackDelta < 0 && stack.length > 0) {
  21912. stack.pop();
  21913. stackDelta++;
  21914. }
  21915. while (stackDelta > 0) {
  21916. stack.push(NaN); // pushing any number into stack
  21917. stackDelta--;
  21918. }
  21919. }
  21920. }
  21921. ttContext.tooComplexToFollowFunctions = tooComplexToFollowFunctions;
  21922. var content = [data];
  21923. if (i > data.length) {
  21924. content.push(new Uint8Array(i - data.length));
  21925. }
  21926. if (lastDeff > lastEndf) {
  21927. warn('TT: complementing a missing function tail');
  21928. // new function definition started, but not finished
  21929. // complete function by [CLEAR, ENDF]
  21930. content.push(new Uint8Array([0x22, 0x2D]));
  21931. }
  21932. foldTTTable(table, content);
  21933. }
  21934. function checkInvalidFunctions(ttContext, maxFunctionDefs) {
  21935. if (ttContext.tooComplexToFollowFunctions) {
  21936. return;
  21937. }
  21938. if (ttContext.functionsDefined.length > maxFunctionDefs) {
  21939. warn('TT: more functions defined than expected');
  21940. ttContext.hintsValid = false;
  21941. return;
  21942. }
  21943. for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
  21944. if (j > maxFunctionDefs) {
  21945. warn('TT: invalid function id: ' + j);
  21946. ttContext.hintsValid = false;
  21947. return;
  21948. }
  21949. if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
  21950. warn('TT: undefined function: ' + j);
  21951. ttContext.hintsValid = false;
  21952. return;
  21953. }
  21954. }
  21955. }
  21956. function foldTTTable(table, content) {
  21957. if (content.length > 1) {
  21958. // concatenating the content items
  21959. var newLength = 0;
  21960. var j, jj;
  21961. for (j = 0, jj = content.length; j < jj; j++) {
  21962. newLength += content[j].length;
  21963. }
  21964. newLength = (newLength + 3) & ~3;
  21965. var result = new Uint8Array(newLength);
  21966. var pos = 0;
  21967. for (j = 0, jj = content.length; j < jj; j++) {
  21968. result.set(content[j], pos);
  21969. pos += content[j].length;
  21970. }
  21971. table.data = result;
  21972. table.length = newLength;
  21973. }
  21974. }
  21975. function sanitizeTTPrograms(fpgm, prep, cvt) {
  21976. var ttContext = {
  21977. functionsDefined: [],
  21978. functionsUsed: [],
  21979. functionsStackDeltas: [],
  21980. tooComplexToFollowFunctions: false,
  21981. hintsValid: true
  21982. };
  21983. if (fpgm) {
  21984. sanitizeTTProgram(fpgm, ttContext);
  21985. }
  21986. if (prep) {
  21987. sanitizeTTProgram(prep, ttContext);
  21988. }
  21989. if (fpgm) {
  21990. checkInvalidFunctions(ttContext, maxFunctionDefs);
  21991. }
  21992. if (cvt && (cvt.length & 1)) {
  21993. var cvtData = new Uint8Array(cvt.length + 1);
  21994. cvtData.set(cvt.data);
  21995. cvt.data = cvtData;
  21996. }
  21997. return ttContext.hintsValid;
  21998. }
  21999. // The following steps modify the original font data, making copy
  22000. font = new Stream(new Uint8Array(font.getBytes()));
  22001. var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp',
  22002. 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF '];
  22003. var header = readOpenTypeHeader(font);
  22004. var numTables = header.numTables;
  22005. var cff, cffFile;
  22006. var tables = { 'OS/2': null, cmap: null, head: null, hhea: null,
  22007. hmtx: null, maxp: null, name: null, post: null };
  22008. var table;
  22009. for (var i = 0; i < numTables; i++) {
  22010. table = readTableEntry(font);
  22011. if (VALID_TABLES.indexOf(table.tag) < 0) {
  22012. continue; // skipping table if it's not a required or optional table
  22013. }
  22014. if (table.length === 0) {
  22015. continue; // skipping empty tables
  22016. }
  22017. tables[table.tag] = table;
  22018. }
  22019. var isTrueType = !tables['CFF '];
  22020. if (!isTrueType) {
  22021. // OpenType font
  22022. if (!tables.head || !tables.hhea || !tables.maxp || !tables.post) {
  22023. // no major tables: throwing everything at CFFFont
  22024. cffFile = new Stream(tables['CFF '].data);
  22025. cff = new CFFFont(cffFile, properties);
  22026. return this.convert(name, cff, properties);
  22027. }
  22028. delete tables.glyf;
  22029. delete tables.loca;
  22030. delete tables.fpgm;
  22031. delete tables.prep;
  22032. delete tables['cvt '];
  22033. this.isOpenType = true;
  22034. } else {
  22035. if (!tables.glyf || !tables.loca) {
  22036. error('Required "glyf" or "loca" tables are not found');
  22037. }
  22038. this.isOpenType = false;
  22039. }
  22040. if (!tables.maxp) {
  22041. error('Required "maxp" table is not found');
  22042. }
  22043. font.pos = (font.start || 0) + tables.maxp.offset;
  22044. var version = font.getInt32();
  22045. var numGlyphs = font.getUint16();
  22046. var maxFunctionDefs = 0;
  22047. if (version >= 0x00010000 && tables.maxp.length >= 22) {
  22048. // maxZones can be invalid
  22049. font.pos += 8;
  22050. var maxZones = font.getUint16();
  22051. if (maxZones > 2) { // reset to 2 if font has invalid maxZones
  22052. tables.maxp.data[14] = 0;
  22053. tables.maxp.data[15] = 2;
  22054. }
  22055. font.pos += 4;
  22056. maxFunctionDefs = font.getUint16();
  22057. }
  22058. var dupFirstEntry = false;
  22059. if (properties.type === 'CIDFontType2' && properties.toUnicode &&
  22060. properties.toUnicode.get(0) > '\u0000') {
  22061. // oracle's defect (see 3427), duplicating first entry
  22062. dupFirstEntry = true;
  22063. numGlyphs++;
  22064. tables.maxp.data[4] = numGlyphs >> 8;
  22065. tables.maxp.data[5] = numGlyphs & 255;
  22066. }
  22067. var hintsValid = sanitizeTTPrograms(tables.fpgm, tables.prep,
  22068. tables['cvt '], maxFunctionDefs);
  22069. if (!hintsValid) {
  22070. delete tables.fpgm;
  22071. delete tables.prep;
  22072. delete tables['cvt '];
  22073. }
  22074. // Ensure the hmtx table contains the advance width and
  22075. // sidebearings information for numGlyphs in the maxp table
  22076. sanitizeMetrics(font, tables.hhea, tables.hmtx, numGlyphs);
  22077. if (!tables.head) {
  22078. error('Required "head" table is not found');
  22079. }
  22080. sanitizeHead(tables.head, numGlyphs, isTrueType ? tables.loca.length : 0);
  22081. if (isTrueType) {
  22082. var isGlyphLocationsLong = int16(tables.head.data[50],
  22083. tables.head.data[51]);
  22084. sanitizeGlyphLocations(tables.loca, tables.glyf, numGlyphs,
  22085. isGlyphLocationsLong, hintsValid, dupFirstEntry);
  22086. }
  22087. if (!tables.hhea) {
  22088. error('Required "hhea" table is not found');
  22089. }
  22090. // Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth
  22091. // Sometimes it's 0. That needs to be fixed
  22092. if (tables.hhea.data[10] === 0 && tables.hhea.data[11] === 0) {
  22093. tables.hhea.data[10] = 0xFF;
  22094. tables.hhea.data[11] = 0xFF;
  22095. }
  22096. // The 'post' table has glyphs names.
  22097. if (tables.post) {
  22098. var valid = readPostScriptTable(tables.post, properties, numGlyphs);
  22099. if (!valid) {
  22100. tables.post = null;
  22101. }
  22102. }
  22103. var charCodeToGlyphId = [], charCode;
  22104. if (properties.type === 'CIDFontType2') {
  22105. var cidToGidMap = properties.cidToGidMap || [];
  22106. var cidToGidMapLength = cidToGidMap.length;
  22107. properties.cMap.forEach(function(charCode, cid) {
  22108. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  22109. var glyphId = -1;
  22110. if (cidToGidMapLength === 0) {
  22111. glyphId = charCode;
  22112. } else if (cidToGidMap[cid] !== undefined) {
  22113. glyphId = cidToGidMap[cid];
  22114. }
  22115. if (glyphId >= 0 && glyphId < numGlyphs) {
  22116. charCodeToGlyphId[charCode] = glyphId;
  22117. }
  22118. });
  22119. if (dupFirstEntry) {
  22120. charCodeToGlyphId[0] = numGlyphs - 1;
  22121. }
  22122. } else {
  22123. // Most of the following logic in this code branch is based on the
  22124. // 9.6.6.4 of the PDF spec.
  22125. var cmapTable = readCmapTable(tables.cmap, font, this.isSymbolicFont);
  22126. var cmapPlatformId = cmapTable.platformId;
  22127. var cmapEncodingId = cmapTable.encodingId;
  22128. var cmapMappings = cmapTable.mappings;
  22129. var cmapMappingsLength = cmapMappings.length;
  22130. var hasEncoding = properties.differences.length ||
  22131. !!properties.baseEncodingName;
  22132. // The spec seems to imply that if the font is symbolic the encoding
  22133. // should be ignored, this doesn't appear to work for 'preistabelle.pdf'
  22134. // where the the font is symbolic and it has an encoding.
  22135. if (hasEncoding &&
  22136. (cmapPlatformId === 3 && cmapEncodingId === 1 ||
  22137. cmapPlatformId === 1 && cmapEncodingId === 0) ||
  22138. (cmapPlatformId === -1 && cmapEncodingId === -1 && // Temporary hack
  22139. !!Encodings[properties.baseEncodingName])) { // Temporary hack
  22140. // When no preferred cmap table was found and |baseEncodingName| is
  22141. // one of the predefined encodings, we seem to obtain a better
  22142. // |charCodeToGlyphId| map from the code below (fixes bug 1057544).
  22143. // TODO: Note that this is a hack which should be removed as soon as
  22144. // we have proper support for more exotic cmap tables.
  22145. var baseEncoding = [];
  22146. if (properties.baseEncodingName === 'MacRomanEncoding' ||
  22147. properties.baseEncodingName === 'WinAnsiEncoding') {
  22148. baseEncoding = Encodings[properties.baseEncodingName];
  22149. }
  22150. for (charCode = 0; charCode < 256; charCode++) {
  22151. var glyphName;
  22152. if (this.differences && charCode in this.differences) {
  22153. glyphName = this.differences[charCode];
  22154. } else if (charCode in baseEncoding &&
  22155. baseEncoding[charCode] !== '') {
  22156. glyphName = baseEncoding[charCode];
  22157. } else {
  22158. glyphName = Encodings.StandardEncoding[charCode];
  22159. }
  22160. if (!glyphName) {
  22161. continue;
  22162. }
  22163. var unicodeOrCharCode;
  22164. if (cmapPlatformId === 3 && cmapEncodingId === 1) {
  22165. unicodeOrCharCode = GlyphsUnicode[glyphName];
  22166. } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {
  22167. // TODO: the encoding needs to be updated with mac os table.
  22168. unicodeOrCharCode = Encodings.MacRomanEncoding.indexOf(glyphName);
  22169. }
  22170. var found = false;
  22171. for (i = 0; i < cmapMappingsLength; ++i) {
  22172. if (cmapMappings[i].charCode === unicodeOrCharCode) {
  22173. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  22174. found = true;
  22175. break;
  22176. }
  22177. }
  22178. if (!found && properties.glyphNames) {
  22179. // Try to map using the post table. There are currently no known
  22180. // pdfs that this fixes.
  22181. var glyphId = properties.glyphNames.indexOf(glyphName);
  22182. if (glyphId > 0) {
  22183. charCodeToGlyphId[charCode] = glyphId;
  22184. }
  22185. }
  22186. }
  22187. } else {
  22188. // For (3, 0) cmap tables:
  22189. // The charcode key being stored in charCodeToGlyphId is the lower
  22190. // byte of the two-byte charcodes of the cmap table since according to
  22191. // the spec: 'each byte from the string shall be prepended with the
  22192. // high byte of the range [of charcodes in the cmap table], to form
  22193. // a two-byte character, which shall be used to select the
  22194. // associated glyph description from the subtable'.
  22195. //
  22196. // For (1, 0) cmap tables:
  22197. // 'single bytes from the string shall be used to look up the
  22198. // associated glyph descriptions from the subtable'. This means
  22199. // charcodes in the cmap will be single bytes, so no-op since
  22200. // glyph.charCode & 0xFF === glyph.charCode
  22201. for (i = 0; i < cmapMappingsLength; ++i) {
  22202. charCode = cmapMappings[i].charCode & 0xFF;
  22203. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  22204. }
  22205. }
  22206. }
  22207. if (charCodeToGlyphId.length === 0) {
  22208. // defines at least one glyph
  22209. charCodeToGlyphId[0] = 0;
  22210. }
  22211. // Converting glyphs and ids into font's cmap table
  22212. var newMapping = adjustMapping(charCodeToGlyphId, properties);
  22213. this.toFontChar = newMapping.toFontChar;
  22214. tables.cmap = {
  22215. tag: 'cmap',
  22216. data: createCmapTable(newMapping.charCodeToGlyphId)
  22217. };
  22218. if (!tables['OS/2'] || !validateOS2Table(tables['OS/2'])) {
  22219. // extract some more font properties from the OpenType head and
  22220. // hhea tables; yMin and descent value are always negative
  22221. var override = {
  22222. unitsPerEm: int16(tables.head.data[18], tables.head.data[19]),
  22223. yMax: int16(tables.head.data[42], tables.head.data[43]),
  22224. yMin: int16(tables.head.data[38], tables.head.data[39]) - 0x10000,
  22225. ascent: int16(tables.hhea.data[4], tables.hhea.data[5]),
  22226. descent: int16(tables.hhea.data[6], tables.hhea.data[7]) - 0x10000
  22227. };
  22228. tables['OS/2'] = {
  22229. tag: 'OS/2',
  22230. data: createOS2Table(properties, newMapping.charCodeToGlyphId,
  22231. override)
  22232. };
  22233. }
  22234. // Rewrite the 'post' table if needed
  22235. if (!tables.post) {
  22236. tables.post = {
  22237. tag: 'post',
  22238. data: createPostTable(properties)
  22239. };
  22240. }
  22241. if (!isTrueType) {
  22242. try {
  22243. // Trying to repair CFF file
  22244. cffFile = new Stream(tables['CFF '].data);
  22245. var parser = new CFFParser(cffFile, properties);
  22246. cff = parser.parse();
  22247. var compiler = new CFFCompiler(cff);
  22248. tables['CFF '].data = compiler.compile();
  22249. } catch (e) {
  22250. warn('Failed to compile font ' + properties.loadedName);
  22251. }
  22252. }
  22253. // Re-creating 'name' table
  22254. if (!tables.name) {
  22255. tables.name = {
  22256. tag: 'name',
  22257. data: createNameTable(this.name)
  22258. };
  22259. } else {
  22260. // ... using existing 'name' table as prototype
  22261. var namePrototype = readNameTable(tables.name);
  22262. tables.name.data = createNameTable(name, namePrototype);
  22263. }
  22264. var builder = new OpenTypeFileBuilder(header.version);
  22265. for (var tableTag in tables) {
  22266. builder.addTable(tableTag, tables[tableTag].data);
  22267. }
  22268. return builder.toArray();
  22269. },
  22270. convert: function Font_convert(fontName, font, properties) {
  22271. // TODO: Check the charstring widths to determine this.
  22272. properties.fixedPitch = false;
  22273. var mapping = font.getGlyphMapping(properties);
  22274. var newMapping = adjustMapping(mapping, properties);
  22275. this.toFontChar = newMapping.toFontChar;
  22276. var numGlyphs = font.numGlyphs;
  22277. function getCharCodes(charCodeToGlyphId, glyphId) {
  22278. var charCodes = null;
  22279. for (var charCode in charCodeToGlyphId) {
  22280. if (glyphId === charCodeToGlyphId[charCode]) {
  22281. if (!charCodes) {
  22282. charCodes = [];
  22283. }
  22284. charCodes.push(charCode | 0);
  22285. }
  22286. }
  22287. return charCodes;
  22288. }
  22289. function createCharCode(charCodeToGlyphId, glyphId) {
  22290. for (var charCode in charCodeToGlyphId) {
  22291. if (glyphId === charCodeToGlyphId[charCode]) {
  22292. return charCode | 0;
  22293. }
  22294. }
  22295. newMapping.charCodeToGlyphId[newMapping.nextAvailableFontCharCode] =
  22296. glyphId;
  22297. return newMapping.nextAvailableFontCharCode++;
  22298. }
  22299. var seacs = font.seacs;
  22300. if (SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {
  22301. var matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX;
  22302. var charset = font.getCharset();
  22303. var seacMap = Object.create(null);
  22304. for (var glyphId in seacs) {
  22305. glyphId |= 0;
  22306. var seac = seacs[glyphId];
  22307. var baseGlyphName = Encodings.StandardEncoding[seac[2]];
  22308. var accentGlyphName = Encodings.StandardEncoding[seac[3]];
  22309. var baseGlyphId = charset.indexOf(baseGlyphName);
  22310. var accentGlyphId = charset.indexOf(accentGlyphName);
  22311. if (baseGlyphId < 0 || accentGlyphId < 0) {
  22312. continue;
  22313. }
  22314. var accentOffset = {
  22315. x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],
  22316. y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5]
  22317. };
  22318. var charCodes = getCharCodes(mapping, glyphId);
  22319. if (!charCodes) {
  22320. // There's no point in mapping it if the char code was never mapped
  22321. // to begin with.
  22322. continue;
  22323. }
  22324. for (var i = 0, ii = charCodes.length; i < ii; i++) {
  22325. var charCode = charCodes[i];
  22326. // Find a fontCharCode that maps to the base and accent glyphs.
  22327. // If one doesn't exists, create it.
  22328. var charCodeToGlyphId = newMapping.charCodeToGlyphId;
  22329. var baseFontCharCode = createCharCode(charCodeToGlyphId,
  22330. baseGlyphId);
  22331. var accentFontCharCode = createCharCode(charCodeToGlyphId,
  22332. accentGlyphId);
  22333. seacMap[charCode] = {
  22334. baseFontCharCode: baseFontCharCode,
  22335. accentFontCharCode: accentFontCharCode,
  22336. accentOffset: accentOffset
  22337. };
  22338. }
  22339. }
  22340. properties.seacMap = seacMap;
  22341. }
  22342. var unitsPerEm = 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  22343. var builder = new OpenTypeFileBuilder('\x4F\x54\x54\x4F');
  22344. // PostScript Font Program
  22345. builder.addTable('CFF ', font.data);
  22346. // OS/2 and Windows Specific metrics
  22347. builder.addTable('OS/2', createOS2Table(properties,
  22348. newMapping.charCodeToGlyphId));
  22349. // Character to glyphs mapping
  22350. builder.addTable('cmap', createCmapTable(newMapping.charCodeToGlyphId));
  22351. // Font header
  22352. builder.addTable('head',
  22353. '\x00\x01\x00\x00' + // Version number
  22354. '\x00\x00\x10\x00' + // fontRevision
  22355. '\x00\x00\x00\x00' + // checksumAdjustement
  22356. '\x5F\x0F\x3C\xF5' + // magicNumber
  22357. '\x00\x00' + // Flags
  22358. safeString16(unitsPerEm) + // unitsPerEM
  22359. '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date
  22360. '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date
  22361. '\x00\x00' + // xMin
  22362. safeString16(properties.descent) + // yMin
  22363. '\x0F\xFF' + // xMax
  22364. safeString16(properties.ascent) + // yMax
  22365. string16(properties.italicAngle ? 2 : 0) + // macStyle
  22366. '\x00\x11' + // lowestRecPPEM
  22367. '\x00\x00' + // fontDirectionHint
  22368. '\x00\x00' + // indexToLocFormat
  22369. '\x00\x00'); // glyphDataFormat
  22370. // Horizontal header
  22371. builder.addTable('hhea',
  22372. '\x00\x01\x00\x00' + // Version number
  22373. safeString16(properties.ascent) + // Typographic Ascent
  22374. safeString16(properties.descent) + // Typographic Descent
  22375. '\x00\x00' + // Line Gap
  22376. '\xFF\xFF' + // advanceWidthMax
  22377. '\x00\x00' + // minLeftSidebearing
  22378. '\x00\x00' + // minRightSidebearing
  22379. '\x00\x00' + // xMaxExtent
  22380. safeString16(properties.capHeight) + // caretSlopeRise
  22381. safeString16(Math.tan(properties.italicAngle) *
  22382. properties.xHeight) + // caretSlopeRun
  22383. '\x00\x00' + // caretOffset
  22384. '\x00\x00' + // -reserved-
  22385. '\x00\x00' + // -reserved-
  22386. '\x00\x00' + // -reserved-
  22387. '\x00\x00' + // -reserved-
  22388. '\x00\x00' + // metricDataFormat
  22389. string16(numGlyphs)); // Number of HMetrics
  22390. // Horizontal metrics
  22391. builder.addTable('hmtx', (function fontFieldsHmtx() {
  22392. var charstrings = font.charstrings;
  22393. var cffWidths = font.cff ? font.cff.widths : null;
  22394. var hmtx = '\x00\x00\x00\x00'; // Fake .notdef
  22395. for (var i = 1, ii = numGlyphs; i < ii; i++) {
  22396. var width = 0;
  22397. if (charstrings) {
  22398. var charstring = charstrings[i - 1];
  22399. width = 'width' in charstring ? charstring.width : 0;
  22400. } else if (cffWidths) {
  22401. width = Math.ceil(cffWidths[i] || 0);
  22402. }
  22403. hmtx += string16(width) + string16(0);
  22404. }
  22405. return hmtx;
  22406. })());
  22407. // Maximum profile
  22408. builder.addTable('maxp',
  22409. '\x00\x00\x50\x00' + // Version number
  22410. string16(numGlyphs)); // Num of glyphs
  22411. // Naming tables
  22412. builder.addTable('name', createNameTable(fontName));
  22413. // PostScript informations
  22414. builder.addTable('post', createPostTable(properties));
  22415. return builder.toArray();
  22416. },
  22417. /**
  22418. * Builds a char code to unicode map based on section 9.10 of the spec.
  22419. * @param {Object} properties Font properties object.
  22420. * @return {Object} A ToUnicodeMap object.
  22421. */
  22422. buildToUnicode: function Font_buildToUnicode(properties) {
  22423. // Section 9.10.2 Mapping Character Codes to Unicode Values
  22424. if (properties.toUnicode && properties.toUnicode.length !== 0) {
  22425. return properties.toUnicode;
  22426. }
  22427. // According to the spec if the font is a simple font we should only map
  22428. // to unicode if the base encoding is MacRoman, MacExpert, or WinAnsi or
  22429. // the differences array only contains adobe standard or symbol set names,
  22430. // in pratice it seems better to always try to create a toUnicode
  22431. // map based of the default encoding.
  22432. var toUnicode, charcode;
  22433. if (!properties.composite /* is simple font */) {
  22434. toUnicode = [];
  22435. var encoding = properties.defaultEncoding.slice();
  22436. var baseEncodingName = properties.baseEncodingName;
  22437. // Merge in the differences array.
  22438. var differences = properties.differences;
  22439. for (charcode in differences) {
  22440. encoding[charcode] = differences[charcode];
  22441. }
  22442. for (charcode in encoding) {
  22443. // a) Map the character code to a character name.
  22444. var glyphName = encoding[charcode];
  22445. // b) Look up the character name in the Adobe Glyph List (see the
  22446. // Bibliography) to obtain the corresponding Unicode value.
  22447. if (glyphName === '') {
  22448. continue;
  22449. } else if (GlyphsUnicode[glyphName] === undefined) {
  22450. // (undocumented) c) Few heuristics to recognize unknown glyphs
  22451. // NOTE: Adobe Reader does not do this step, but OSX Preview does
  22452. var code = 0;
  22453. switch (glyphName[0]) {
  22454. case 'G': // Gxx glyph
  22455. if (glyphName.length === 3) {
  22456. code = parseInt(glyphName.substr(1), 16);
  22457. }
  22458. break;
  22459. case 'g': // g00xx glyph
  22460. if (glyphName.length === 5) {
  22461. code = parseInt(glyphName.substr(1), 16);
  22462. }
  22463. break;
  22464. case 'C': // Cddd glyph
  22465. case 'c': // cddd glyph
  22466. if (glyphName.length >= 3) {
  22467. code = +glyphName.substr(1);
  22468. }
  22469. break;
  22470. }
  22471. if (code) {
  22472. // If |baseEncodingName| is one the predefined encodings,
  22473. // and |code| equals |charcode|, using the glyph defined in the
  22474. // baseEncoding seems to yield a better |toUnicode| mapping
  22475. // (fixes issue 5070).
  22476. if (baseEncodingName && code === +charcode) {
  22477. var baseEncoding = Encodings[baseEncodingName];
  22478. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  22479. toUnicode[charcode] =
  22480. String.fromCharCode(GlyphsUnicode[glyphName]);
  22481. continue;
  22482. }
  22483. }
  22484. toUnicode[charcode] = String.fromCharCode(code);
  22485. }
  22486. continue;
  22487. }
  22488. toUnicode[charcode] = String.fromCharCode(GlyphsUnicode[glyphName]);
  22489. }
  22490. return new ToUnicodeMap(toUnicode);
  22491. }
  22492. // If the font is a composite font that uses one of the predefined CMaps
  22493. // listed in Table 118 (except Identity–H and Identity–V) or whose
  22494. // descendant CIDFont uses the Adobe-GB1, Adobe-CNS1, Adobe-Japan1, or
  22495. // Adobe-Korea1 character collection:
  22496. if (properties.composite && (
  22497. (properties.cMap.builtInCMap &&
  22498. !(properties.cMap instanceof IdentityCMap)) ||
  22499. (properties.cidSystemInfo.registry === 'Adobe' &&
  22500. (properties.cidSystemInfo.ordering === 'GB1' ||
  22501. properties.cidSystemInfo.ordering === 'CNS1' ||
  22502. properties.cidSystemInfo.ordering === 'Japan1' ||
  22503. properties.cidSystemInfo.ordering === 'Korea1')))) {
  22504. // Then:
  22505. // a) Map the character code to a character identifier (CID) according
  22506. // to the font’s CMap.
  22507. // b) Obtain the registry and ordering of the character collection used
  22508. // by the font’s CMap (for example, Adobe and Japan1) from its
  22509. // CIDSystemInfo dictionary.
  22510. var registry = properties.cidSystemInfo.registry;
  22511. var ordering = properties.cidSystemInfo.ordering;
  22512. // c) Construct a second CMap name by concatenating the registry and
  22513. // ordering obtained in step (b) in the format registry–ordering–UCS2
  22514. // (for example, Adobe–Japan1–UCS2).
  22515. var ucs2CMapName = new Name(registry + '-' + ordering + '-UCS2');
  22516. // d) Obtain the CMap with the name constructed in step (c) (available
  22517. // from the ASN Web site; see the Bibliography).
  22518. var ucs2CMap = CMapFactory.create(ucs2CMapName,
  22519. { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
  22520. var cMap = properties.cMap;
  22521. toUnicode = [];
  22522. cMap.forEach(function(charcode, cid) {
  22523. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  22524. // e) Map the CID obtained in step (a) according to the CMap obtained
  22525. // in step (d), producing a Unicode value.
  22526. var ucs2 = ucs2CMap.lookup(cid);
  22527. if (ucs2) {
  22528. toUnicode[charcode] =
  22529. String.fromCharCode((ucs2.charCodeAt(0) << 8) +
  22530. ucs2.charCodeAt(1));
  22531. }
  22532. });
  22533. return new ToUnicodeMap(toUnicode);
  22534. }
  22535. // The viewer's choice, just use an identity map.
  22536. return new IdentityToUnicodeMap(properties.firstChar,
  22537. properties.lastChar);
  22538. },
  22539. get spaceWidth() {
  22540. if ('_shadowWidth' in this) {
  22541. return this._shadowWidth;
  22542. }
  22543. // trying to estimate space character width
  22544. var possibleSpaceReplacements = ['space', 'minus', 'one', 'i'];
  22545. var width;
  22546. for (var i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) {
  22547. var glyphName = possibleSpaceReplacements[i];
  22548. // if possible, getting width by glyph name
  22549. if (glyphName in this.widths) {
  22550. width = this.widths[glyphName];
  22551. break;
  22552. }
  22553. var glyphUnicode = GlyphsUnicode[glyphName];
  22554. // finding the charcode via unicodeToCID map
  22555. var charcode = 0;
  22556. if (this.composite) {
  22557. if (this.cMap.contains(glyphUnicode)) {
  22558. charcode = this.cMap.lookup(glyphUnicode);
  22559. }
  22560. }
  22561. // ... via toUnicode map
  22562. if (!charcode && 'toUnicode' in this) {
  22563. charcode = this.toUnicode.charCodeOf(glyphUnicode);
  22564. }
  22565. // setting it to unicode if negative or undefined
  22566. if (charcode <= 0) {
  22567. charcode = glyphUnicode;
  22568. }
  22569. // trying to get width via charcode
  22570. width = this.widths[charcode];
  22571. if (width) {
  22572. break; // the non-zero width found
  22573. }
  22574. }
  22575. width = width || this.defaultWidth;
  22576. // Do not shadow the property here. See discussion:
  22577. // https://github.com/mozilla/pdf.js/pull/2127#discussion_r1662280
  22578. this._shadowWidth = width;
  22579. return width;
  22580. },
  22581. charToGlyph: function Font_charToGlyph(charcode) {
  22582. var fontCharCode, width, operatorListId;
  22583. var widthCode = charcode;
  22584. if (this.cMap && this.cMap.contains(charcode)) {
  22585. widthCode = this.cMap.lookup(charcode);
  22586. }
  22587. width = this.widths[widthCode];
  22588. width = isNum(width) ? width : this.defaultWidth;
  22589. var vmetric = this.vmetrics && this.vmetrics[widthCode];
  22590. var unicode = this.toUnicode.get(charcode) || charcode;
  22591. if (typeof unicode === 'number') {
  22592. unicode = String.fromCharCode(unicode);
  22593. }
  22594. // First try the toFontChar map, if it's not there then try falling
  22595. // back to the char code.
  22596. fontCharCode = this.toFontChar[charcode] || charcode;
  22597. if (this.missingFile) {
  22598. fontCharCode = mapSpecialUnicodeValues(fontCharCode);
  22599. }
  22600. if (this.isType3Font) {
  22601. // Font char code in this case is actually a glyph name.
  22602. operatorListId = fontCharCode;
  22603. }
  22604. var accent = null;
  22605. if (this.seacMap && this.seacMap[charcode]) {
  22606. var seac = this.seacMap[charcode];
  22607. fontCharCode = seac.baseFontCharCode;
  22608. accent = {
  22609. fontChar: String.fromCharCode(seac.accentFontCharCode),
  22610. offset: seac.accentOffset
  22611. };
  22612. }
  22613. var fontChar = String.fromCharCode(fontCharCode);
  22614. var glyph = this.glyphCache[charcode];
  22615. if (!glyph ||
  22616. !glyph.matchesForCache(fontChar, unicode, accent, width, vmetric,
  22617. operatorListId)) {
  22618. glyph = new Glyph(fontChar, unicode, accent, width, vmetric,
  22619. operatorListId);
  22620. this.glyphCache[charcode] = glyph;
  22621. }
  22622. return glyph;
  22623. },
  22624. charsToGlyphs: function Font_charsToGlyphs(chars) {
  22625. var charsCache = this.charsCache;
  22626. var glyphs, glyph, charcode;
  22627. // if we translated this string before, just grab it from the cache
  22628. if (charsCache) {
  22629. glyphs = charsCache[chars];
  22630. if (glyphs) {
  22631. return glyphs;
  22632. }
  22633. }
  22634. // lazily create the translation cache
  22635. if (!charsCache) {
  22636. charsCache = this.charsCache = Object.create(null);
  22637. }
  22638. glyphs = [];
  22639. var charsCacheKey = chars;
  22640. var i = 0, ii;
  22641. if (this.cMap) {
  22642. // composite fonts have multi-byte strings convert the string from
  22643. // single-byte to multi-byte
  22644. var c = {};
  22645. while (i < chars.length) {
  22646. this.cMap.readCharCode(chars, i, c);
  22647. charcode = c.charcode;
  22648. var length = c.length;
  22649. i += length;
  22650. glyph = this.charToGlyph(charcode);
  22651. glyphs.push(glyph);
  22652. // placing null after each word break charcode (ASCII SPACE)
  22653. // Ignore occurences of 0x20 in multiple-byte codes.
  22654. if (length === 1 && chars.charCodeAt(i - 1) === 0x20) {
  22655. glyphs.push(null);
  22656. }
  22657. }
  22658. } else {
  22659. for (i = 0, ii = chars.length; i < ii; ++i) {
  22660. charcode = chars.charCodeAt(i);
  22661. glyph = this.charToGlyph(charcode);
  22662. glyphs.push(glyph);
  22663. if (charcode === 0x20) {
  22664. glyphs.push(null);
  22665. }
  22666. }
  22667. }
  22668. // Enter the translated string into the cache
  22669. return (charsCache[charsCacheKey] = glyphs);
  22670. }
  22671. };
  22672. return Font;
  22673. })();
  22674. var ErrorFont = (function ErrorFontClosure() {
  22675. function ErrorFont(error) {
  22676. this.error = error;
  22677. this.loadedName = 'g_font_error';
  22678. this.loading = false;
  22679. }
  22680. ErrorFont.prototype = {
  22681. charsToGlyphs: function ErrorFont_charsToGlyphs() {
  22682. return [];
  22683. },
  22684. exportData: function ErrorFont_exportData() {
  22685. return {error: this.error};
  22686. }
  22687. };
  22688. return ErrorFont;
  22689. })();
  22690. /**
  22691. * Shared logic for building a char code to glyph id mapping for Type1 and
  22692. * simple CFF fonts. See section 9.6.6.2 of the spec.
  22693. * @param {Object} properties Font properties object.
  22694. * @param {Object} builtInEncoding The encoding contained within the actual font
  22695. * data.
  22696. * @param {Array} Array of glyph names where the index is the glyph ID.
  22697. * @returns {Object} A char code to glyph ID map.
  22698. */
  22699. function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
  22700. var charCodeToGlyphId = Object.create(null);
  22701. var glyphId, charCode, baseEncoding;
  22702. if (properties.baseEncodingName) {
  22703. // If a valid base encoding name was used, the mapping is initialized with
  22704. // that.
  22705. baseEncoding = Encodings[properties.baseEncodingName];
  22706. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  22707. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  22708. if (glyphId >= 0) {
  22709. charCodeToGlyphId[charCode] = glyphId;
  22710. } else {
  22711. charCodeToGlyphId[charCode] = 0; // notdef
  22712. }
  22713. }
  22714. } else if (!!(properties.flags & FontFlags.Symbolic)) {
  22715. // For a symbolic font the encoding should be the fonts built-in
  22716. // encoding.
  22717. for (charCode in builtInEncoding) {
  22718. charCodeToGlyphId[charCode] = builtInEncoding[charCode];
  22719. }
  22720. } else {
  22721. // For non-symbolic fonts that don't have a base encoding the standard
  22722. // encoding should be used.
  22723. baseEncoding = Encodings.StandardEncoding;
  22724. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  22725. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  22726. if (glyphId >= 0) {
  22727. charCodeToGlyphId[charCode] = glyphId;
  22728. } else {
  22729. charCodeToGlyphId[charCode] = 0; // notdef
  22730. }
  22731. }
  22732. }
  22733. // Lastly, merge in the differences.
  22734. var differences = properties.differences;
  22735. if (differences) {
  22736. for (charCode in differences) {
  22737. var glyphName = differences[charCode];
  22738. glyphId = glyphNames.indexOf(glyphName);
  22739. if (glyphId >= 0) {
  22740. charCodeToGlyphId[charCode] = glyphId;
  22741. } else {
  22742. charCodeToGlyphId[charCode] = 0; // notdef
  22743. }
  22744. }
  22745. }
  22746. return charCodeToGlyphId;
  22747. }
  22748. /*
  22749. * CharStrings are encoded following the the CharString Encoding sequence
  22750. * describe in Chapter 6 of the "Adobe Type1 Font Format" specification.
  22751. * The value in a byte indicates a command, a number, or subsequent bytes
  22752. * that are to be interpreted in a special way.
  22753. *
  22754. * CharString Number Encoding:
  22755. * A CharString byte containing the values from 32 through 255 inclusive
  22756. * indicate an integer. These values are decoded in four ranges.
  22757. *
  22758. * 1. A CharString byte containing a value, v, between 32 and 246 inclusive,
  22759. * indicate the integer v - 139. Thus, the integer values from -107 through
  22760. * 107 inclusive may be encoded in single byte.
  22761. *
  22762. * 2. A CharString byte containing a value, v, between 247 and 250 inclusive,
  22763. * indicates an integer involving the next byte, w, according to the formula:
  22764. * [(v - 247) x 256] + w + 108
  22765. *
  22766. * 3. A CharString byte containing a value, v, between 251 and 254 inclusive,
  22767. * indicates an integer involving the next byte, w, according to the formula:
  22768. * -[(v - 251) * 256] - w - 108
  22769. *
  22770. * 4. A CharString containing the value 255 indicates that the next 4 bytes
  22771. * are a two complement signed integer. The first of these bytes contains the
  22772. * highest order bits, the second byte contains the next higher order bits
  22773. * and the fourth byte contain the lowest order bits.
  22774. *
  22775. *
  22776. * CharString Command Encoding:
  22777. * CharStrings commands are encoded in 1 or 2 bytes.
  22778. *
  22779. * Single byte commands are encoded in 1 byte that contains a value between
  22780. * 0 and 31 inclusive.
  22781. * If a command byte contains the value 12, then the value in the next byte
  22782. * indicates a command. This "escape" mechanism allows many extra commands
  22783. * to be encoded and this encoding technique helps to minimize the length of
  22784. * the charStrings.
  22785. */
  22786. var Type1CharString = (function Type1CharStringClosure() {
  22787. var COMMAND_MAP = {
  22788. 'hstem': [1],
  22789. 'vstem': [3],
  22790. 'vmoveto': [4],
  22791. 'rlineto': [5],
  22792. 'hlineto': [6],
  22793. 'vlineto': [7],
  22794. 'rrcurveto': [8],
  22795. 'callsubr': [10],
  22796. 'flex': [12, 35],
  22797. 'drop' : [12, 18],
  22798. 'endchar': [14],
  22799. 'rmoveto': [21],
  22800. 'hmoveto': [22],
  22801. 'vhcurveto': [30],
  22802. 'hvcurveto': [31]
  22803. };
  22804. function Type1CharString() {
  22805. this.width = 0;
  22806. this.lsb = 0;
  22807. this.flexing = false;
  22808. this.output = [];
  22809. this.stack = [];
  22810. }
  22811. Type1CharString.prototype = {
  22812. convert: function Type1CharString_convert(encoded, subrs) {
  22813. var count = encoded.length;
  22814. var error = false;
  22815. var wx, sbx, subrNumber;
  22816. for (var i = 0; i < count; i++) {
  22817. var value = encoded[i];
  22818. if (value < 32) {
  22819. if (value === 12) {
  22820. value = (value << 8) + encoded[++i];
  22821. }
  22822. switch (value) {
  22823. case 1: // hstem
  22824. if (!HINTING_ENABLED) {
  22825. this.stack = [];
  22826. break;
  22827. }
  22828. error = this.executeCommand(2, COMMAND_MAP.hstem);
  22829. break;
  22830. case 3: // vstem
  22831. if (!HINTING_ENABLED) {
  22832. this.stack = [];
  22833. break;
  22834. }
  22835. error = this.executeCommand(2, COMMAND_MAP.vstem);
  22836. break;
  22837. case 4: // vmoveto
  22838. if (this.flexing) {
  22839. if (this.stack.length < 1) {
  22840. error = true;
  22841. break;
  22842. }
  22843. // Add the dx for flex and but also swap the values so they are
  22844. // the right order.
  22845. var dy = this.stack.pop();
  22846. this.stack.push(0, dy);
  22847. break;
  22848. }
  22849. error = this.executeCommand(1, COMMAND_MAP.vmoveto);
  22850. break;
  22851. case 5: // rlineto
  22852. error = this.executeCommand(2, COMMAND_MAP.rlineto);
  22853. break;
  22854. case 6: // hlineto
  22855. error = this.executeCommand(1, COMMAND_MAP.hlineto);
  22856. break;
  22857. case 7: // vlineto
  22858. error = this.executeCommand(1, COMMAND_MAP.vlineto);
  22859. break;
  22860. case 8: // rrcurveto
  22861. error = this.executeCommand(6, COMMAND_MAP.rrcurveto);
  22862. break;
  22863. case 9: // closepath
  22864. // closepath is a Type1 command that does not take argument and is
  22865. // useless in Type2 and it can simply be ignored.
  22866. this.stack = [];
  22867. break;
  22868. case 10: // callsubr
  22869. if (this.stack.length < 1) {
  22870. error = true;
  22871. break;
  22872. }
  22873. subrNumber = this.stack.pop();
  22874. error = this.convert(subrs[subrNumber], subrs);
  22875. break;
  22876. case 11: // return
  22877. return error;
  22878. case 13: // hsbw
  22879. if (this.stack.length < 2) {
  22880. error = true;
  22881. break;
  22882. }
  22883. // To convert to type2 we have to move the width value to the
  22884. // first part of the charstring and then use hmoveto with lsb.
  22885. wx = this.stack.pop();
  22886. sbx = this.stack.pop();
  22887. this.lsb = sbx;
  22888. this.width = wx;
  22889. this.stack.push(wx, sbx);
  22890. error = this.executeCommand(2, COMMAND_MAP.hmoveto);
  22891. break;
  22892. case 14: // endchar
  22893. this.output.push(COMMAND_MAP.endchar[0]);
  22894. break;
  22895. case 21: // rmoveto
  22896. if (this.flexing) {
  22897. break;
  22898. }
  22899. error = this.executeCommand(2, COMMAND_MAP.rmoveto);
  22900. break;
  22901. case 22: // hmoveto
  22902. if (this.flexing) {
  22903. // Add the dy for flex.
  22904. this.stack.push(0);
  22905. break;
  22906. }
  22907. error = this.executeCommand(1, COMMAND_MAP.hmoveto);
  22908. break;
  22909. case 30: // vhcurveto
  22910. error = this.executeCommand(4, COMMAND_MAP.vhcurveto);
  22911. break;
  22912. case 31: // hvcurveto
  22913. error = this.executeCommand(4, COMMAND_MAP.hvcurveto);
  22914. break;
  22915. case (12 << 8) + 0: // dotsection
  22916. // dotsection is a Type1 command to specify some hinting feature
  22917. // for dots that do not take a parameter and it can safely be
  22918. // ignored for Type2.
  22919. this.stack = [];
  22920. break;
  22921. case (12 << 8) + 1: // vstem3
  22922. if (!HINTING_ENABLED) {
  22923. this.stack = [];
  22924. break;
  22925. }
  22926. // [vh]stem3 are Type1 only and Type2 supports [vh]stem with
  22927. // multiple parameters, so instead of returning [vh]stem3 take a
  22928. // shortcut and return [vhstem] instead.
  22929. error = this.executeCommand(2, COMMAND_MAP.vstem);
  22930. break;
  22931. case (12 << 8) + 2: // hstem3
  22932. if (!HINTING_ENABLED) {
  22933. this.stack = [];
  22934. break;
  22935. }
  22936. // See vstem3.
  22937. error = this.executeCommand(2, COMMAND_MAP.hstem);
  22938. break;
  22939. case (12 << 8) + 6: // seac
  22940. // seac is like type 2's special endchar but it doesn't use the
  22941. // first argument asb, so remove it.
  22942. if (SEAC_ANALYSIS_ENABLED) {
  22943. this.seac = this.stack.splice(-4, 4);
  22944. error = this.executeCommand(0, COMMAND_MAP.endchar);
  22945. } else {
  22946. error = this.executeCommand(4, COMMAND_MAP.endchar);
  22947. }
  22948. break;
  22949. case (12 << 8) + 7: // sbw
  22950. if (this.stack.length < 4) {
  22951. error = true;
  22952. break;
  22953. }
  22954. // To convert to type2 we have to move the width value to the
  22955. // first part of the charstring and then use rmoveto with
  22956. // (dx, dy). The height argument will not be used for vmtx and
  22957. // vhea tables reconstruction -- ignoring it.
  22958. var wy = this.stack.pop();
  22959. wx = this.stack.pop();
  22960. var sby = this.stack.pop();
  22961. sbx = this.stack.pop();
  22962. this.lsb = sbx;
  22963. this.width = wx;
  22964. this.stack.push(wx, sbx, sby);
  22965. error = this.executeCommand(3, COMMAND_MAP.rmoveto);
  22966. break;
  22967. case (12 << 8) + 12: // div
  22968. if (this.stack.length < 2) {
  22969. error = true;
  22970. break;
  22971. }
  22972. var num2 = this.stack.pop();
  22973. var num1 = this.stack.pop();
  22974. this.stack.push(num1 / num2);
  22975. break;
  22976. case (12 << 8) + 16: // callothersubr
  22977. if (this.stack.length < 2) {
  22978. error = true;
  22979. break;
  22980. }
  22981. subrNumber = this.stack.pop();
  22982. var numArgs = this.stack.pop();
  22983. if (subrNumber === 0 && numArgs === 3) {
  22984. var flexArgs = this.stack.splice(this.stack.length - 17, 17);
  22985. this.stack.push(
  22986. flexArgs[2] + flexArgs[0], // bcp1x + rpx
  22987. flexArgs[3] + flexArgs[1], // bcp1y + rpy
  22988. flexArgs[4], // bcp2x
  22989. flexArgs[5], // bcp2y
  22990. flexArgs[6], // p2x
  22991. flexArgs[7], // p2y
  22992. flexArgs[8], // bcp3x
  22993. flexArgs[9], // bcp3y
  22994. flexArgs[10], // bcp4x
  22995. flexArgs[11], // bcp4y
  22996. flexArgs[12], // p3x
  22997. flexArgs[13], // p3y
  22998. flexArgs[14] // flexDepth
  22999. // 15 = finalx unused by flex
  23000. // 16 = finaly unused by flex
  23001. );
  23002. error = this.executeCommand(13, COMMAND_MAP.flex, true);
  23003. this.flexing = false;
  23004. this.stack.push(flexArgs[15], flexArgs[16]);
  23005. } else if (subrNumber === 1 && numArgs === 0) {
  23006. this.flexing = true;
  23007. }
  23008. break;
  23009. case (12 << 8) + 17: // pop
  23010. // Ignore this since it is only used with othersubr.
  23011. break;
  23012. case (12 << 8) + 33: // setcurrentpoint
  23013. // Ignore for now.
  23014. this.stack = [];
  23015. break;
  23016. default:
  23017. warn('Unknown type 1 charstring command of "' + value + '"');
  23018. break;
  23019. }
  23020. if (error) {
  23021. break;
  23022. }
  23023. continue;
  23024. } else if (value <= 246) {
  23025. value = value - 139;
  23026. } else if (value <= 250) {
  23027. value = ((value - 247) * 256) + encoded[++i] + 108;
  23028. } else if (value <= 254) {
  23029. value = -((value - 251) * 256) - encoded[++i] - 108;
  23030. } else {
  23031. value = (encoded[++i] & 0xff) << 24 | (encoded[++i] & 0xff) << 16 |
  23032. (encoded[++i] & 0xff) << 8 | (encoded[++i] & 0xff) << 0;
  23033. }
  23034. this.stack.push(value);
  23035. }
  23036. return error;
  23037. },
  23038. executeCommand: function(howManyArgs, command, keepStack) {
  23039. var stackLength = this.stack.length;
  23040. if (howManyArgs > stackLength) {
  23041. return true;
  23042. }
  23043. var start = stackLength - howManyArgs;
  23044. for (var i = start; i < stackLength; i++) {
  23045. var value = this.stack[i];
  23046. if (value === (value | 0)) { // int
  23047. this.output.push(28, (value >> 8) & 0xff, value & 0xff);
  23048. } else { // fixed point
  23049. value = (65536 * value) | 0;
  23050. this.output.push(255,
  23051. (value >> 24) & 0xFF,
  23052. (value >> 16) & 0xFF,
  23053. (value >> 8) & 0xFF,
  23054. value & 0xFF);
  23055. }
  23056. }
  23057. this.output.push.apply(this.output, command);
  23058. if (keepStack) {
  23059. this.stack.splice(start, howManyArgs);
  23060. } else {
  23061. this.stack.length = 0;
  23062. }
  23063. return false;
  23064. }
  23065. };
  23066. return Type1CharString;
  23067. })();
  23068. /*
  23069. * Type1Parser encapsulate the needed code for parsing a Type1 font
  23070. * program. Some of its logic depends on the Type2 charstrings
  23071. * structure.
  23072. * Note: this doesn't really parse the font since that would require evaluation
  23073. * of PostScript, but it is possible in most cases to extract what we need
  23074. * without a full parse.
  23075. */
  23076. var Type1Parser = (function Type1ParserClosure() {
  23077. /*
  23078. * Decrypt a Sequence of Ciphertext Bytes to Produce the Original Sequence
  23079. * of Plaintext Bytes. The function took a key as a parameter which can be
  23080. * for decrypting the eexec block of for decoding charStrings.
  23081. */
  23082. var EEXEC_ENCRYPT_KEY = 55665;
  23083. var CHAR_STRS_ENCRYPT_KEY = 4330;
  23084. function isHexDigit(code) {
  23085. return code >= 48 && code <= 57 || // '0'-'9'
  23086. code >= 65 && code <= 70 || // 'A'-'F'
  23087. code >= 97 && code <= 102; // 'a'-'f'
  23088. }
  23089. function decrypt(data, key, discardNumber) {
  23090. var r = key | 0, c1 = 52845, c2 = 22719;
  23091. var count = data.length;
  23092. var decrypted = new Uint8Array(count);
  23093. for (var i = 0; i < count; i++) {
  23094. var value = data[i];
  23095. decrypted[i] = value ^ (r >> 8);
  23096. r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
  23097. }
  23098. return Array.prototype.slice.call(decrypted, discardNumber);
  23099. }
  23100. function decryptAscii(data, key, discardNumber) {
  23101. var r = key | 0, c1 = 52845, c2 = 22719;
  23102. var count = data.length, maybeLength = count >>> 1;
  23103. var decrypted = new Uint8Array(maybeLength);
  23104. var i, j;
  23105. for (i = 0, j = 0; i < count; i++) {
  23106. var digit1 = data[i];
  23107. if (!isHexDigit(digit1)) {
  23108. continue;
  23109. }
  23110. i++;
  23111. var digit2;
  23112. while (i < count && !isHexDigit(digit2 = data[i])) {
  23113. i++;
  23114. }
  23115. if (i < count) {
  23116. var value = parseInt(String.fromCharCode(digit1, digit2), 16);
  23117. decrypted[j++] = value ^ (r >> 8);
  23118. r = ((value + r) * c1 + c2) & ((1 << 16) - 1);
  23119. }
  23120. }
  23121. return Array.prototype.slice.call(decrypted, discardNumber, j);
  23122. }
  23123. function isSpecial(c) {
  23124. return c === 0x2F || // '/'
  23125. c === 0x5B || c === 0x5D || // '[', ']'
  23126. c === 0x7B || c === 0x7D || // '{', '}'
  23127. c === 0x28 || c === 0x29; // '(', ')'
  23128. }
  23129. function Type1Parser(stream, encrypted) {
  23130. if (encrypted) {
  23131. var data = stream.getBytes();
  23132. var isBinary = !(isHexDigit(data[0]) && isHexDigit(data[1]) &&
  23133. isHexDigit(data[2]) && isHexDigit(data[3]));
  23134. stream = new Stream(isBinary ? decrypt(data, EEXEC_ENCRYPT_KEY, 4) :
  23135. decryptAscii(data, EEXEC_ENCRYPT_KEY, 4));
  23136. }
  23137. this.stream = stream;
  23138. this.nextChar();
  23139. }
  23140. Type1Parser.prototype = {
  23141. readNumberArray: function Type1Parser_readNumberArray() {
  23142. this.getToken(); // read '[' or '{' (arrays can start with either)
  23143. var array = [];
  23144. while (true) {
  23145. var token = this.getToken();
  23146. if (token === null || token === ']' || token === '}') {
  23147. break;
  23148. }
  23149. array.push(parseFloat(token || 0));
  23150. }
  23151. return array;
  23152. },
  23153. readNumber: function Type1Parser_readNumber() {
  23154. var token = this.getToken();
  23155. return parseFloat(token || 0);
  23156. },
  23157. readInt: function Type1Parser_readInt() {
  23158. // Use '| 0' to prevent setting a double into length such as the double
  23159. // does not flow into the loop variable.
  23160. var token = this.getToken();
  23161. return parseInt(token || 0, 10) | 0;
  23162. },
  23163. readBoolean: function Type1Parser_readBoolean() {
  23164. var token = this.getToken();
  23165. // Use 1 and 0 since that's what type2 charstrings use.
  23166. return token === 'true' ? 1 : 0;
  23167. },
  23168. nextChar : function Type1_nextChar() {
  23169. return (this.currentChar = this.stream.getByte());
  23170. },
  23171. getToken: function Type1Parser_getToken() {
  23172. // Eat whitespace and comments.
  23173. var comment = false;
  23174. var ch = this.currentChar;
  23175. while (true) {
  23176. if (ch === -1) {
  23177. return null;
  23178. }
  23179. if (comment) {
  23180. if (ch === 0x0A || ch === 0x0D) {
  23181. comment = false;
  23182. }
  23183. } else if (ch === 0x25) { // '%'
  23184. comment = true;
  23185. } else if (!Lexer.isSpace(ch)) {
  23186. break;
  23187. }
  23188. ch = this.nextChar();
  23189. }
  23190. if (isSpecial(ch)) {
  23191. this.nextChar();
  23192. return String.fromCharCode(ch);
  23193. }
  23194. var token = '';
  23195. do {
  23196. token += String.fromCharCode(ch);
  23197. ch = this.nextChar();
  23198. } while (ch >= 0 && !Lexer.isSpace(ch) && !isSpecial(ch));
  23199. return token;
  23200. },
  23201. /*
  23202. * Returns an object containing a Subrs array and a CharStrings
  23203. * array extracted from and eexec encrypted block of data
  23204. */
  23205. extractFontProgram: function Type1Parser_extractFontProgram() {
  23206. var stream = this.stream;
  23207. var subrs = [], charstrings = [];
  23208. var program = {
  23209. subrs: [],
  23210. charstrings: [],
  23211. properties: {
  23212. 'privateData': {
  23213. 'lenIV': 4
  23214. }
  23215. }
  23216. };
  23217. var token, length, data, lenIV, encoded;
  23218. while ((token = this.getToken()) !== null) {
  23219. if (token !== '/') {
  23220. continue;
  23221. }
  23222. token = this.getToken();
  23223. switch (token) {
  23224. case 'CharStrings':
  23225. // The number immediately following CharStrings must be greater or
  23226. // equal to the number of CharStrings.
  23227. this.getToken();
  23228. this.getToken(); // read in 'dict'
  23229. this.getToken(); // read in 'dup'
  23230. this.getToken(); // read in 'begin'
  23231. while(true) {
  23232. token = this.getToken();
  23233. if (token === null || token === 'end') {
  23234. break;
  23235. }
  23236. if (token !== '/') {
  23237. continue;
  23238. }
  23239. var glyph = this.getToken();
  23240. length = this.readInt();
  23241. this.getToken(); // read in 'RD' or '-|'
  23242. data = stream.makeSubStream(stream.pos, length);
  23243. lenIV = program.properties.privateData['lenIV'];
  23244. encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);
  23245. // Skip past the required space and binary data.
  23246. stream.skip(length);
  23247. this.nextChar();
  23248. token = this.getToken(); // read in 'ND' or '|-'
  23249. if (token === 'noaccess') {
  23250. this.getToken(); // read in 'def'
  23251. }
  23252. charstrings.push({
  23253. glyph: glyph,
  23254. encoded: encoded
  23255. });
  23256. }
  23257. break;
  23258. case 'Subrs':
  23259. var num = this.readInt();
  23260. this.getToken(); // read in 'array'
  23261. while ((token = this.getToken()) === 'dup') {
  23262. var index = this.readInt();
  23263. length = this.readInt();
  23264. this.getToken(); // read in 'RD' or '-|'
  23265. data = stream.makeSubStream(stream.pos, length);
  23266. lenIV = program.properties.privateData['lenIV'];
  23267. encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);
  23268. // Skip past the required space and binary data.
  23269. stream.skip(length);
  23270. this.nextChar();
  23271. token = this.getToken(); // read in 'NP' or '|'
  23272. if (token === 'noaccess') {
  23273. this.getToken(); // read in 'put'
  23274. }
  23275. subrs[index] = encoded;
  23276. }
  23277. break;
  23278. case 'BlueValues':
  23279. case 'OtherBlues':
  23280. case 'FamilyBlues':
  23281. case 'FamilyOtherBlues':
  23282. var blueArray = this.readNumberArray();
  23283. // *Blue* values may contain invalid data: disables reading of
  23284. // those values when hinting is disabled.
  23285. if (blueArray.length > 0 && (blueArray.length % 2) === 0 &&
  23286. HINTING_ENABLED) {
  23287. program.properties.privateData[token] = blueArray;
  23288. }
  23289. break;
  23290. case 'StemSnapH':
  23291. case 'StemSnapV':
  23292. program.properties.privateData[token] = this.readNumberArray();
  23293. break;
  23294. case 'StdHW':
  23295. case 'StdVW':
  23296. program.properties.privateData[token] =
  23297. this.readNumberArray()[0];
  23298. break;
  23299. case 'BlueShift':
  23300. case 'lenIV':
  23301. case 'BlueFuzz':
  23302. case 'BlueScale':
  23303. case 'LanguageGroup':
  23304. case 'ExpansionFactor':
  23305. program.properties.privateData[token] = this.readNumber();
  23306. break;
  23307. case 'ForceBold':
  23308. program.properties.privateData[token] = this.readBoolean();
  23309. break;
  23310. }
  23311. }
  23312. for (var i = 0; i < charstrings.length; i++) {
  23313. glyph = charstrings[i].glyph;
  23314. encoded = charstrings[i].encoded;
  23315. var charString = new Type1CharString();
  23316. var error = charString.convert(encoded, subrs);
  23317. var output = charString.output;
  23318. if (error) {
  23319. // It seems when FreeType encounters an error while evaluating a glyph
  23320. // that it completely ignores the glyph so we'll mimic that behaviour
  23321. // here and put an endchar to make the validator happy.
  23322. output = [14];
  23323. }
  23324. program.charstrings.push({
  23325. glyphName: glyph,
  23326. charstring: output,
  23327. width: charString.width,
  23328. lsb: charString.lsb,
  23329. seac: charString.seac
  23330. });
  23331. }
  23332. return program;
  23333. },
  23334. extractFontHeader: function Type1Parser_extractFontHeader(properties) {
  23335. var token;
  23336. while ((token = this.getToken()) !== null) {
  23337. if (token !== '/') {
  23338. continue;
  23339. }
  23340. token = this.getToken();
  23341. switch (token) {
  23342. case 'FontMatrix':
  23343. var matrix = this.readNumberArray();
  23344. properties.fontMatrix = matrix;
  23345. break;
  23346. case 'Encoding':
  23347. var encodingArg = this.getToken();
  23348. var encoding;
  23349. if (!/^\d+$/.test(encodingArg)) {
  23350. // encoding name is specified
  23351. encoding = Encodings[encodingArg];
  23352. } else {
  23353. encoding = [];
  23354. var size = parseInt(encodingArg, 10) | 0;
  23355. this.getToken(); // read in 'array'
  23356. for (var j = 0; j < size; j++) {
  23357. token = this.getToken();
  23358. // skipping till first dup or def (e.g. ignoring for statement)
  23359. while (token !== 'dup' && token !== 'def') {
  23360. token = this.getToken();
  23361. if (token === null) {
  23362. return; // invalid header
  23363. }
  23364. }
  23365. if (token === 'def') {
  23366. break; // read all array data
  23367. }
  23368. var index = this.readInt();
  23369. this.getToken(); // read in '/'
  23370. var glyph = this.getToken();
  23371. encoding[index] = glyph;
  23372. this.getToken(); // read the in 'put'
  23373. }
  23374. }
  23375. properties.builtInEncoding = encoding;
  23376. break;
  23377. case 'FontBBox':
  23378. var fontBBox = this.readNumberArray();
  23379. // adjusting ascent/descent
  23380. properties.ascent = fontBBox[3];
  23381. properties.descent = fontBBox[1];
  23382. properties.ascentScaled = true;
  23383. break;
  23384. }
  23385. }
  23386. }
  23387. };
  23388. return Type1Parser;
  23389. })();
  23390. /**
  23391. * The CFF class takes a Type1 file and wrap it into a
  23392. * 'Compact Font Format' which itself embed Type2 charstrings.
  23393. */
  23394. var CFFStandardStrings = [
  23395. '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
  23396. 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
  23397. 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
  23398. 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
  23399. 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  23400. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  23401. 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum',
  23402. 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  23403. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
  23404. 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
  23405. 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
  23406. 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
  23407. 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
  23408. 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase',
  23409. 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown',
  23410. 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent',
  23411. 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash',
  23412. 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae',
  23413. 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior',
  23414. 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn',
  23415. 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters',
  23416. 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior',
  23417. 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring',
  23418. 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave',
  23419. 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute',
  23420. 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute',
  23421. 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron',
  23422. 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde',
  23423. 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute',
  23424. 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex',
  23425. 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex',
  23426. 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall',
  23427. 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall',
  23428. 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
  23429. 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle',
  23430. 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
  23431. 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior',
  23432. 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior',
  23433. 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior',
  23434. 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
  23435. 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior',
  23436. 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall',
  23437. 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
  23438. 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
  23439. 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
  23440. 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
  23441. 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
  23442. 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
  23443. 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior',
  23444. 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth',
  23445. 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
  23446. 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
  23447. 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior',
  23448. 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior',
  23449. 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
  23450. 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
  23451. 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall',
  23452. 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
  23453. 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
  23454. 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall',
  23455. 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall',
  23456. 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
  23457. 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall',
  23458. 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003',
  23459. 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'
  23460. ];
  23461. // Type1Font is also a CIDFontType0.
  23462. var Type1Font = function Type1Font(name, file, properties) {
  23463. // Some bad generators embed pfb file as is, we have to strip 6-byte headers.
  23464. // Also, length1 and length2 might be off by 6 bytes as well.
  23465. // http://www.math.ubc.ca/~cass/piscript/type1.pdf
  23466. var PFB_HEADER_SIZE = 6;
  23467. var headerBlockLength = properties.length1;
  23468. var eexecBlockLength = properties.length2;
  23469. var pfbHeader = file.peekBytes(PFB_HEADER_SIZE);
  23470. var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01;
  23471. if (pfbHeaderPresent) {
  23472. file.skip(PFB_HEADER_SIZE);
  23473. headerBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
  23474. (pfbHeader[3] << 8) | pfbHeader[2];
  23475. }
  23476. // Get the data block containing glyphs and subrs informations
  23477. var headerBlock = new Stream(file.getBytes(headerBlockLength));
  23478. var headerBlockParser = new Type1Parser(headerBlock);
  23479. headerBlockParser.extractFontHeader(properties);
  23480. if (pfbHeaderPresent) {
  23481. pfbHeader = file.getBytes(PFB_HEADER_SIZE);
  23482. eexecBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
  23483. (pfbHeader[3] << 8) | pfbHeader[2];
  23484. }
  23485. // Decrypt the data blocks and retrieve it's content
  23486. var eexecBlock = new Stream(file.getBytes(eexecBlockLength));
  23487. var eexecBlockParser = new Type1Parser(eexecBlock, true);
  23488. var data = eexecBlockParser.extractFontProgram();
  23489. for (var info in data.properties) {
  23490. properties[info] = data.properties[info];
  23491. }
  23492. var charstrings = data.charstrings;
  23493. var type2Charstrings = this.getType2Charstrings(charstrings);
  23494. var subrs = this.getType2Subrs(data.subrs);
  23495. this.charstrings = charstrings;
  23496. this.data = this.wrap(name, type2Charstrings, this.charstrings,
  23497. subrs, properties);
  23498. this.seacs = this.getSeacs(data.charstrings);
  23499. };
  23500. Type1Font.prototype = {
  23501. get numGlyphs() {
  23502. return this.charstrings.length + 1;
  23503. },
  23504. getCharset: function Type1Font_getCharset() {
  23505. var charset = ['.notdef'];
  23506. var charstrings = this.charstrings;
  23507. for (var glyphId = 0; glyphId < charstrings.length; glyphId++) {
  23508. charset.push(charstrings[glyphId].glyphName);
  23509. }
  23510. return charset;
  23511. },
  23512. getGlyphMapping: function Type1Font_getGlyphMapping(properties) {
  23513. var charstrings = this.charstrings;
  23514. var glyphNames = ['.notdef'], glyphId;
  23515. for (glyphId = 0; glyphId < charstrings.length; glyphId++) {
  23516. glyphNames.push(charstrings[glyphId].glyphName);
  23517. }
  23518. var encoding = properties.builtInEncoding;
  23519. if (encoding) {
  23520. var builtInEncoding = {};
  23521. for (var charCode in encoding) {
  23522. glyphId = glyphNames.indexOf(encoding[charCode]);
  23523. if (glyphId >= 0) {
  23524. builtInEncoding[charCode] = glyphId;
  23525. }
  23526. }
  23527. }
  23528. return type1FontGlyphMapping(properties, builtInEncoding, glyphNames);
  23529. },
  23530. getSeacs: function Type1Font_getSeacs(charstrings) {
  23531. var i, ii;
  23532. var seacMap = [];
  23533. for (i = 0, ii = charstrings.length; i < ii; i++) {
  23534. var charstring = charstrings[i];
  23535. if (charstring.seac) {
  23536. // Offset by 1 for .notdef
  23537. seacMap[i + 1] = charstring.seac;
  23538. }
  23539. }
  23540. return seacMap;
  23541. },
  23542. getType2Charstrings: function Type1Font_getType2Charstrings(
  23543. type1Charstrings) {
  23544. var type2Charstrings = [];
  23545. for (var i = 0, ii = type1Charstrings.length; i < ii; i++) {
  23546. type2Charstrings.push(type1Charstrings[i].charstring);
  23547. }
  23548. return type2Charstrings;
  23549. },
  23550. getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) {
  23551. var bias = 0;
  23552. var count = type1Subrs.length;
  23553. if (count < 1133) {
  23554. bias = 107;
  23555. } else if (count < 33769) {
  23556. bias = 1131;
  23557. } else {
  23558. bias = 32768;
  23559. }
  23560. // Add a bunch of empty subrs to deal with the Type2 bias
  23561. var type2Subrs = [];
  23562. var i;
  23563. for (i = 0; i < bias; i++) {
  23564. type2Subrs.push([0x0B]);
  23565. }
  23566. for (i = 0; i < count; i++) {
  23567. type2Subrs.push(type1Subrs[i]);
  23568. }
  23569. return type2Subrs;
  23570. },
  23571. wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) {
  23572. var cff = new CFF();
  23573. cff.header = new CFFHeader(1, 0, 4, 4);
  23574. cff.names = [name];
  23575. var topDict = new CFFTopDict();
  23576. // CFF strings IDs 0...390 are predefined names, so refering
  23577. // to entries in our own String INDEX starts at SID 391.
  23578. topDict.setByName('version', 391);
  23579. topDict.setByName('Notice', 392);
  23580. topDict.setByName('FullName', 393);
  23581. topDict.setByName('FamilyName', 394);
  23582. topDict.setByName('Weight', 395);
  23583. topDict.setByName('Encoding', null); // placeholder
  23584. topDict.setByName('FontMatrix', properties.fontMatrix);
  23585. topDict.setByName('FontBBox', properties.bbox);
  23586. topDict.setByName('charset', null); // placeholder
  23587. topDict.setByName('CharStrings', null); // placeholder
  23588. topDict.setByName('Private', null); // placeholder
  23589. cff.topDict = topDict;
  23590. var strings = new CFFStrings();
  23591. strings.add('Version 0.11'); // Version
  23592. strings.add('See original notice'); // Notice
  23593. strings.add(name); // FullName
  23594. strings.add(name); // FamilyName
  23595. strings.add('Medium'); // Weight
  23596. cff.strings = strings;
  23597. cff.globalSubrIndex = new CFFIndex();
  23598. var count = glyphs.length;
  23599. var charsetArray = [0];
  23600. var i, ii;
  23601. for (i = 0; i < count; i++) {
  23602. var index = CFFStandardStrings.indexOf(charstrings[i].glyphName);
  23603. // TODO: Insert the string and correctly map it. Previously it was
  23604. // thought mapping names that aren't in the standard strings to .notdef
  23605. // was fine, however in issue818 when mapping them all to .notdef the
  23606. // adieresis glyph no longer worked.
  23607. if (index === -1) {
  23608. index = 0;
  23609. }
  23610. charsetArray.push((index >> 8) & 0xff, index & 0xff);
  23611. }
  23612. cff.charset = new CFFCharset(false, 0, [], charsetArray);
  23613. var charStringsIndex = new CFFIndex();
  23614. charStringsIndex.add([0x8B, 0x0E]); // .notdef
  23615. for (i = 0; i < count; i++) {
  23616. charStringsIndex.add(glyphs[i]);
  23617. }
  23618. cff.charStrings = charStringsIndex;
  23619. var privateDict = new CFFPrivateDict();
  23620. privateDict.setByName('Subrs', null); // placeholder
  23621. var fields = [
  23622. 'BlueValues',
  23623. 'OtherBlues',
  23624. 'FamilyBlues',
  23625. 'FamilyOtherBlues',
  23626. 'StemSnapH',
  23627. 'StemSnapV',
  23628. 'BlueShift',
  23629. 'BlueFuzz',
  23630. 'BlueScale',
  23631. 'LanguageGroup',
  23632. 'ExpansionFactor',
  23633. 'ForceBold',
  23634. 'StdHW',
  23635. 'StdVW'
  23636. ];
  23637. for (i = 0, ii = fields.length; i < ii; i++) {
  23638. var field = fields[i];
  23639. if (!properties.privateData.hasOwnProperty(field)) {
  23640. continue;
  23641. }
  23642. var value = properties.privateData[field];
  23643. if (isArray(value)) {
  23644. // All of the private dictionary array data in CFF must be stored as
  23645. // "delta-encoded" numbers.
  23646. for (var j = value.length - 1; j > 0; j--) {
  23647. value[j] -= value[j - 1]; // ... difference from previous value
  23648. }
  23649. }
  23650. privateDict.setByName(field, value);
  23651. }
  23652. cff.topDict.privateDict = privateDict;
  23653. var subrIndex = new CFFIndex();
  23654. for (i = 0, ii = subrs.length; i < ii; i++) {
  23655. subrIndex.add(subrs[i]);
  23656. }
  23657. privateDict.subrsIndex = subrIndex;
  23658. var compiler = new CFFCompiler(cff);
  23659. return compiler.compile();
  23660. }
  23661. };
  23662. var CFFFont = (function CFFFontClosure() {
  23663. function CFFFont(file, properties) {
  23664. this.properties = properties;
  23665. var parser = new CFFParser(file, properties);
  23666. this.cff = parser.parse();
  23667. var compiler = new CFFCompiler(this.cff);
  23668. this.seacs = this.cff.seacs;
  23669. try {
  23670. this.data = compiler.compile();
  23671. } catch (e) {
  23672. warn('Failed to compile font ' + properties.loadedName);
  23673. // There may have just been an issue with the compiler, set the data
  23674. // anyway and hope the font loaded.
  23675. this.data = file;
  23676. }
  23677. }
  23678. CFFFont.prototype = {
  23679. get numGlyphs() {
  23680. return this.cff.charStrings.count;
  23681. },
  23682. getCharset: function CFFFont_getCharset() {
  23683. return this.cff.charset.charset;
  23684. },
  23685. getGlyphMapping: function CFFFont_getGlyphMapping() {
  23686. var cff = this.cff;
  23687. var properties = this.properties;
  23688. var charsets = cff.charset.charset;
  23689. var charCodeToGlyphId;
  23690. var glyphId;
  23691. if (properties.composite) {
  23692. charCodeToGlyphId = Object.create(null);
  23693. if (cff.isCIDFont) {
  23694. // If the font is actually a CID font then we should use the charset
  23695. // to map CIDs to GIDs.
  23696. for (glyphId = 0; glyphId < charsets.length; glyphId++) {
  23697. var cid = charsets[glyphId];
  23698. var charCode = properties.cMap.charCodeOf(cid);
  23699. charCodeToGlyphId[charCode] = glyphId;
  23700. }
  23701. } else {
  23702. // If it is NOT actually a CID font then CIDs should be mapped
  23703. // directly to GIDs.
  23704. for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {
  23705. charCodeToGlyphId[glyphId] = glyphId;
  23706. }
  23707. }
  23708. return charCodeToGlyphId;
  23709. }
  23710. var encoding = cff.encoding ? cff.encoding.encoding : null;
  23711. charCodeToGlyphId = type1FontGlyphMapping(properties, encoding, charsets);
  23712. return charCodeToGlyphId;
  23713. }
  23714. };
  23715. return CFFFont;
  23716. })();
  23717. var CFFParser = (function CFFParserClosure() {
  23718. var CharstringValidationData = [
  23719. null,
  23720. { id: 'hstem', min: 2, stackClearing: true, stem: true },
  23721. null,
  23722. { id: 'vstem', min: 2, stackClearing: true, stem: true },
  23723. { id: 'vmoveto', min: 1, stackClearing: true },
  23724. { id: 'rlineto', min: 2, resetStack: true },
  23725. { id: 'hlineto', min: 1, resetStack: true },
  23726. { id: 'vlineto', min: 1, resetStack: true },
  23727. { id: 'rrcurveto', min: 6, resetStack: true },
  23728. null,
  23729. { id: 'callsubr', min: 1, undefStack: true },
  23730. { id: 'return', min: 0, undefStack: true },
  23731. null, // 12
  23732. null,
  23733. { id: 'endchar', min: 0, stackClearing: true },
  23734. null,
  23735. null,
  23736. null,
  23737. { id: 'hstemhm', min: 2, stackClearing: true, stem: true },
  23738. { id: 'hintmask', min: 0, stackClearing: true },
  23739. { id: 'cntrmask', min: 0, stackClearing: true },
  23740. { id: 'rmoveto', min: 2, stackClearing: true },
  23741. { id: 'hmoveto', min: 1, stackClearing: true },
  23742. { id: 'vstemhm', min: 2, stackClearing: true, stem: true },
  23743. { id: 'rcurveline', min: 8, resetStack: true },
  23744. { id: 'rlinecurve', min: 8, resetStack: true },
  23745. { id: 'vvcurveto', min: 4, resetStack: true },
  23746. { id: 'hhcurveto', min: 4, resetStack: true },
  23747. null, // shortint
  23748. { id: 'callgsubr', min: 1, undefStack: true },
  23749. { id: 'vhcurveto', min: 4, resetStack: true },
  23750. { id: 'hvcurveto', min: 4, resetStack: true }
  23751. ];
  23752. var CharstringValidationData12 = [
  23753. null,
  23754. null,
  23755. null,
  23756. { id: 'and', min: 2, stackDelta: -1 },
  23757. { id: 'or', min: 2, stackDelta: -1 },
  23758. { id: 'not', min: 1, stackDelta: 0 },
  23759. null,
  23760. null,
  23761. null,
  23762. { id: 'abs', min: 1, stackDelta: 0 },
  23763. { id: 'add', min: 2, stackDelta: -1,
  23764. stackFn: function stack_div(stack, index) {
  23765. stack[index - 2] = stack[index - 2] + stack[index - 1];
  23766. }
  23767. },
  23768. { id: 'sub', min: 2, stackDelta: -1,
  23769. stackFn: function stack_div(stack, index) {
  23770. stack[index - 2] = stack[index - 2] - stack[index - 1];
  23771. }
  23772. },
  23773. { id: 'div', min: 2, stackDelta: -1,
  23774. stackFn: function stack_div(stack, index) {
  23775. stack[index - 2] = stack[index - 2] / stack[index - 1];
  23776. }
  23777. },
  23778. null,
  23779. { id: 'neg', min: 1, stackDelta: 0,
  23780. stackFn: function stack_div(stack, index) {
  23781. stack[index - 1] = -stack[index - 1];
  23782. }
  23783. },
  23784. { id: 'eq', min: 2, stackDelta: -1 },
  23785. null,
  23786. null,
  23787. { id: 'drop', min: 1, stackDelta: -1 },
  23788. null,
  23789. { id: 'put', min: 2, stackDelta: -2 },
  23790. { id: 'get', min: 1, stackDelta: 0 },
  23791. { id: 'ifelse', min: 4, stackDelta: -3 },
  23792. { id: 'random', min: 0, stackDelta: 1 },
  23793. { id: 'mul', min: 2, stackDelta: -1,
  23794. stackFn: function stack_div(stack, index) {
  23795. stack[index - 2] = stack[index - 2] * stack[index - 1];
  23796. }
  23797. },
  23798. null,
  23799. { id: 'sqrt', min: 1, stackDelta: 0 },
  23800. { id: 'dup', min: 1, stackDelta: 1 },
  23801. { id: 'exch', min: 2, stackDelta: 0 },
  23802. { id: 'index', min: 2, stackDelta: 0 },
  23803. { id: 'roll', min: 3, stackDelta: -2 },
  23804. null,
  23805. null,
  23806. null,
  23807. { id: 'hflex', min: 7, resetStack: true },
  23808. { id: 'flex', min: 13, resetStack: true },
  23809. { id: 'hflex1', min: 9, resetStack: true },
  23810. { id: 'flex1', min: 11, resetStack: true }
  23811. ];
  23812. function CFFParser(file, properties) {
  23813. this.bytes = file.getBytes();
  23814. this.properties = properties;
  23815. }
  23816. CFFParser.prototype = {
  23817. parse: function CFFParser_parse() {
  23818. var properties = this.properties;
  23819. var cff = new CFF();
  23820. this.cff = cff;
  23821. // The first five sections must be in order, all the others are reached
  23822. // via offsets contained in one of the below.
  23823. var header = this.parseHeader();
  23824. var nameIndex = this.parseIndex(header.endPos);
  23825. var topDictIndex = this.parseIndex(nameIndex.endPos);
  23826. var stringIndex = this.parseIndex(topDictIndex.endPos);
  23827. var globalSubrIndex = this.parseIndex(stringIndex.endPos);
  23828. var topDictParsed = this.parseDict(topDictIndex.obj.get(0));
  23829. var topDict = this.createDict(CFFTopDict, topDictParsed, cff.strings);
  23830. cff.header = header.obj;
  23831. cff.names = this.parseNameIndex(nameIndex.obj);
  23832. cff.strings = this.parseStringIndex(stringIndex.obj);
  23833. cff.topDict = topDict;
  23834. cff.globalSubrIndex = globalSubrIndex.obj;
  23835. this.parsePrivateDict(cff.topDict);
  23836. cff.isCIDFont = topDict.hasName('ROS');
  23837. var charStringOffset = topDict.getByName('CharStrings');
  23838. var charStringsAndSeacs = this.parseCharStrings(charStringOffset);
  23839. cff.charStrings = charStringsAndSeacs.charStrings;
  23840. cff.seacs = charStringsAndSeacs.seacs;
  23841. cff.widths = charStringsAndSeacs.widths;
  23842. var fontMatrix = topDict.getByName('FontMatrix');
  23843. if (fontMatrix) {
  23844. properties.fontMatrix = fontMatrix;
  23845. }
  23846. var fontBBox = topDict.getByName('FontBBox');
  23847. if (fontBBox) {
  23848. // adjusting ascent/descent
  23849. properties.ascent = fontBBox[3];
  23850. properties.descent = fontBBox[1];
  23851. properties.ascentScaled = true;
  23852. }
  23853. var charset, encoding;
  23854. if (cff.isCIDFont) {
  23855. var fdArrayIndex = this.parseIndex(topDict.getByName('FDArray')).obj;
  23856. for (var i = 0, ii = fdArrayIndex.count; i < ii; ++i) {
  23857. var dictRaw = fdArrayIndex.get(i);
  23858. var fontDict = this.createDict(CFFTopDict, this.parseDict(dictRaw),
  23859. cff.strings);
  23860. this.parsePrivateDict(fontDict);
  23861. cff.fdArray.push(fontDict);
  23862. }
  23863. // cid fonts don't have an encoding
  23864. encoding = null;
  23865. charset = this.parseCharsets(topDict.getByName('charset'),
  23866. cff.charStrings.count, cff.strings, true);
  23867. cff.fdSelect = this.parseFDSelect(topDict.getByName('FDSelect'),
  23868. cff.charStrings.count);
  23869. } else {
  23870. charset = this.parseCharsets(topDict.getByName('charset'),
  23871. cff.charStrings.count, cff.strings, false);
  23872. encoding = this.parseEncoding(topDict.getByName('Encoding'),
  23873. properties,
  23874. cff.strings, charset.charset);
  23875. }
  23876. cff.charset = charset;
  23877. cff.encoding = encoding;
  23878. return cff;
  23879. },
  23880. parseHeader: function CFFParser_parseHeader() {
  23881. var bytes = this.bytes;
  23882. var bytesLength = bytes.length;
  23883. var offset = 0;
  23884. // Prevent an infinite loop, by checking that the offset is within the
  23885. // bounds of the bytes array. Necessary in empty, or invalid, font files.
  23886. while (offset < bytesLength && bytes[offset] !== 1) {
  23887. ++offset;
  23888. }
  23889. if (offset >= bytesLength) {
  23890. error('Invalid CFF header');
  23891. } else if (offset !== 0) {
  23892. info('cff data is shifted');
  23893. bytes = bytes.subarray(offset);
  23894. this.bytes = bytes;
  23895. }
  23896. var major = bytes[0];
  23897. var minor = bytes[1];
  23898. var hdrSize = bytes[2];
  23899. var offSize = bytes[3];
  23900. var header = new CFFHeader(major, minor, hdrSize, offSize);
  23901. return { obj: header, endPos: hdrSize };
  23902. },
  23903. parseDict: function CFFParser_parseDict(dict) {
  23904. var pos = 0;
  23905. function parseOperand() {
  23906. var value = dict[pos++];
  23907. if (value === 30) {
  23908. return parseFloatOperand(pos);
  23909. } else if (value === 28) {
  23910. value = dict[pos++];
  23911. value = ((value << 24) | (dict[pos++] << 16)) >> 16;
  23912. return value;
  23913. } else if (value === 29) {
  23914. value = dict[pos++];
  23915. value = (value << 8) | dict[pos++];
  23916. value = (value << 8) | dict[pos++];
  23917. value = (value << 8) | dict[pos++];
  23918. return value;
  23919. } else if (value >= 32 && value <= 246) {
  23920. return value - 139;
  23921. } else if (value >= 247 && value <= 250) {
  23922. return ((value - 247) * 256) + dict[pos++] + 108;
  23923. } else if (value >= 251 && value <= 254) {
  23924. return -((value - 251) * 256) - dict[pos++] - 108;
  23925. } else {
  23926. error('255 is not a valid DICT command');
  23927. }
  23928. return -1;
  23929. }
  23930. function parseFloatOperand() {
  23931. var str = '';
  23932. var eof = 15;
  23933. var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
  23934. '9', '.', 'E', 'E-', null, '-'];
  23935. var length = dict.length;
  23936. while (pos < length) {
  23937. var b = dict[pos++];
  23938. var b1 = b >> 4;
  23939. var b2 = b & 15;
  23940. if (b1 === eof) {
  23941. break;
  23942. }
  23943. str += lookup[b1];
  23944. if (b2 === eof) {
  23945. break;
  23946. }
  23947. str += lookup[b2];
  23948. }
  23949. return parseFloat(str);
  23950. }
  23951. var operands = [];
  23952. var entries = [];
  23953. pos = 0;
  23954. var end = dict.length;
  23955. while (pos < end) {
  23956. var b = dict[pos];
  23957. if (b <= 21) {
  23958. if (b === 12) {
  23959. b = (b << 8) | dict[++pos];
  23960. }
  23961. entries.push([b, operands]);
  23962. operands = [];
  23963. ++pos;
  23964. } else {
  23965. operands.push(parseOperand());
  23966. }
  23967. }
  23968. return entries;
  23969. },
  23970. parseIndex: function CFFParser_parseIndex(pos) {
  23971. var cffIndex = new CFFIndex();
  23972. var bytes = this.bytes;
  23973. var count = (bytes[pos++] << 8) | bytes[pos++];
  23974. var offsets = [];
  23975. var end = pos;
  23976. var i, ii;
  23977. if (count !== 0) {
  23978. var offsetSize = bytes[pos++];
  23979. // add 1 for offset to determine size of last object
  23980. var startPos = pos + ((count + 1) * offsetSize) - 1;
  23981. for (i = 0, ii = count + 1; i < ii; ++i) {
  23982. var offset = 0;
  23983. for (var j = 0; j < offsetSize; ++j) {
  23984. offset <<= 8;
  23985. offset += bytes[pos++];
  23986. }
  23987. offsets.push(startPos + offset);
  23988. }
  23989. end = offsets[count];
  23990. }
  23991. for (i = 0, ii = offsets.length - 1; i < ii; ++i) {
  23992. var offsetStart = offsets[i];
  23993. var offsetEnd = offsets[i + 1];
  23994. cffIndex.add(bytes.subarray(offsetStart, offsetEnd));
  23995. }
  23996. return {obj: cffIndex, endPos: end};
  23997. },
  23998. parseNameIndex: function CFFParser_parseNameIndex(index) {
  23999. var names = [];
  24000. for (var i = 0, ii = index.count; i < ii; ++i) {
  24001. var name = index.get(i);
  24002. // OTS doesn't allow names to be over 127 characters.
  24003. var length = Math.min(name.length, 127);
  24004. var data = [];
  24005. // OTS also only permits certain characters in the name.
  24006. for (var j = 0; j < length; ++j) {
  24007. var c = name[j];
  24008. if (j === 0 && c === 0) {
  24009. data[j] = c;
  24010. continue;
  24011. }
  24012. if ((c < 33 || c > 126) || c === 91 /* [ */ || c === 93 /* ] */ ||
  24013. c === 40 /* ( */ || c === 41 /* ) */ || c === 123 /* { */ ||
  24014. c === 125 /* } */ || c === 60 /* < */ || c === 62 /* > */ ||
  24015. c === 47 /* / */ || c === 37 /* % */ || c === 35 /* # */) {
  24016. data[j] = 95;
  24017. continue;
  24018. }
  24019. data[j] = c;
  24020. }
  24021. names.push(bytesToString(data));
  24022. }
  24023. return names;
  24024. },
  24025. parseStringIndex: function CFFParser_parseStringIndex(index) {
  24026. var strings = new CFFStrings();
  24027. for (var i = 0, ii = index.count; i < ii; ++i) {
  24028. var data = index.get(i);
  24029. strings.add(bytesToString(data));
  24030. }
  24031. return strings;
  24032. },
  24033. createDict: function CFFParser_createDict(Type, dict, strings) {
  24034. var cffDict = new Type(strings);
  24035. for (var i = 0, ii = dict.length; i < ii; ++i) {
  24036. var pair = dict[i];
  24037. var key = pair[0];
  24038. var value = pair[1];
  24039. cffDict.setByKey(key, value);
  24040. }
  24041. return cffDict;
  24042. },
  24043. parseCharStrings: function CFFParser_parseCharStrings(charStringOffset) {
  24044. var charStrings = this.parseIndex(charStringOffset).obj;
  24045. var seacs = [];
  24046. var widths = [];
  24047. var count = charStrings.count;
  24048. for (var i = 0; i < count; i++) {
  24049. var charstring = charStrings.get(i);
  24050. var stackSize = 0;
  24051. var stack = [];
  24052. var undefStack = true;
  24053. var hints = 0;
  24054. var valid = true;
  24055. var data = charstring;
  24056. var length = data.length;
  24057. var firstStackClearing = true;
  24058. for (var j = 0; j < length;) {
  24059. var value = data[j++];
  24060. var validationCommand = null;
  24061. if (value === 12) {
  24062. var q = data[j++];
  24063. if (q === 0) {
  24064. // The CFF specification state that the 'dotsection' command
  24065. // (12, 0) is deprecated and treated as a no-op, but all Type2
  24066. // charstrings processors should support them. Unfortunately
  24067. // the font sanitizer don't. As a workaround the sequence (12, 0)
  24068. // is replaced by a useless (0, hmoveto).
  24069. data[j - 2] = 139;
  24070. data[j - 1] = 22;
  24071. stackSize = 0;
  24072. } else {
  24073. validationCommand = CharstringValidationData12[q];
  24074. }
  24075. } else if (value === 28) { // number (16 bit)
  24076. stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16)) >> 16;
  24077. j += 2;
  24078. stackSize++;
  24079. } else if (value === 14) {
  24080. if (stackSize >= 4) {
  24081. stackSize -= 4;
  24082. if (SEAC_ANALYSIS_ENABLED) {
  24083. seacs[i] = stack.slice(stackSize, stackSize + 4);
  24084. valid = false;
  24085. }
  24086. }
  24087. validationCommand = CharstringValidationData[value];
  24088. } else if (value >= 32 && value <= 246) { // number
  24089. stack[stackSize] = value - 139;
  24090. stackSize++;
  24091. } else if (value >= 247 && value <= 254) { // number (+1 bytes)
  24092. stack[stackSize] = (value < 251 ?
  24093. ((value - 247) << 8) + data[j] + 108 :
  24094. -((value - 251) << 8) - data[j] - 108);
  24095. j++;
  24096. stackSize++;
  24097. } else if (value === 255) { // number (32 bit)
  24098. stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16) |
  24099. (data[j + 2] << 8) | data[j + 3]) / 65536;
  24100. j += 4;
  24101. stackSize++;
  24102. } else if (value === 19 || value === 20) {
  24103. hints += stackSize >> 1;
  24104. j += (hints + 7) >> 3; // skipping right amount of hints flag data
  24105. stackSize %= 2;
  24106. validationCommand = CharstringValidationData[value];
  24107. } else {
  24108. validationCommand = CharstringValidationData[value];
  24109. }
  24110. if (validationCommand) {
  24111. if (validationCommand.stem) {
  24112. hints += stackSize >> 1;
  24113. }
  24114. if ('min' in validationCommand) {
  24115. if (!undefStack && stackSize < validationCommand.min) {
  24116. warn('Not enough parameters for ' + validationCommand.id +
  24117. '; actual: ' + stackSize +
  24118. ', expected: ' + validationCommand.min);
  24119. valid = false;
  24120. break;
  24121. }
  24122. }
  24123. if (firstStackClearing && validationCommand.stackClearing) {
  24124. firstStackClearing = false;
  24125. // the optional character width can be found before the first
  24126. // stack-clearing command arguments
  24127. stackSize -= validationCommand.min;
  24128. if (stackSize >= 2 && validationCommand.stem) {
  24129. // there are even amount of arguments for stem commands
  24130. stackSize %= 2;
  24131. } else if (stackSize > 1) {
  24132. warn('Found too many parameters for stack-clearing command');
  24133. }
  24134. if (stackSize > 0 && stack[stackSize - 1] >= 0) {
  24135. widths[i] = stack[stackSize - 1];
  24136. }
  24137. }
  24138. if ('stackDelta' in validationCommand) {
  24139. if ('stackFn' in validationCommand) {
  24140. validationCommand.stackFn(stack, stackSize);
  24141. }
  24142. stackSize += validationCommand.stackDelta;
  24143. } else if (validationCommand.stackClearing) {
  24144. stackSize = 0;
  24145. } else if (validationCommand.resetStack) {
  24146. stackSize = 0;
  24147. undefStack = false;
  24148. } else if (validationCommand.undefStack) {
  24149. stackSize = 0;
  24150. undefStack = true;
  24151. firstStackClearing = false;
  24152. }
  24153. }
  24154. }
  24155. if (!valid) {
  24156. // resetting invalid charstring to single 'endchar'
  24157. charStrings.set(i, new Uint8Array([14]));
  24158. }
  24159. }
  24160. return { charStrings: charStrings, seacs: seacs, widths: widths };
  24161. },
  24162. emptyPrivateDictionary:
  24163. function CFFParser_emptyPrivateDictionary(parentDict) {
  24164. var privateDict = this.createDict(CFFPrivateDict, [],
  24165. parentDict.strings);
  24166. parentDict.setByKey(18, [0, 0]);
  24167. parentDict.privateDict = privateDict;
  24168. },
  24169. parsePrivateDict: function CFFParser_parsePrivateDict(parentDict) {
  24170. // no private dict, do nothing
  24171. if (!parentDict.hasName('Private')) {
  24172. this.emptyPrivateDictionary(parentDict);
  24173. return;
  24174. }
  24175. var privateOffset = parentDict.getByName('Private');
  24176. // make sure the params are formatted correctly
  24177. if (!isArray(privateOffset) || privateOffset.length !== 2) {
  24178. parentDict.removeByName('Private');
  24179. return;
  24180. }
  24181. var size = privateOffset[0];
  24182. var offset = privateOffset[1];
  24183. // remove empty dicts or ones that refer to invalid location
  24184. if (size === 0 || offset >= this.bytes.length) {
  24185. this.emptyPrivateDictionary(parentDict);
  24186. return;
  24187. }
  24188. var privateDictEnd = offset + size;
  24189. var dictData = this.bytes.subarray(offset, privateDictEnd);
  24190. var dict = this.parseDict(dictData);
  24191. var privateDict = this.createDict(CFFPrivateDict, dict,
  24192. parentDict.strings);
  24193. parentDict.privateDict = privateDict;
  24194. // Parse the Subrs index also since it's relative to the private dict.
  24195. if (!privateDict.getByName('Subrs')) {
  24196. return;
  24197. }
  24198. var subrsOffset = privateDict.getByName('Subrs');
  24199. var relativeOffset = offset + subrsOffset;
  24200. // Validate the offset.
  24201. if (subrsOffset === 0 || relativeOffset >= this.bytes.length) {
  24202. this.emptyPrivateDictionary(parentDict);
  24203. return;
  24204. }
  24205. var subrsIndex = this.parseIndex(relativeOffset);
  24206. privateDict.subrsIndex = subrsIndex.obj;
  24207. },
  24208. parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) {
  24209. if (pos === 0) {
  24210. return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE,
  24211. ISOAdobeCharset);
  24212. } else if (pos === 1) {
  24213. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT,
  24214. ExpertCharset);
  24215. } else if (pos === 2) {
  24216. return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET,
  24217. ExpertSubsetCharset);
  24218. }
  24219. var bytes = this.bytes;
  24220. var start = pos;
  24221. var format = bytes[pos++];
  24222. var charset = ['.notdef'];
  24223. var id, count, i;
  24224. // subtract 1 for the .notdef glyph
  24225. length -= 1;
  24226. switch (format) {
  24227. case 0:
  24228. for (i = 0; i < length; i++) {
  24229. id = (bytes[pos++] << 8) | bytes[pos++];
  24230. charset.push(cid ? id : strings.get(id));
  24231. }
  24232. break;
  24233. case 1:
  24234. while (charset.length <= length) {
  24235. id = (bytes[pos++] << 8) | bytes[pos++];
  24236. count = bytes[pos++];
  24237. for (i = 0; i <= count; i++) {
  24238. charset.push(cid ? id++ : strings.get(id++));
  24239. }
  24240. }
  24241. break;
  24242. case 2:
  24243. while (charset.length <= length) {
  24244. id = (bytes[pos++] << 8) | bytes[pos++];
  24245. count = (bytes[pos++] << 8) | bytes[pos++];
  24246. for (i = 0; i <= count; i++) {
  24247. charset.push(cid ? id++ : strings.get(id++));
  24248. }
  24249. }
  24250. break;
  24251. default:
  24252. error('Unknown charset format');
  24253. }
  24254. // Raw won't be needed if we actually compile the charset.
  24255. var end = pos;
  24256. var raw = bytes.subarray(start, end);
  24257. return new CFFCharset(false, format, charset, raw);
  24258. },
  24259. parseEncoding: function CFFParser_parseEncoding(pos,
  24260. properties,
  24261. strings,
  24262. charset) {
  24263. var encoding = {};
  24264. var bytes = this.bytes;
  24265. var predefined = false;
  24266. var hasSupplement = false;
  24267. var format, i, ii;
  24268. var raw = null;
  24269. function readSupplement() {
  24270. var supplementsCount = bytes[pos++];
  24271. for (i = 0; i < supplementsCount; i++) {
  24272. var code = bytes[pos++];
  24273. var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);
  24274. encoding[code] = charset.indexOf(strings.get(sid));
  24275. }
  24276. }
  24277. if (pos === 0 || pos === 1) {
  24278. predefined = true;
  24279. format = pos;
  24280. var baseEncoding = pos ? Encodings.ExpertEncoding :
  24281. Encodings.StandardEncoding;
  24282. for (i = 0, ii = charset.length; i < ii; i++) {
  24283. var index = baseEncoding.indexOf(charset[i]);
  24284. if (index !== -1) {
  24285. encoding[index] = i;
  24286. }
  24287. }
  24288. } else {
  24289. var dataStart = pos;
  24290. format = bytes[pos++];
  24291. switch (format & 0x7f) {
  24292. case 0:
  24293. var glyphsCount = bytes[pos++];
  24294. for (i = 1; i <= glyphsCount; i++) {
  24295. encoding[bytes[pos++]] = i;
  24296. }
  24297. break;
  24298. case 1:
  24299. var rangesCount = bytes[pos++];
  24300. var gid = 1;
  24301. for (i = 0; i < rangesCount; i++) {
  24302. var start = bytes[pos++];
  24303. var left = bytes[pos++];
  24304. for (var j = start; j <= start + left; j++) {
  24305. encoding[j] = gid++;
  24306. }
  24307. }
  24308. break;
  24309. default:
  24310. error('Unknow encoding format: ' + format + ' in CFF');
  24311. break;
  24312. }
  24313. var dataEnd = pos;
  24314. if (format & 0x80) {
  24315. // The font sanitizer does not support CFF encoding with a
  24316. // supplement, since the encoding is not really used to map
  24317. // between gid to glyph, let's overwrite what is declared in
  24318. // the top dictionary to let the sanitizer think the font use
  24319. // StandardEncoding, that's a lie but that's ok.
  24320. bytes[dataStart] &= 0x7f;
  24321. readSupplement();
  24322. hasSupplement = true;
  24323. }
  24324. raw = bytes.subarray(dataStart, dataEnd);
  24325. }
  24326. format = format & 0x7f;
  24327. return new CFFEncoding(predefined, format, encoding, raw);
  24328. },
  24329. parseFDSelect: function CFFParser_parseFDSelect(pos, length) {
  24330. var start = pos;
  24331. var bytes = this.bytes;
  24332. var format = bytes[pos++];
  24333. var fdSelect = [];
  24334. var i;
  24335. switch (format) {
  24336. case 0:
  24337. for (i = 0; i < length; ++i) {
  24338. var id = bytes[pos++];
  24339. fdSelect.push(id);
  24340. }
  24341. break;
  24342. case 3:
  24343. var rangesCount = (bytes[pos++] << 8) | bytes[pos++];
  24344. for (i = 0; i < rangesCount; ++i) {
  24345. var first = (bytes[pos++] << 8) | bytes[pos++];
  24346. var fdIndex = bytes[pos++];
  24347. var next = (bytes[pos] << 8) | bytes[pos + 1];
  24348. for (var j = first; j < next; ++j) {
  24349. fdSelect.push(fdIndex);
  24350. }
  24351. }
  24352. // Advance past the sentinel(next).
  24353. pos += 2;
  24354. break;
  24355. default:
  24356. error('Unknown fdselect format ' + format);
  24357. break;
  24358. }
  24359. var end = pos;
  24360. return new CFFFDSelect(fdSelect, bytes.subarray(start, end));
  24361. }
  24362. };
  24363. return CFFParser;
  24364. })();
  24365. // Compact Font Format
  24366. var CFF = (function CFFClosure() {
  24367. function CFF() {
  24368. this.header = null;
  24369. this.names = [];
  24370. this.topDict = null;
  24371. this.strings = new CFFStrings();
  24372. this.globalSubrIndex = null;
  24373. // The following could really be per font, but since we only have one font
  24374. // store them here.
  24375. this.encoding = null;
  24376. this.charset = null;
  24377. this.charStrings = null;
  24378. this.fdArray = [];
  24379. this.fdSelect = null;
  24380. this.isCIDFont = false;
  24381. }
  24382. return CFF;
  24383. })();
  24384. var CFFHeader = (function CFFHeaderClosure() {
  24385. function CFFHeader(major, minor, hdrSize, offSize) {
  24386. this.major = major;
  24387. this.minor = minor;
  24388. this.hdrSize = hdrSize;
  24389. this.offSize = offSize;
  24390. }
  24391. return CFFHeader;
  24392. })();
  24393. var CFFStrings = (function CFFStringsClosure() {
  24394. function CFFStrings() {
  24395. this.strings = [];
  24396. }
  24397. CFFStrings.prototype = {
  24398. get: function CFFStrings_get(index) {
  24399. if (index >= 0 && index <= 390) {
  24400. return CFFStandardStrings[index];
  24401. }
  24402. if (index - 391 <= this.strings.length) {
  24403. return this.strings[index - 391];
  24404. }
  24405. return CFFStandardStrings[0];
  24406. },
  24407. add: function CFFStrings_add(value) {
  24408. this.strings.push(value);
  24409. },
  24410. get count() {
  24411. return this.strings.length;
  24412. }
  24413. };
  24414. return CFFStrings;
  24415. })();
  24416. var CFFIndex = (function CFFIndexClosure() {
  24417. function CFFIndex() {
  24418. this.objects = [];
  24419. this.length = 0;
  24420. }
  24421. CFFIndex.prototype = {
  24422. add: function CFFIndex_add(data) {
  24423. this.length += data.length;
  24424. this.objects.push(data);
  24425. },
  24426. set: function CFFIndex_set(index, data) {
  24427. this.length += data.length - this.objects[index].length;
  24428. this.objects[index] = data;
  24429. },
  24430. get: function CFFIndex_get(index) {
  24431. return this.objects[index];
  24432. },
  24433. get count() {
  24434. return this.objects.length;
  24435. }
  24436. };
  24437. return CFFIndex;
  24438. })();
  24439. var CFFDict = (function CFFDictClosure() {
  24440. function CFFDict(tables, strings) {
  24441. this.keyToNameMap = tables.keyToNameMap;
  24442. this.nameToKeyMap = tables.nameToKeyMap;
  24443. this.defaults = tables.defaults;
  24444. this.types = tables.types;
  24445. this.opcodes = tables.opcodes;
  24446. this.order = tables.order;
  24447. this.strings = strings;
  24448. this.values = {};
  24449. }
  24450. CFFDict.prototype = {
  24451. // value should always be an array
  24452. setByKey: function CFFDict_setByKey(key, value) {
  24453. if (!(key in this.keyToNameMap)) {
  24454. return false;
  24455. }
  24456. // ignore empty values
  24457. if (value.length === 0) {
  24458. return true;
  24459. }
  24460. var type = this.types[key];
  24461. // remove the array wrapping these types of values
  24462. if (type === 'num' || type === 'sid' || type === 'offset') {
  24463. value = value[0];
  24464. }
  24465. this.values[key] = value;
  24466. return true;
  24467. },
  24468. setByName: function CFFDict_setByName(name, value) {
  24469. if (!(name in this.nameToKeyMap)) {
  24470. error('Invalid dictionary name "' + name + '"');
  24471. }
  24472. this.values[this.nameToKeyMap[name]] = value;
  24473. },
  24474. hasName: function CFFDict_hasName(name) {
  24475. return this.nameToKeyMap[name] in this.values;
  24476. },
  24477. getByName: function CFFDict_getByName(name) {
  24478. if (!(name in this.nameToKeyMap)) {
  24479. error('Invalid dictionary name "' + name + '"');
  24480. }
  24481. var key = this.nameToKeyMap[name];
  24482. if (!(key in this.values)) {
  24483. return this.defaults[key];
  24484. }
  24485. return this.values[key];
  24486. },
  24487. removeByName: function CFFDict_removeByName(name) {
  24488. delete this.values[this.nameToKeyMap[name]];
  24489. }
  24490. };
  24491. CFFDict.createTables = function CFFDict_createTables(layout) {
  24492. var tables = {
  24493. keyToNameMap: {},
  24494. nameToKeyMap: {},
  24495. defaults: {},
  24496. types: {},
  24497. opcodes: {},
  24498. order: []
  24499. };
  24500. for (var i = 0, ii = layout.length; i < ii; ++i) {
  24501. var entry = layout[i];
  24502. var key = isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0];
  24503. tables.keyToNameMap[key] = entry[1];
  24504. tables.nameToKeyMap[entry[1]] = key;
  24505. tables.types[key] = entry[2];
  24506. tables.defaults[key] = entry[3];
  24507. tables.opcodes[key] = isArray(entry[0]) ? entry[0] : [entry[0]];
  24508. tables.order.push(key);
  24509. }
  24510. return tables;
  24511. };
  24512. return CFFDict;
  24513. })();
  24514. var CFFTopDict = (function CFFTopDictClosure() {
  24515. var layout = [
  24516. [[12, 30], 'ROS', ['sid', 'sid', 'num'], null],
  24517. [[12, 20], 'SyntheticBase', 'num', null],
  24518. [0, 'version', 'sid', null],
  24519. [1, 'Notice', 'sid', null],
  24520. [[12, 0], 'Copyright', 'sid', null],
  24521. [2, 'FullName', 'sid', null],
  24522. [3, 'FamilyName', 'sid', null],
  24523. [4, 'Weight', 'sid', null],
  24524. [[12, 1], 'isFixedPitch', 'num', 0],
  24525. [[12, 2], 'ItalicAngle', 'num', 0],
  24526. [[12, 3], 'UnderlinePosition', 'num', -100],
  24527. [[12, 4], 'UnderlineThickness', 'num', 50],
  24528. [[12, 5], 'PaintType', 'num', 0],
  24529. [[12, 6], 'CharstringType', 'num', 2],
  24530. [[12, 7], 'FontMatrix', ['num', 'num', 'num', 'num', 'num', 'num'],
  24531. [0.001, 0, 0, 0.001, 0, 0]],
  24532. [13, 'UniqueID', 'num', null],
  24533. [5, 'FontBBox', ['num', 'num', 'num', 'num'], [0, 0, 0, 0]],
  24534. [[12, 8], 'StrokeWidth', 'num', 0],
  24535. [14, 'XUID', 'array', null],
  24536. [15, 'charset', 'offset', 0],
  24537. [16, 'Encoding', 'offset', 0],
  24538. [17, 'CharStrings', 'offset', 0],
  24539. [18, 'Private', ['offset', 'offset'], null],
  24540. [[12, 21], 'PostScript', 'sid', null],
  24541. [[12, 22], 'BaseFontName', 'sid', null],
  24542. [[12, 23], 'BaseFontBlend', 'delta', null],
  24543. [[12, 31], 'CIDFontVersion', 'num', 0],
  24544. [[12, 32], 'CIDFontRevision', 'num', 0],
  24545. [[12, 33], 'CIDFontType', 'num', 0],
  24546. [[12, 34], 'CIDCount', 'num', 8720],
  24547. [[12, 35], 'UIDBase', 'num', null],
  24548. // XXX: CID Fonts on DirectWrite 6.1 only seem to work if FDSelect comes
  24549. // before FDArray.
  24550. [[12, 37], 'FDSelect', 'offset', null],
  24551. [[12, 36], 'FDArray', 'offset', null],
  24552. [[12, 38], 'FontName', 'sid', null]
  24553. ];
  24554. var tables = null;
  24555. function CFFTopDict(strings) {
  24556. if (tables === null) {
  24557. tables = CFFDict.createTables(layout);
  24558. }
  24559. CFFDict.call(this, tables, strings);
  24560. this.privateDict = null;
  24561. }
  24562. CFFTopDict.prototype = Object.create(CFFDict.prototype);
  24563. return CFFTopDict;
  24564. })();
  24565. var CFFPrivateDict = (function CFFPrivateDictClosure() {
  24566. var layout = [
  24567. [6, 'BlueValues', 'delta', null],
  24568. [7, 'OtherBlues', 'delta', null],
  24569. [8, 'FamilyBlues', 'delta', null],
  24570. [9, 'FamilyOtherBlues', 'delta', null],
  24571. [[12, 9], 'BlueScale', 'num', 0.039625],
  24572. [[12, 10], 'BlueShift', 'num', 7],
  24573. [[12, 11], 'BlueFuzz', 'num', 1],
  24574. [10, 'StdHW', 'num', null],
  24575. [11, 'StdVW', 'num', null],
  24576. [[12, 12], 'StemSnapH', 'delta', null],
  24577. [[12, 13], 'StemSnapV', 'delta', null],
  24578. [[12, 14], 'ForceBold', 'num', 0],
  24579. [[12, 17], 'LanguageGroup', 'num', 0],
  24580. [[12, 18], 'ExpansionFactor', 'num', 0.06],
  24581. [[12, 19], 'initialRandomSeed', 'num', 0],
  24582. [20, 'defaultWidthX', 'num', 0],
  24583. [21, 'nominalWidthX', 'num', 0],
  24584. [19, 'Subrs', 'offset', null]
  24585. ];
  24586. var tables = null;
  24587. function CFFPrivateDict(strings) {
  24588. if (tables === null) {
  24589. tables = CFFDict.createTables(layout);
  24590. }
  24591. CFFDict.call(this, tables, strings);
  24592. this.subrsIndex = null;
  24593. }
  24594. CFFPrivateDict.prototype = Object.create(CFFDict.prototype);
  24595. return CFFPrivateDict;
  24596. })();
  24597. var CFFCharsetPredefinedTypes = {
  24598. ISO_ADOBE: 0,
  24599. EXPERT: 1,
  24600. EXPERT_SUBSET: 2
  24601. };
  24602. var CFFCharset = (function CFFCharsetClosure() {
  24603. function CFFCharset(predefined, format, charset, raw) {
  24604. this.predefined = predefined;
  24605. this.format = format;
  24606. this.charset = charset;
  24607. this.raw = raw;
  24608. }
  24609. return CFFCharset;
  24610. })();
  24611. var CFFEncoding = (function CFFEncodingClosure() {
  24612. function CFFEncoding(predefined, format, encoding, raw) {
  24613. this.predefined = predefined;
  24614. this.format = format;
  24615. this.encoding = encoding;
  24616. this.raw = raw;
  24617. }
  24618. return CFFEncoding;
  24619. })();
  24620. var CFFFDSelect = (function CFFFDSelectClosure() {
  24621. function CFFFDSelect(fdSelect, raw) {
  24622. this.fdSelect = fdSelect;
  24623. this.raw = raw;
  24624. }
  24625. return CFFFDSelect;
  24626. })();
  24627. // Helper class to keep track of where an offset is within the data and helps
  24628. // filling in that offset once it's known.
  24629. var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
  24630. function CFFOffsetTracker() {
  24631. this.offsets = {};
  24632. }
  24633. CFFOffsetTracker.prototype = {
  24634. isTracking: function CFFOffsetTracker_isTracking(key) {
  24635. return key in this.offsets;
  24636. },
  24637. track: function CFFOffsetTracker_track(key, location) {
  24638. if (key in this.offsets) {
  24639. error('Already tracking location of ' + key);
  24640. }
  24641. this.offsets[key] = location;
  24642. },
  24643. offset: function CFFOffsetTracker_offset(value) {
  24644. for (var key in this.offsets) {
  24645. this.offsets[key] += value;
  24646. }
  24647. },
  24648. setEntryLocation: function CFFOffsetTracker_setEntryLocation(key,
  24649. values,
  24650. output) {
  24651. if (!(key in this.offsets)) {
  24652. error('Not tracking location of ' + key);
  24653. }
  24654. var data = output.data;
  24655. var dataOffset = this.offsets[key];
  24656. var size = 5;
  24657. for (var i = 0, ii = values.length; i < ii; ++i) {
  24658. var offset0 = i * size + dataOffset;
  24659. var offset1 = offset0 + 1;
  24660. var offset2 = offset0 + 2;
  24661. var offset3 = offset0 + 3;
  24662. var offset4 = offset0 + 4;
  24663. // It's easy to screw up offsets so perform this sanity check.
  24664. if (data[offset0] !== 0x1d || data[offset1] !== 0 ||
  24665. data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
  24666. error('writing to an offset that is not empty');
  24667. }
  24668. var value = values[i];
  24669. data[offset0] = 0x1d;
  24670. data[offset1] = (value >> 24) & 0xFF;
  24671. data[offset2] = (value >> 16) & 0xFF;
  24672. data[offset3] = (value >> 8) & 0xFF;
  24673. data[offset4] = value & 0xFF;
  24674. }
  24675. }
  24676. };
  24677. return CFFOffsetTracker;
  24678. })();
  24679. // Takes a CFF and converts it to the binary representation.
  24680. var CFFCompiler = (function CFFCompilerClosure() {
  24681. function CFFCompiler(cff) {
  24682. this.cff = cff;
  24683. }
  24684. CFFCompiler.prototype = {
  24685. compile: function CFFCompiler_compile() {
  24686. var cff = this.cff;
  24687. var output = {
  24688. data: [],
  24689. length: 0,
  24690. add: function CFFCompiler_add(data) {
  24691. this.data = this.data.concat(data);
  24692. this.length = this.data.length;
  24693. }
  24694. };
  24695. // Compile the five entries that must be in order.
  24696. var header = this.compileHeader(cff.header);
  24697. output.add(header);
  24698. var nameIndex = this.compileNameIndex(cff.names);
  24699. output.add(nameIndex);
  24700. if (cff.isCIDFont) {
  24701. // The spec is unclear on how font matrices should relate to each other
  24702. // when there is one in the main top dict and the sub top dicts.
  24703. // Windows handles this differently than linux and osx so we have to
  24704. // normalize to work on all.
  24705. // Rules based off of some mailing list discussions:
  24706. // - If main font has a matrix and subfont doesn't, use the main matrix.
  24707. // - If no main font matrix and there is a subfont matrix, use the
  24708. // subfont matrix.
  24709. // - If both have matrices, concat together.
  24710. // - If neither have matrices, use default.
  24711. // To make this work on all platforms we move the top matrix into each
  24712. // sub top dict and concat if necessary.
  24713. if (cff.topDict.hasName('FontMatrix')) {
  24714. var base = cff.topDict.getByName('FontMatrix');
  24715. cff.topDict.removeByName('FontMatrix');
  24716. for (var i = 0, ii = cff.fdArray.length; i < ii; i++) {
  24717. var subDict = cff.fdArray[i];
  24718. var matrix = base.slice(0);
  24719. if (subDict.hasName('FontMatrix')) {
  24720. matrix = Util.transform(matrix, subDict.getByName('FontMatrix'));
  24721. }
  24722. subDict.setByName('FontMatrix', matrix);
  24723. }
  24724. }
  24725. }
  24726. var compiled = this.compileTopDicts([cff.topDict],
  24727. output.length,
  24728. cff.isCIDFont);
  24729. output.add(compiled.output);
  24730. var topDictTracker = compiled.trackers[0];
  24731. var stringIndex = this.compileStringIndex(cff.strings.strings);
  24732. output.add(stringIndex);
  24733. var globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
  24734. output.add(globalSubrIndex);
  24735. // Now start on the other entries that have no specfic order.
  24736. if (cff.encoding && cff.topDict.hasName('Encoding')) {
  24737. if (cff.encoding.predefined) {
  24738. topDictTracker.setEntryLocation('Encoding', [cff.encoding.format],
  24739. output);
  24740. } else {
  24741. var encoding = this.compileEncoding(cff.encoding);
  24742. topDictTracker.setEntryLocation('Encoding', [output.length], output);
  24743. output.add(encoding);
  24744. }
  24745. }
  24746. if (cff.charset && cff.topDict.hasName('charset')) {
  24747. if (cff.charset.predefined) {
  24748. topDictTracker.setEntryLocation('charset', [cff.charset.format],
  24749. output);
  24750. } else {
  24751. var charset = this.compileCharset(cff.charset);
  24752. topDictTracker.setEntryLocation('charset', [output.length], output);
  24753. output.add(charset);
  24754. }
  24755. }
  24756. var charStrings = this.compileCharStrings(cff.charStrings);
  24757. topDictTracker.setEntryLocation('CharStrings', [output.length], output);
  24758. output.add(charStrings);
  24759. if (cff.isCIDFont) {
  24760. // For some reason FDSelect must be in front of FDArray on windows. OSX
  24761. // and linux don't seem to care.
  24762. topDictTracker.setEntryLocation('FDSelect', [output.length], output);
  24763. var fdSelect = this.compileFDSelect(cff.fdSelect.raw);
  24764. output.add(fdSelect);
  24765. // It is unclear if the sub font dictionary can have CID related
  24766. // dictionary keys, but the sanitizer doesn't like them so remove them.
  24767. compiled = this.compileTopDicts(cff.fdArray, output.length, true);
  24768. topDictTracker.setEntryLocation('FDArray', [output.length], output);
  24769. output.add(compiled.output);
  24770. var fontDictTrackers = compiled.trackers;
  24771. this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
  24772. }
  24773. this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
  24774. // If the font data ends with INDEX whose object data is zero-length,
  24775. // the sanitizer will bail out. Add a dummy byte to avoid that.
  24776. output.add([0]);
  24777. return output.data;
  24778. },
  24779. encodeNumber: function CFFCompiler_encodeNumber(value) {
  24780. if (parseFloat(value) === parseInt(value, 10) && !isNaN(value)) { // isInt
  24781. return this.encodeInteger(value);
  24782. } else {
  24783. return this.encodeFloat(value);
  24784. }
  24785. },
  24786. encodeFloat: function CFFCompiler_encodeFloat(num) {
  24787. var value = num.toString();
  24788. // rounding inaccurate doubles
  24789. var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
  24790. if (m) {
  24791. var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
  24792. value = (Math.round(num * epsilon) / epsilon).toString();
  24793. }
  24794. var nibbles = '';
  24795. var i, ii;
  24796. for (i = 0, ii = value.length; i < ii; ++i) {
  24797. var a = value[i];
  24798. if (a === 'e') {
  24799. nibbles += value[++i] === '-' ? 'c' : 'b';
  24800. } else if (a === '.') {
  24801. nibbles += 'a';
  24802. } else if (a === '-') {
  24803. nibbles += 'e';
  24804. } else {
  24805. nibbles += a;
  24806. }
  24807. }
  24808. nibbles += (nibbles.length & 1) ? 'f' : 'ff';
  24809. var out = [30];
  24810. for (i = 0, ii = nibbles.length; i < ii; i += 2) {
  24811. out.push(parseInt(nibbles.substr(i, 2), 16));
  24812. }
  24813. return out;
  24814. },
  24815. encodeInteger: function CFFCompiler_encodeInteger(value) {
  24816. var code;
  24817. if (value >= -107 && value <= 107) {
  24818. code = [value + 139];
  24819. } else if (value >= 108 && value <= 1131) {
  24820. value = [value - 108];
  24821. code = [(value >> 8) + 247, value & 0xFF];
  24822. } else if (value >= -1131 && value <= -108) {
  24823. value = -value - 108;
  24824. code = [(value >> 8) + 251, value & 0xFF];
  24825. } else if (value >= -32768 && value <= 32767) {
  24826. code = [0x1c, (value >> 8) & 0xFF, value & 0xFF];
  24827. } else {
  24828. code = [0x1d,
  24829. (value >> 24) & 0xFF,
  24830. (value >> 16) & 0xFF,
  24831. (value >> 8) & 0xFF,
  24832. value & 0xFF];
  24833. }
  24834. return code;
  24835. },
  24836. compileHeader: function CFFCompiler_compileHeader(header) {
  24837. return [
  24838. header.major,
  24839. header.minor,
  24840. header.hdrSize,
  24841. header.offSize
  24842. ];
  24843. },
  24844. compileNameIndex: function CFFCompiler_compileNameIndex(names) {
  24845. var nameIndex = new CFFIndex();
  24846. for (var i = 0, ii = names.length; i < ii; ++i) {
  24847. nameIndex.add(stringToBytes(names[i]));
  24848. }
  24849. return this.compileIndex(nameIndex);
  24850. },
  24851. compileTopDicts: function CFFCompiler_compileTopDicts(dicts,
  24852. length,
  24853. removeCidKeys) {
  24854. var fontDictTrackers = [];
  24855. var fdArrayIndex = new CFFIndex();
  24856. for (var i = 0, ii = dicts.length; i < ii; ++i) {
  24857. var fontDict = dicts[i];
  24858. if (removeCidKeys) {
  24859. fontDict.removeByName('CIDFontVersion');
  24860. fontDict.removeByName('CIDFontRevision');
  24861. fontDict.removeByName('CIDFontType');
  24862. fontDict.removeByName('CIDCount');
  24863. fontDict.removeByName('UIDBase');
  24864. }
  24865. var fontDictTracker = new CFFOffsetTracker();
  24866. var fontDictData = this.compileDict(fontDict, fontDictTracker);
  24867. fontDictTrackers.push(fontDictTracker);
  24868. fdArrayIndex.add(fontDictData);
  24869. fontDictTracker.offset(length);
  24870. }
  24871. fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
  24872. return {
  24873. trackers: fontDictTrackers,
  24874. output: fdArrayIndex
  24875. };
  24876. },
  24877. compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts,
  24878. trackers,
  24879. output) {
  24880. for (var i = 0, ii = dicts.length; i < ii; ++i) {
  24881. var fontDict = dicts[i];
  24882. assert(fontDict.privateDict && fontDict.hasName('Private'),
  24883. 'There must be an private dictionary.');
  24884. var privateDict = fontDict.privateDict;
  24885. var privateDictTracker = new CFFOffsetTracker();
  24886. var privateDictData = this.compileDict(privateDict, privateDictTracker);
  24887. var outputLength = output.length;
  24888. privateDictTracker.offset(outputLength);
  24889. if (!privateDictData.length) {
  24890. // The private dictionary was empty, set the output length to zero to
  24891. // ensure the offset length isn't out of bounds in the eyes of the
  24892. // sanitizer.
  24893. outputLength = 0;
  24894. }
  24895. trackers[i].setEntryLocation('Private',
  24896. [privateDictData.length, outputLength],
  24897. output);
  24898. output.add(privateDictData);
  24899. if (privateDict.subrsIndex && privateDict.hasName('Subrs')) {
  24900. var subrs = this.compileIndex(privateDict.subrsIndex);
  24901. privateDictTracker.setEntryLocation('Subrs', [privateDictData.length],
  24902. output);
  24903. output.add(subrs);
  24904. }
  24905. }
  24906. },
  24907. compileDict: function CFFCompiler_compileDict(dict, offsetTracker) {
  24908. var out = [];
  24909. // The dictionary keys must be in a certain order.
  24910. var order = dict.order;
  24911. for (var i = 0; i < order.length; ++i) {
  24912. var key = order[i];
  24913. if (!(key in dict.values)) {
  24914. continue;
  24915. }
  24916. var values = dict.values[key];
  24917. var types = dict.types[key];
  24918. if (!isArray(types)) {
  24919. types = [types];
  24920. }
  24921. if (!isArray(values)) {
  24922. values = [values];
  24923. }
  24924. // Remove any empty dict values.
  24925. if (values.length === 0) {
  24926. continue;
  24927. }
  24928. for (var j = 0, jj = types.length; j < jj; ++j) {
  24929. var type = types[j];
  24930. var value = values[j];
  24931. switch (type) {
  24932. case 'num':
  24933. case 'sid':
  24934. out = out.concat(this.encodeNumber(value));
  24935. break;
  24936. case 'offset':
  24937. // For offsets we just insert a 32bit integer so we don't have to
  24938. // deal with figuring out the length of the offset when it gets
  24939. // replaced later on by the compiler.
  24940. var name = dict.keyToNameMap[key];
  24941. // Some offsets have the offset and the length, so just record the
  24942. // position of the first one.
  24943. if (!offsetTracker.isTracking(name)) {
  24944. offsetTracker.track(name, out.length);
  24945. }
  24946. out = out.concat([0x1d, 0, 0, 0, 0]);
  24947. break;
  24948. case 'array':
  24949. case 'delta':
  24950. out = out.concat(this.encodeNumber(value));
  24951. for (var k = 1, kk = values.length; k < kk; ++k) {
  24952. out = out.concat(this.encodeNumber(values[k]));
  24953. }
  24954. break;
  24955. default:
  24956. error('Unknown data type of ' + type);
  24957. break;
  24958. }
  24959. }
  24960. out = out.concat(dict.opcodes[key]);
  24961. }
  24962. return out;
  24963. },
  24964. compileStringIndex: function CFFCompiler_compileStringIndex(strings) {
  24965. var stringIndex = new CFFIndex();
  24966. for (var i = 0, ii = strings.length; i < ii; ++i) {
  24967. stringIndex.add(stringToBytes(strings[i]));
  24968. }
  24969. return this.compileIndex(stringIndex);
  24970. },
  24971. compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() {
  24972. var globalSubrIndex = this.cff.globalSubrIndex;
  24973. this.out.writeByteArray(this.compileIndex(globalSubrIndex));
  24974. },
  24975. compileCharStrings: function CFFCompiler_compileCharStrings(charStrings) {
  24976. return this.compileIndex(charStrings);
  24977. },
  24978. compileCharset: function CFFCompiler_compileCharset(charset) {
  24979. return this.compileTypedArray(charset.raw);
  24980. },
  24981. compileEncoding: function CFFCompiler_compileEncoding(encoding) {
  24982. return this.compileTypedArray(encoding.raw);
  24983. },
  24984. compileFDSelect: function CFFCompiler_compileFDSelect(fdSelect) {
  24985. return this.compileTypedArray(fdSelect);
  24986. },
  24987. compileTypedArray: function CFFCompiler_compileTypedArray(data) {
  24988. var out = [];
  24989. for (var i = 0, ii = data.length; i < ii; ++i) {
  24990. out[i] = data[i];
  24991. }
  24992. return out;
  24993. },
  24994. compileIndex: function CFFCompiler_compileIndex(index, trackers) {
  24995. trackers = trackers || [];
  24996. var objects = index.objects;
  24997. // First 2 bytes contains the number of objects contained into this index
  24998. var count = objects.length;
  24999. // If there is no object, just create an index. This technically
  25000. // should just be [0, 0] but OTS has an issue with that.
  25001. if (count === 0) {
  25002. return [0, 0, 0];
  25003. }
  25004. var data = [(count >> 8) & 0xFF, count & 0xff];
  25005. var lastOffset = 1, i;
  25006. for (i = 0; i < count; ++i) {
  25007. lastOffset += objects[i].length;
  25008. }
  25009. var offsetSize;
  25010. if (lastOffset < 0x100) {
  25011. offsetSize = 1;
  25012. } else if (lastOffset < 0x10000) {
  25013. offsetSize = 2;
  25014. } else if (lastOffset < 0x1000000) {
  25015. offsetSize = 3;
  25016. } else {
  25017. offsetSize = 4;
  25018. }
  25019. // Next byte contains the offset size use to reference object in the file
  25020. data.push(offsetSize);
  25021. // Add another offset after this one because we need a new offset
  25022. var relativeOffset = 1;
  25023. for (i = 0; i < count + 1; i++) {
  25024. if (offsetSize === 1) {
  25025. data.push(relativeOffset & 0xFF);
  25026. } else if (offsetSize === 2) {
  25027. data.push((relativeOffset >> 8) & 0xFF,
  25028. relativeOffset & 0xFF);
  25029. } else if (offsetSize === 3) {
  25030. data.push((relativeOffset >> 16) & 0xFF,
  25031. (relativeOffset >> 8) & 0xFF,
  25032. relativeOffset & 0xFF);
  25033. } else {
  25034. data.push((relativeOffset >>> 24) & 0xFF,
  25035. (relativeOffset >> 16) & 0xFF,
  25036. (relativeOffset >> 8) & 0xFF,
  25037. relativeOffset & 0xFF);
  25038. }
  25039. if (objects[i]) {
  25040. relativeOffset += objects[i].length;
  25041. }
  25042. }
  25043. for (i = 0; i < count; i++) {
  25044. // Notify the tracker where the object will be offset in the data.
  25045. if (trackers[i]) {
  25046. trackers[i].offset(data.length);
  25047. }
  25048. for (var j = 0, jj = objects[i].length; j < jj; j++) {
  25049. data.push(objects[i][j]);
  25050. }
  25051. }
  25052. return data;
  25053. }
  25054. };
  25055. return CFFCompiler;
  25056. })();
  25057. // Workaround for seac on Windows.
  25058. (function checkSeacSupport() {
  25059. if (/Windows/.test(navigator.userAgent)) {
  25060. SEAC_ANALYSIS_ENABLED = true;
  25061. }
  25062. })();
  25063. // Workaround for Private Use Area characters in Chrome on Windows
  25064. // http://code.google.com/p/chromium/issues/detail?id=122465
  25065. // https://github.com/mozilla/pdf.js/issues/1689
  25066. (function checkChromeWindows() {
  25067. if (/Windows.*Chrome/.test(navigator.userAgent)) {
  25068. SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = true;
  25069. }
  25070. })();
  25071. var FontRendererFactory = (function FontRendererFactoryClosure() {
  25072. function getLong(data, offset) {
  25073. return (data[offset] << 24) | (data[offset + 1] << 16) |
  25074. (data[offset + 2] << 8) | data[offset + 3];
  25075. }
  25076. function getUshort(data, offset) {
  25077. return (data[offset] << 8) | data[offset + 1];
  25078. }
  25079. function parseCmap(data, start, end) {
  25080. var offset = (getUshort(data, start + 2) === 1 ?
  25081. getLong(data, start + 8) : getLong(data, start + 16));
  25082. var format = getUshort(data, start + offset);
  25083. var length, ranges, p, i;
  25084. if (format === 4) {
  25085. length = getUshort(data, start + offset + 2);
  25086. var segCount = getUshort(data, start + offset + 6) >> 1;
  25087. p = start + offset + 14;
  25088. ranges = [];
  25089. for (i = 0; i < segCount; i++, p += 2) {
  25090. ranges[i] = {end: getUshort(data, p)};
  25091. }
  25092. p += 2;
  25093. for (i = 0; i < segCount; i++, p += 2) {
  25094. ranges[i].start = getUshort(data, p);
  25095. }
  25096. for (i = 0; i < segCount; i++, p += 2) {
  25097. ranges[i].idDelta = getUshort(data, p);
  25098. }
  25099. for (i = 0; i < segCount; i++, p += 2) {
  25100. var idOffset = getUshort(data, p);
  25101. if (idOffset === 0) {
  25102. continue;
  25103. }
  25104. ranges[i].ids = [];
  25105. for (var j = 0, jj = ranges[i].end - ranges[i].start + 1; j < jj; j++) {
  25106. ranges[i].ids[j] = getUshort(data, p + idOffset);
  25107. idOffset += 2;
  25108. }
  25109. }
  25110. return ranges;
  25111. } else if (format === 12) {
  25112. length = getLong(data, start + offset + 4);
  25113. var groups = getLong(data, start + offset + 12);
  25114. p = start + offset + 16;
  25115. ranges = [];
  25116. for (i = 0; i < groups; i++) {
  25117. ranges.push({
  25118. start: getLong(data, p),
  25119. end: getLong(data, p + 4),
  25120. idDelta: getLong(data, p + 8) - getLong(data, p)
  25121. });
  25122. p += 12;
  25123. }
  25124. return ranges;
  25125. }
  25126. error('not supported cmap: ' + format);
  25127. }
  25128. function parseCff(data, start, end) {
  25129. var properties = {};
  25130. var parser = new CFFParser(new Stream(data, start, end - start),
  25131. properties);
  25132. var cff = parser.parse();
  25133. return {
  25134. glyphs: cff.charStrings.objects,
  25135. subrs: (cff.topDict.privateDict && cff.topDict.privateDict.subrsIndex &&
  25136. cff.topDict.privateDict.subrsIndex.objects),
  25137. gsubrs: cff.globalSubrIndex && cff.globalSubrIndex.objects
  25138. };
  25139. }
  25140. function parseGlyfTable(glyf, loca, isGlyphLocationsLong) {
  25141. var itemSize, itemDecode;
  25142. if (isGlyphLocationsLong) {
  25143. itemSize = 4;
  25144. itemDecode = function fontItemDecodeLong(data, offset) {
  25145. return (data[offset] << 24) | (data[offset + 1] << 16) |
  25146. (data[offset + 2] << 8) | data[offset + 3];
  25147. };
  25148. } else {
  25149. itemSize = 2;
  25150. itemDecode = function fontItemDecode(data, offset) {
  25151. return (data[offset] << 9) | (data[offset + 1] << 1);
  25152. };
  25153. }
  25154. var glyphs = [];
  25155. var startOffset = itemDecode(loca, 0);
  25156. for (var j = itemSize; j < loca.length; j += itemSize) {
  25157. var endOffset = itemDecode(loca, j);
  25158. glyphs.push(glyf.subarray(startOffset, endOffset));
  25159. startOffset = endOffset;
  25160. }
  25161. return glyphs;
  25162. }
  25163. function lookupCmap(ranges, unicode) {
  25164. var code = unicode.charCodeAt(0);
  25165. var l = 0, r = ranges.length - 1;
  25166. while (l < r) {
  25167. var c = (l + r + 1) >> 1;
  25168. if (code < ranges[c].start) {
  25169. r = c - 1;
  25170. } else {
  25171. l = c;
  25172. }
  25173. }
  25174. if (ranges[l].start <= code && code <= ranges[l].end) {
  25175. return (ranges[l].idDelta + (ranges[l].ids ?
  25176. ranges[l].ids[code - ranges[l].start] : code)) & 0xFFFF;
  25177. }
  25178. return 0;
  25179. }
  25180. function compileGlyf(code, js, font) {
  25181. function moveTo(x, y) {
  25182. js.push('c.moveTo(' + x + ',' + y + ');');
  25183. }
  25184. function lineTo(x, y) {
  25185. js.push('c.lineTo(' + x + ',' + y + ');');
  25186. }
  25187. function quadraticCurveTo(xa, ya, x, y) {
  25188. js.push('c.quadraticCurveTo(' + xa + ',' + ya + ',' +
  25189. x + ',' + y + ');');
  25190. }
  25191. var i = 0;
  25192. var numberOfContours = ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25193. var flags;
  25194. var x = 0, y = 0;
  25195. i += 10;
  25196. if (numberOfContours < 0) {
  25197. // composite glyph
  25198. do {
  25199. flags = (code[i] << 8) | code[i + 1];
  25200. var glyphIndex = (code[i + 2] << 8) | code[i + 3];
  25201. i += 4;
  25202. var arg1, arg2;
  25203. if ((flags & 0x01)) {
  25204. arg1 = ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25205. arg2 = ((code[i + 2] << 24) | (code[i + 3] << 16)) >> 16;
  25206. i += 4;
  25207. } else {
  25208. arg1 = code[i++]; arg2 = code[i++];
  25209. }
  25210. if ((flags & 0x02)) {
  25211. x = arg1;
  25212. y = arg2;
  25213. } else {
  25214. x = 0; y = 0; // TODO "they are points" ?
  25215. }
  25216. var scaleX = 1, scaleY = 1, scale01 = 0, scale10 = 0;
  25217. if ((flags & 0x08)) {
  25218. scaleX =
  25219. scaleY = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  25220. i += 2;
  25221. } else if ((flags & 0x40)) {
  25222. scaleX = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  25223. scaleY = ((code[i + 2] << 24) | (code[i + 3] << 16)) / 1073741824;
  25224. i += 4;
  25225. } else if ((flags & 0x80)) {
  25226. scaleX = ((code[i] << 24) | (code[i + 1] << 16)) / 1073741824;
  25227. scale01 = ((code[i + 2] << 24) | (code[i + 3] << 16)) / 1073741824;
  25228. scale10 = ((code[i + 4] << 24) | (code[i + 5] << 16)) / 1073741824;
  25229. scaleY = ((code[i + 6] << 24) | (code[i + 7] << 16)) / 1073741824;
  25230. i += 8;
  25231. }
  25232. var subglyph = font.glyphs[glyphIndex];
  25233. if (subglyph) {
  25234. js.push('c.save();');
  25235. js.push('c.transform(' + scaleX + ',' + scale01 + ',' +
  25236. scale10 + ',' + scaleY + ',' + x + ',' + y + ');');
  25237. compileGlyf(subglyph, js, font);
  25238. js.push('c.restore();');
  25239. }
  25240. } while ((flags & 0x20));
  25241. } else {
  25242. // simple glyph
  25243. var endPtsOfContours = [];
  25244. var j, jj;
  25245. for (j = 0; j < numberOfContours; j++) {
  25246. endPtsOfContours.push((code[i] << 8) | code[i + 1]);
  25247. i += 2;
  25248. }
  25249. var instructionLength = (code[i] << 8) | code[i + 1];
  25250. i += 2 + instructionLength; // skipping the instructions
  25251. var numberOfPoints = endPtsOfContours[endPtsOfContours.length - 1] + 1;
  25252. var points = [];
  25253. while (points.length < numberOfPoints) {
  25254. flags = code[i++];
  25255. var repeat = 1;
  25256. if ((flags & 0x08)) {
  25257. repeat += code[i++];
  25258. }
  25259. while (repeat-- > 0) {
  25260. points.push({flags: flags});
  25261. }
  25262. }
  25263. for (j = 0; j < numberOfPoints; j++) {
  25264. switch (points[j].flags & 0x12) {
  25265. case 0x00:
  25266. x += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25267. i += 2;
  25268. break;
  25269. case 0x02:
  25270. x -= code[i++];
  25271. break;
  25272. case 0x12:
  25273. x += code[i++];
  25274. break;
  25275. }
  25276. points[j].x = x;
  25277. }
  25278. for (j = 0; j < numberOfPoints; j++) {
  25279. switch (points[j].flags & 0x24) {
  25280. case 0x00:
  25281. y += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;
  25282. i += 2;
  25283. break;
  25284. case 0x04:
  25285. y -= code[i++];
  25286. break;
  25287. case 0x24:
  25288. y += code[i++];
  25289. break;
  25290. }
  25291. points[j].y = y;
  25292. }
  25293. var startPoint = 0;
  25294. for (i = 0; i < numberOfContours; i++) {
  25295. var endPoint = endPtsOfContours[i];
  25296. // contours might have implicit points, which is located in the middle
  25297. // between two neighboring off-curve points
  25298. var contour = points.slice(startPoint, endPoint + 1);
  25299. if ((contour[0].flags & 1)) {
  25300. contour.push(contour[0]); // using start point at the contour end
  25301. } else if ((contour[contour.length - 1].flags & 1)) {
  25302. // first is off-curve point, trying to use one from the end
  25303. contour.unshift(contour[contour.length - 1]);
  25304. } else {
  25305. // start and end are off-curve points, creating implicit one
  25306. var p = {
  25307. flags: 1,
  25308. x: (contour[0].x + contour[contour.length - 1].x) / 2,
  25309. y: (contour[0].y + contour[contour.length - 1].y) / 2
  25310. };
  25311. contour.unshift(p);
  25312. contour.push(p);
  25313. }
  25314. moveTo(contour[0].x, contour[0].y);
  25315. for (j = 1, jj = contour.length; j < jj; j++) {
  25316. if ((contour[j].flags & 1)) {
  25317. lineTo(contour[j].x, contour[j].y);
  25318. } else if ((contour[j + 1].flags & 1)){
  25319. quadraticCurveTo(contour[j].x, contour[j].y,
  25320. contour[j + 1].x, contour[j + 1].y);
  25321. j++;
  25322. } else {
  25323. quadraticCurveTo(contour[j].x, contour[j].y,
  25324. (contour[j].x + contour[j + 1].x) / 2,
  25325. (contour[j].y + contour[j + 1].y) / 2);
  25326. }
  25327. }
  25328. startPoint = endPoint + 1;
  25329. }
  25330. }
  25331. }
  25332. function compileCharString(code, js, font) {
  25333. var stack = [];
  25334. var x = 0, y = 0;
  25335. var stems = 0;
  25336. function moveTo(x, y) {
  25337. js.push('c.moveTo(' + x + ',' + y + ');');
  25338. }
  25339. function lineTo(x, y) {
  25340. js.push('c.lineTo(' + x + ',' + y + ');');
  25341. }
  25342. function bezierCurveTo(x1, y1, x2, y2, x, y) {
  25343. js.push('c.bezierCurveTo(' + x1 + ',' + y1 + ',' + x2 + ',' + y2 + ',' +
  25344. x + ',' + y + ');');
  25345. }
  25346. function parse(code) {
  25347. var i = 0;
  25348. while (i < code.length) {
  25349. var stackClean = false;
  25350. var v = code[i++];
  25351. var xa, xb, ya, yb, y1, y2, y3, n, subrCode;
  25352. switch (v) {
  25353. case 1: // hstem
  25354. stems += stack.length >> 1;
  25355. stackClean = true;
  25356. break;
  25357. case 3: // vstem
  25358. stems += stack.length >> 1;
  25359. stackClean = true;
  25360. break;
  25361. case 4: // vmoveto
  25362. y += stack.pop();
  25363. moveTo(x, y);
  25364. stackClean = true;
  25365. break;
  25366. case 5: // rlineto
  25367. while (stack.length > 0) {
  25368. x += stack.shift();
  25369. y += stack.shift();
  25370. lineTo(x, y);
  25371. }
  25372. break;
  25373. case 6: // hlineto
  25374. while (stack.length > 0) {
  25375. x += stack.shift();
  25376. lineTo(x, y);
  25377. if (stack.length === 0) {
  25378. break;
  25379. }
  25380. y += stack.shift();
  25381. lineTo(x, y);
  25382. }
  25383. break;
  25384. case 7: // vlineto
  25385. while (stack.length > 0) {
  25386. y += stack.shift();
  25387. lineTo(x, y);
  25388. if (stack.length === 0) {
  25389. break;
  25390. }
  25391. x += stack.shift();
  25392. lineTo(x, y);
  25393. }
  25394. break;
  25395. case 8: // rrcurveto
  25396. while (stack.length > 0) {
  25397. xa = x + stack.shift(); ya = y + stack.shift();
  25398. xb = xa + stack.shift(); yb = ya + stack.shift();
  25399. x = xb + stack.shift(); y = yb + stack.shift();
  25400. bezierCurveTo(xa, ya, xb, yb, x, y);
  25401. }
  25402. break;
  25403. case 10: // callsubr
  25404. n = stack.pop() + font.subrsBias;
  25405. subrCode = font.subrs[n];
  25406. if (subrCode) {
  25407. parse(subrCode);
  25408. }
  25409. break;
  25410. case 11: // return
  25411. return;
  25412. case 12:
  25413. v = code[i++];
  25414. switch (v) {
  25415. case 34: // flex
  25416. xa = x + stack.shift();
  25417. xb = xa + stack.shift(); y1 = y + stack.shift();
  25418. x = xb + stack.shift();
  25419. bezierCurveTo(xa, y, xb, y1, x, y1);
  25420. xa = x + stack.shift();
  25421. xb = xa + stack.shift();
  25422. x = xb + stack.shift();
  25423. bezierCurveTo(xa, y1, xb, y, x, y);
  25424. break;
  25425. case 35: // flex
  25426. xa = x + stack.shift(); ya = y + stack.shift();
  25427. xb = xa + stack.shift(); yb = ya + stack.shift();
  25428. x = xb + stack.shift(); y = yb + stack.shift();
  25429. bezierCurveTo(xa, ya, xb, yb, x, y);
  25430. xa = x + stack.shift(); ya = y + stack.shift();
  25431. xb = xa + stack.shift(); yb = ya + stack.shift();
  25432. x = xb + stack.shift(); y = yb + stack.shift();
  25433. bezierCurveTo(xa, ya, xb, yb, x, y);
  25434. stack.pop(); // fd
  25435. break;
  25436. case 36: // hflex1
  25437. xa = x + stack.shift(); y1 = y + stack.shift();
  25438. xb = xa + stack.shift(); y2 = y1 + stack.shift();
  25439. x = xb + stack.shift();
  25440. bezierCurveTo(xa, y1, xb, y2, x, y2);
  25441. xa = x + stack.shift();
  25442. xb = xa + stack.shift(); y3 = y2 + stack.shift();
  25443. x = xb + stack.shift();
  25444. bezierCurveTo(xa, y2, xb, y3, x, y);
  25445. break;
  25446. case 37: // flex1
  25447. var x0 = x, y0 = y;
  25448. xa = x + stack.shift(); ya = y + stack.shift();
  25449. xb = xa + stack.shift(); yb = ya + stack.shift();
  25450. x = xb + stack.shift(); y = yb + stack.shift();
  25451. bezierCurveTo(xa, ya, xb, yb, x, y);
  25452. xa = x + stack.shift(); ya = y + stack.shift();
  25453. xb = xa + stack.shift(); yb = ya + stack.shift();
  25454. x = xb; y = yb;
  25455. if (Math.abs(x - x0) > Math.abs(y - y0)) {
  25456. x += stack.shift();
  25457. } else {
  25458. y += stack.shift();
  25459. }
  25460. bezierCurveTo(xa, ya, xb, yb, x, y);
  25461. break;
  25462. default:
  25463. error('unknown operator: 12 ' + v);
  25464. }
  25465. break;
  25466. case 14: // endchar
  25467. if (stack.length >= 4) {
  25468. var achar = stack.pop();
  25469. var bchar = stack.pop();
  25470. y = stack.pop();
  25471. x = stack.pop();
  25472. js.push('c.save();');
  25473. js.push('c.translate('+ x + ',' + y + ');');
  25474. var gid = lookupCmap(font.cmap, String.fromCharCode(
  25475. font.glyphNameMap[Encodings.StandardEncoding[achar]]));
  25476. compileCharString(font.glyphs[gid], js, font);
  25477. js.push('c.restore();');
  25478. gid = lookupCmap(font.cmap, String.fromCharCode(
  25479. font.glyphNameMap[Encodings.StandardEncoding[bchar]]));
  25480. compileCharString(font.glyphs[gid], js, font);
  25481. }
  25482. return;
  25483. case 18: // hstemhm
  25484. stems += stack.length >> 1;
  25485. stackClean = true;
  25486. break;
  25487. case 19: // hintmask
  25488. stems += stack.length >> 1;
  25489. i += (stems + 7) >> 3;
  25490. stackClean = true;
  25491. break;
  25492. case 20: // cntrmask
  25493. stems += stack.length >> 1;
  25494. i += (stems + 7) >> 3;
  25495. stackClean = true;
  25496. break;
  25497. case 21: // rmoveto
  25498. y += stack.pop();
  25499. x += stack.pop();
  25500. moveTo(x, y);
  25501. stackClean = true;
  25502. break;
  25503. case 22: // hmoveto
  25504. x += stack.pop();
  25505. moveTo(x, y);
  25506. stackClean = true;
  25507. break;
  25508. case 23: // vstemhm
  25509. stems += stack.length >> 1;
  25510. stackClean = true;
  25511. break;
  25512. case 24: // rcurveline
  25513. while (stack.length > 2) {
  25514. xa = x + stack.shift(); ya = y + stack.shift();
  25515. xb = xa + stack.shift(); yb = ya + stack.shift();
  25516. x = xb + stack.shift(); y = yb + stack.shift();
  25517. bezierCurveTo(xa, ya, xb, yb, x, y);
  25518. }
  25519. x += stack.shift();
  25520. y += stack.shift();
  25521. lineTo(x, y);
  25522. break;
  25523. case 25: // rlinecurve
  25524. while (stack.length > 6) {
  25525. x += stack.shift();
  25526. y += stack.shift();
  25527. lineTo(x, y);
  25528. }
  25529. xa = x + stack.shift(); ya = y + stack.shift();
  25530. xb = xa + stack.shift(); yb = ya + stack.shift();
  25531. x = xb + stack.shift(); y = yb + stack.shift();
  25532. bezierCurveTo(xa, ya, xb, yb, x, y);
  25533. break;
  25534. case 26: // vvcurveto
  25535. if (stack.length % 2) {
  25536. x += stack.shift();
  25537. }
  25538. while (stack.length > 0) {
  25539. xa = x; ya = y + stack.shift();
  25540. xb = xa + stack.shift(); yb = ya + stack.shift();
  25541. x = xb; y = yb + stack.shift();
  25542. bezierCurveTo(xa, ya, xb, yb, x, y);
  25543. }
  25544. break;
  25545. case 27: // hhcurveto
  25546. if (stack.length % 2) {
  25547. y += stack.shift();
  25548. }
  25549. while (stack.length > 0) {
  25550. xa = x + stack.shift(); ya = y;
  25551. xb = xa + stack.shift(); yb = ya + stack.shift();
  25552. x = xb + stack.shift(); y = yb;
  25553. bezierCurveTo(xa, ya, xb, yb, x, y);
  25554. }
  25555. break;
  25556. case 28:
  25557. stack.push(((code[i] << 24) | (code[i + 1] << 16)) >> 16);
  25558. i += 2;
  25559. break;
  25560. case 29: // callgsubr
  25561. n = stack.pop() + font.gsubrsBias;
  25562. subrCode = font.gsubrs[n];
  25563. if (subrCode) {
  25564. parse(subrCode);
  25565. }
  25566. break;
  25567. case 30: // vhcurveto
  25568. while (stack.length > 0) {
  25569. xa = x; ya = y + stack.shift();
  25570. xb = xa + stack.shift(); yb = ya + stack.shift();
  25571. x = xb + stack.shift();
  25572. y = yb + (stack.length === 1 ? stack.shift() : 0);
  25573. bezierCurveTo(xa, ya, xb, yb, x, y);
  25574. if (stack.length === 0) {
  25575. break;
  25576. }
  25577. xa = x + stack.shift(); ya = y;
  25578. xb = xa + stack.shift(); yb = ya + stack.shift();
  25579. y = yb + stack.shift();
  25580. x = xb + (stack.length === 1 ? stack.shift() : 0);
  25581. bezierCurveTo(xa, ya, xb, yb, x, y);
  25582. }
  25583. break;
  25584. case 31: // hvcurveto
  25585. while (stack.length > 0) {
  25586. xa = x + stack.shift(); ya = y;
  25587. xb = xa + stack.shift(); yb = ya + stack.shift();
  25588. y = yb + stack.shift();
  25589. x = xb + (stack.length === 1 ? stack.shift() : 0);
  25590. bezierCurveTo(xa, ya, xb, yb, x, y);
  25591. if (stack.length === 0) {
  25592. break;
  25593. }
  25594. xa = x; ya = y + stack.shift();
  25595. xb = xa + stack.shift(); yb = ya + stack.shift();
  25596. x = xb + stack.shift();
  25597. y = yb + (stack.length === 1 ? stack.shift() : 0);
  25598. bezierCurveTo(xa, ya, xb, yb, x, y);
  25599. }
  25600. break;
  25601. default:
  25602. if (v < 32) {
  25603. error('unknown operator: ' + v);
  25604. }
  25605. if (v < 247) {
  25606. stack.push(v - 139);
  25607. } else if (v < 251) {
  25608. stack.push((v - 247) * 256 + code[i++] + 108);
  25609. } else if (v < 255) {
  25610. stack.push(-(v - 251) * 256 - code[i++] - 108);
  25611. } else {
  25612. stack.push(((code[i] << 24) | (code[i + 1] << 16) |
  25613. (code[i + 2] << 8) | code[i + 3]) / 65536);
  25614. i += 4;
  25615. }
  25616. break;
  25617. }
  25618. if (stackClean) {
  25619. stack.length = 0;
  25620. }
  25621. }
  25622. }
  25623. parse(code);
  25624. }
  25625. var noop = '';
  25626. function CompiledFont(fontMatrix) {
  25627. this.compiledGlyphs = {};
  25628. this.fontMatrix = fontMatrix;
  25629. }
  25630. CompiledFont.prototype = {
  25631. getPathJs: function (unicode) {
  25632. var gid = lookupCmap(this.cmap, unicode);
  25633. var fn = this.compiledGlyphs[gid];
  25634. if (!fn) {
  25635. this.compiledGlyphs[gid] = fn = this.compileGlyph(this.glyphs[gid]);
  25636. }
  25637. return fn;
  25638. },
  25639. compileGlyph: function (code) {
  25640. if (!code || code.length === 0 || code[0] === 14) {
  25641. return noop;
  25642. }
  25643. var js = [];
  25644. js.push('c.save();');
  25645. js.push('c.transform(' + this.fontMatrix.join(',') + ');');
  25646. js.push('c.scale(size, -size);');
  25647. this.compileGlyphImpl(code, js);
  25648. js.push('c.restore();');
  25649. return js.join('\n');
  25650. },
  25651. compileGlyphImpl: function () {
  25652. error('Children classes should implement this.');
  25653. },
  25654. hasBuiltPath: function (unicode) {
  25655. var gid = lookupCmap(this.cmap, unicode);
  25656. return gid in this.compiledGlyphs;
  25657. }
  25658. };
  25659. function TrueTypeCompiled(glyphs, cmap, fontMatrix) {
  25660. fontMatrix = fontMatrix || [0.000488, 0, 0, 0.000488, 0, 0];
  25661. CompiledFont.call(this, fontMatrix);
  25662. this.glyphs = glyphs;
  25663. this.cmap = cmap;
  25664. this.compiledGlyphs = [];
  25665. }
  25666. Util.inherit(TrueTypeCompiled, CompiledFont, {
  25667. compileGlyphImpl: function (code, js) {
  25668. compileGlyf(code, js, this);
  25669. }
  25670. });
  25671. function Type2Compiled(cffInfo, cmap, fontMatrix, glyphNameMap) {
  25672. fontMatrix = fontMatrix || [0.001, 0, 0, 0.001, 0, 0];
  25673. CompiledFont.call(this, fontMatrix);
  25674. this.glyphs = cffInfo.glyphs;
  25675. this.gsubrs = cffInfo.gsubrs || [];
  25676. this.subrs = cffInfo.subrs || [];
  25677. this.cmap = cmap;
  25678. this.glyphNameMap = glyphNameMap || GlyphsUnicode;
  25679. this.compiledGlyphs = [];
  25680. this.gsubrsBias = (this.gsubrs.length < 1240 ?
  25681. 107 : (this.gsubrs.length < 33900 ? 1131 : 32768));
  25682. this.subrsBias = (this.subrs.length < 1240 ?
  25683. 107 : (this.subrs.length < 33900 ? 1131 : 32768));
  25684. }
  25685. Util.inherit(Type2Compiled, CompiledFont, {
  25686. compileGlyphImpl: function (code, js) {
  25687. compileCharString(code, js, this);
  25688. }
  25689. });
  25690. return {
  25691. create: function FontRendererFactory_create(font) {
  25692. var data = new Uint8Array(font.data);
  25693. var cmap, glyf, loca, cff, indexToLocFormat, unitsPerEm;
  25694. var numTables = getUshort(data, 4);
  25695. for (var i = 0, p = 12; i < numTables; i++, p += 16) {
  25696. var tag = bytesToString(data.subarray(p, p + 4));
  25697. var offset = getLong(data, p + 8);
  25698. var length = getLong(data, p + 12);
  25699. switch (tag) {
  25700. case 'cmap':
  25701. cmap = parseCmap(data, offset, offset + length);
  25702. break;
  25703. case 'glyf':
  25704. glyf = data.subarray(offset, offset + length);
  25705. break;
  25706. case 'loca':
  25707. loca = data.subarray(offset, offset + length);
  25708. break;
  25709. case 'head':
  25710. unitsPerEm = getUshort(data, offset + 18);
  25711. indexToLocFormat = getUshort(data, offset + 50);
  25712. break;
  25713. case 'CFF ':
  25714. cff = parseCff(data, offset, offset + length);
  25715. break;
  25716. }
  25717. }
  25718. if (glyf) {
  25719. var fontMatrix = (!unitsPerEm ? font.fontMatrix :
  25720. [1 / unitsPerEm, 0, 0, 1 / unitsPerEm, 0, 0]);
  25721. return new TrueTypeCompiled(
  25722. parseGlyfTable(glyf, loca, indexToLocFormat), cmap, fontMatrix);
  25723. } else {
  25724. return new Type2Compiled(cff, cmap, font.fontMatrix, font.glyphNameMap);
  25725. }
  25726. }
  25727. };
  25728. })();
  25729. var GlyphsUnicode = {
  25730. A: 0x0041,
  25731. AE: 0x00C6,
  25732. AEacute: 0x01FC,
  25733. AEmacron: 0x01E2,
  25734. AEsmall: 0xF7E6,
  25735. Aacute: 0x00C1,
  25736. Aacutesmall: 0xF7E1,
  25737. Abreve: 0x0102,
  25738. Abreveacute: 0x1EAE,
  25739. Abrevecyrillic: 0x04D0,
  25740. Abrevedotbelow: 0x1EB6,
  25741. Abrevegrave: 0x1EB0,
  25742. Abrevehookabove: 0x1EB2,
  25743. Abrevetilde: 0x1EB4,
  25744. Acaron: 0x01CD,
  25745. Acircle: 0x24B6,
  25746. Acircumflex: 0x00C2,
  25747. Acircumflexacute: 0x1EA4,
  25748. Acircumflexdotbelow: 0x1EAC,
  25749. Acircumflexgrave: 0x1EA6,
  25750. Acircumflexhookabove: 0x1EA8,
  25751. Acircumflexsmall: 0xF7E2,
  25752. Acircumflextilde: 0x1EAA,
  25753. Acute: 0xF6C9,
  25754. Acutesmall: 0xF7B4,
  25755. Acyrillic: 0x0410,
  25756. Adblgrave: 0x0200,
  25757. Adieresis: 0x00C4,
  25758. Adieresiscyrillic: 0x04D2,
  25759. Adieresismacron: 0x01DE,
  25760. Adieresissmall: 0xF7E4,
  25761. Adotbelow: 0x1EA0,
  25762. Adotmacron: 0x01E0,
  25763. Agrave: 0x00C0,
  25764. Agravesmall: 0xF7E0,
  25765. Ahookabove: 0x1EA2,
  25766. Aiecyrillic: 0x04D4,
  25767. Ainvertedbreve: 0x0202,
  25768. Alpha: 0x0391,
  25769. Alphatonos: 0x0386,
  25770. Amacron: 0x0100,
  25771. Amonospace: 0xFF21,
  25772. Aogonek: 0x0104,
  25773. Aring: 0x00C5,
  25774. Aringacute: 0x01FA,
  25775. Aringbelow: 0x1E00,
  25776. Aringsmall: 0xF7E5,
  25777. Asmall: 0xF761,
  25778. Atilde: 0x00C3,
  25779. Atildesmall: 0xF7E3,
  25780. Aybarmenian: 0x0531,
  25781. B: 0x0042,
  25782. Bcircle: 0x24B7,
  25783. Bdotaccent: 0x1E02,
  25784. Bdotbelow: 0x1E04,
  25785. Becyrillic: 0x0411,
  25786. Benarmenian: 0x0532,
  25787. Beta: 0x0392,
  25788. Bhook: 0x0181,
  25789. Blinebelow: 0x1E06,
  25790. Bmonospace: 0xFF22,
  25791. Brevesmall: 0xF6F4,
  25792. Bsmall: 0xF762,
  25793. Btopbar: 0x0182,
  25794. C: 0x0043,
  25795. Caarmenian: 0x053E,
  25796. Cacute: 0x0106,
  25797. Caron: 0xF6CA,
  25798. Caronsmall: 0xF6F5,
  25799. Ccaron: 0x010C,
  25800. Ccedilla: 0x00C7,
  25801. Ccedillaacute: 0x1E08,
  25802. Ccedillasmall: 0xF7E7,
  25803. Ccircle: 0x24B8,
  25804. Ccircumflex: 0x0108,
  25805. Cdot: 0x010A,
  25806. Cdotaccent: 0x010A,
  25807. Cedillasmall: 0xF7B8,
  25808. Chaarmenian: 0x0549,
  25809. Cheabkhasiancyrillic: 0x04BC,
  25810. Checyrillic: 0x0427,
  25811. Chedescenderabkhasiancyrillic: 0x04BE,
  25812. Chedescendercyrillic: 0x04B6,
  25813. Chedieresiscyrillic: 0x04F4,
  25814. Cheharmenian: 0x0543,
  25815. Chekhakassiancyrillic: 0x04CB,
  25816. Cheverticalstrokecyrillic: 0x04B8,
  25817. Chi: 0x03A7,
  25818. Chook: 0x0187,
  25819. Circumflexsmall: 0xF6F6,
  25820. Cmonospace: 0xFF23,
  25821. Coarmenian: 0x0551,
  25822. Csmall: 0xF763,
  25823. D: 0x0044,
  25824. DZ: 0x01F1,
  25825. DZcaron: 0x01C4,
  25826. Daarmenian: 0x0534,
  25827. Dafrican: 0x0189,
  25828. Dcaron: 0x010E,
  25829. Dcedilla: 0x1E10,
  25830. Dcircle: 0x24B9,
  25831. Dcircumflexbelow: 0x1E12,
  25832. Dcroat: 0x0110,
  25833. Ddotaccent: 0x1E0A,
  25834. Ddotbelow: 0x1E0C,
  25835. Decyrillic: 0x0414,
  25836. Deicoptic: 0x03EE,
  25837. Delta: 0x2206,
  25838. Deltagreek: 0x0394,
  25839. Dhook: 0x018A,
  25840. Dieresis: 0xF6CB,
  25841. DieresisAcute: 0xF6CC,
  25842. DieresisGrave: 0xF6CD,
  25843. Dieresissmall: 0xF7A8,
  25844. Digammagreek: 0x03DC,
  25845. Djecyrillic: 0x0402,
  25846. Dlinebelow: 0x1E0E,
  25847. Dmonospace: 0xFF24,
  25848. Dotaccentsmall: 0xF6F7,
  25849. Dslash: 0x0110,
  25850. Dsmall: 0xF764,
  25851. Dtopbar: 0x018B,
  25852. Dz: 0x01F2,
  25853. Dzcaron: 0x01C5,
  25854. Dzeabkhasiancyrillic: 0x04E0,
  25855. Dzecyrillic: 0x0405,
  25856. Dzhecyrillic: 0x040F,
  25857. E: 0x0045,
  25858. Eacute: 0x00C9,
  25859. Eacutesmall: 0xF7E9,
  25860. Ebreve: 0x0114,
  25861. Ecaron: 0x011A,
  25862. Ecedillabreve: 0x1E1C,
  25863. Echarmenian: 0x0535,
  25864. Ecircle: 0x24BA,
  25865. Ecircumflex: 0x00CA,
  25866. Ecircumflexacute: 0x1EBE,
  25867. Ecircumflexbelow: 0x1E18,
  25868. Ecircumflexdotbelow: 0x1EC6,
  25869. Ecircumflexgrave: 0x1EC0,
  25870. Ecircumflexhookabove: 0x1EC2,
  25871. Ecircumflexsmall: 0xF7EA,
  25872. Ecircumflextilde: 0x1EC4,
  25873. Ecyrillic: 0x0404,
  25874. Edblgrave: 0x0204,
  25875. Edieresis: 0x00CB,
  25876. Edieresissmall: 0xF7EB,
  25877. Edot: 0x0116,
  25878. Edotaccent: 0x0116,
  25879. Edotbelow: 0x1EB8,
  25880. Efcyrillic: 0x0424,
  25881. Egrave: 0x00C8,
  25882. Egravesmall: 0xF7E8,
  25883. Eharmenian: 0x0537,
  25884. Ehookabove: 0x1EBA,
  25885. Eightroman: 0x2167,
  25886. Einvertedbreve: 0x0206,
  25887. Eiotifiedcyrillic: 0x0464,
  25888. Elcyrillic: 0x041B,
  25889. Elevenroman: 0x216A,
  25890. Emacron: 0x0112,
  25891. Emacronacute: 0x1E16,
  25892. Emacrongrave: 0x1E14,
  25893. Emcyrillic: 0x041C,
  25894. Emonospace: 0xFF25,
  25895. Encyrillic: 0x041D,
  25896. Endescendercyrillic: 0x04A2,
  25897. Eng: 0x014A,
  25898. Enghecyrillic: 0x04A4,
  25899. Enhookcyrillic: 0x04C7,
  25900. Eogonek: 0x0118,
  25901. Eopen: 0x0190,
  25902. Epsilon: 0x0395,
  25903. Epsilontonos: 0x0388,
  25904. Ercyrillic: 0x0420,
  25905. Ereversed: 0x018E,
  25906. Ereversedcyrillic: 0x042D,
  25907. Escyrillic: 0x0421,
  25908. Esdescendercyrillic: 0x04AA,
  25909. Esh: 0x01A9,
  25910. Esmall: 0xF765,
  25911. Eta: 0x0397,
  25912. Etarmenian: 0x0538,
  25913. Etatonos: 0x0389,
  25914. Eth: 0x00D0,
  25915. Ethsmall: 0xF7F0,
  25916. Etilde: 0x1EBC,
  25917. Etildebelow: 0x1E1A,
  25918. Euro: 0x20AC,
  25919. Ezh: 0x01B7,
  25920. Ezhcaron: 0x01EE,
  25921. Ezhreversed: 0x01B8,
  25922. F: 0x0046,
  25923. Fcircle: 0x24BB,
  25924. Fdotaccent: 0x1E1E,
  25925. Feharmenian: 0x0556,
  25926. Feicoptic: 0x03E4,
  25927. Fhook: 0x0191,
  25928. Fitacyrillic: 0x0472,
  25929. Fiveroman: 0x2164,
  25930. Fmonospace: 0xFF26,
  25931. Fourroman: 0x2163,
  25932. Fsmall: 0xF766,
  25933. G: 0x0047,
  25934. GBsquare: 0x3387,
  25935. Gacute: 0x01F4,
  25936. Gamma: 0x0393,
  25937. Gammaafrican: 0x0194,
  25938. Gangiacoptic: 0x03EA,
  25939. Gbreve: 0x011E,
  25940. Gcaron: 0x01E6,
  25941. Gcedilla: 0x0122,
  25942. Gcircle: 0x24BC,
  25943. Gcircumflex: 0x011C,
  25944. Gcommaaccent: 0x0122,
  25945. Gdot: 0x0120,
  25946. Gdotaccent: 0x0120,
  25947. Gecyrillic: 0x0413,
  25948. Ghadarmenian: 0x0542,
  25949. Ghemiddlehookcyrillic: 0x0494,
  25950. Ghestrokecyrillic: 0x0492,
  25951. Gheupturncyrillic: 0x0490,
  25952. Ghook: 0x0193,
  25953. Gimarmenian: 0x0533,
  25954. Gjecyrillic: 0x0403,
  25955. Gmacron: 0x1E20,
  25956. Gmonospace: 0xFF27,
  25957. Grave: 0xF6CE,
  25958. Gravesmall: 0xF760,
  25959. Gsmall: 0xF767,
  25960. Gsmallhook: 0x029B,
  25961. Gstroke: 0x01E4,
  25962. H: 0x0048,
  25963. H18533: 0x25CF,
  25964. H18543: 0x25AA,
  25965. H18551: 0x25AB,
  25966. H22073: 0x25A1,
  25967. HPsquare: 0x33CB,
  25968. Haabkhasiancyrillic: 0x04A8,
  25969. Hadescendercyrillic: 0x04B2,
  25970. Hardsigncyrillic: 0x042A,
  25971. Hbar: 0x0126,
  25972. Hbrevebelow: 0x1E2A,
  25973. Hcedilla: 0x1E28,
  25974. Hcircle: 0x24BD,
  25975. Hcircumflex: 0x0124,
  25976. Hdieresis: 0x1E26,
  25977. Hdotaccent: 0x1E22,
  25978. Hdotbelow: 0x1E24,
  25979. Hmonospace: 0xFF28,
  25980. Hoarmenian: 0x0540,
  25981. Horicoptic: 0x03E8,
  25982. Hsmall: 0xF768,
  25983. Hungarumlaut: 0xF6CF,
  25984. Hungarumlautsmall: 0xF6F8,
  25985. Hzsquare: 0x3390,
  25986. I: 0x0049,
  25987. IAcyrillic: 0x042F,
  25988. IJ: 0x0132,
  25989. IUcyrillic: 0x042E,
  25990. Iacute: 0x00CD,
  25991. Iacutesmall: 0xF7ED,
  25992. Ibreve: 0x012C,
  25993. Icaron: 0x01CF,
  25994. Icircle: 0x24BE,
  25995. Icircumflex: 0x00CE,
  25996. Icircumflexsmall: 0xF7EE,
  25997. Icyrillic: 0x0406,
  25998. Idblgrave: 0x0208,
  25999. Idieresis: 0x00CF,
  26000. Idieresisacute: 0x1E2E,
  26001. Idieresiscyrillic: 0x04E4,
  26002. Idieresissmall: 0xF7EF,
  26003. Idot: 0x0130,
  26004. Idotaccent: 0x0130,
  26005. Idotbelow: 0x1ECA,
  26006. Iebrevecyrillic: 0x04D6,
  26007. Iecyrillic: 0x0415,
  26008. Ifraktur: 0x2111,
  26009. Igrave: 0x00CC,
  26010. Igravesmall: 0xF7EC,
  26011. Ihookabove: 0x1EC8,
  26012. Iicyrillic: 0x0418,
  26013. Iinvertedbreve: 0x020A,
  26014. Iishortcyrillic: 0x0419,
  26015. Imacron: 0x012A,
  26016. Imacroncyrillic: 0x04E2,
  26017. Imonospace: 0xFF29,
  26018. Iniarmenian: 0x053B,
  26019. Iocyrillic: 0x0401,
  26020. Iogonek: 0x012E,
  26021. Iota: 0x0399,
  26022. Iotaafrican: 0x0196,
  26023. Iotadieresis: 0x03AA,
  26024. Iotatonos: 0x038A,
  26025. Ismall: 0xF769,
  26026. Istroke: 0x0197,
  26027. Itilde: 0x0128,
  26028. Itildebelow: 0x1E2C,
  26029. Izhitsacyrillic: 0x0474,
  26030. Izhitsadblgravecyrillic: 0x0476,
  26031. J: 0x004A,
  26032. Jaarmenian: 0x0541,
  26033. Jcircle: 0x24BF,
  26034. Jcircumflex: 0x0134,
  26035. Jecyrillic: 0x0408,
  26036. Jheharmenian: 0x054B,
  26037. Jmonospace: 0xFF2A,
  26038. Jsmall: 0xF76A,
  26039. K: 0x004B,
  26040. KBsquare: 0x3385,
  26041. KKsquare: 0x33CD,
  26042. Kabashkircyrillic: 0x04A0,
  26043. Kacute: 0x1E30,
  26044. Kacyrillic: 0x041A,
  26045. Kadescendercyrillic: 0x049A,
  26046. Kahookcyrillic: 0x04C3,
  26047. Kappa: 0x039A,
  26048. Kastrokecyrillic: 0x049E,
  26049. Kaverticalstrokecyrillic: 0x049C,
  26050. Kcaron: 0x01E8,
  26051. Kcedilla: 0x0136,
  26052. Kcircle: 0x24C0,
  26053. Kcommaaccent: 0x0136,
  26054. Kdotbelow: 0x1E32,
  26055. Keharmenian: 0x0554,
  26056. Kenarmenian: 0x053F,
  26057. Khacyrillic: 0x0425,
  26058. Kheicoptic: 0x03E6,
  26059. Khook: 0x0198,
  26060. Kjecyrillic: 0x040C,
  26061. Klinebelow: 0x1E34,
  26062. Kmonospace: 0xFF2B,
  26063. Koppacyrillic: 0x0480,
  26064. Koppagreek: 0x03DE,
  26065. Ksicyrillic: 0x046E,
  26066. Ksmall: 0xF76B,
  26067. L: 0x004C,
  26068. LJ: 0x01C7,
  26069. LL: 0xF6BF,
  26070. Lacute: 0x0139,
  26071. Lambda: 0x039B,
  26072. Lcaron: 0x013D,
  26073. Lcedilla: 0x013B,
  26074. Lcircle: 0x24C1,
  26075. Lcircumflexbelow: 0x1E3C,
  26076. Lcommaaccent: 0x013B,
  26077. Ldot: 0x013F,
  26078. Ldotaccent: 0x013F,
  26079. Ldotbelow: 0x1E36,
  26080. Ldotbelowmacron: 0x1E38,
  26081. Liwnarmenian: 0x053C,
  26082. Lj: 0x01C8,
  26083. Ljecyrillic: 0x0409,
  26084. Llinebelow: 0x1E3A,
  26085. Lmonospace: 0xFF2C,
  26086. Lslash: 0x0141,
  26087. Lslashsmall: 0xF6F9,
  26088. Lsmall: 0xF76C,
  26089. M: 0x004D,
  26090. MBsquare: 0x3386,
  26091. Macron: 0xF6D0,
  26092. Macronsmall: 0xF7AF,
  26093. Macute: 0x1E3E,
  26094. Mcircle: 0x24C2,
  26095. Mdotaccent: 0x1E40,
  26096. Mdotbelow: 0x1E42,
  26097. Menarmenian: 0x0544,
  26098. Mmonospace: 0xFF2D,
  26099. Msmall: 0xF76D,
  26100. Mturned: 0x019C,
  26101. Mu: 0x039C,
  26102. N: 0x004E,
  26103. NJ: 0x01CA,
  26104. Nacute: 0x0143,
  26105. Ncaron: 0x0147,
  26106. Ncedilla: 0x0145,
  26107. Ncircle: 0x24C3,
  26108. Ncircumflexbelow: 0x1E4A,
  26109. Ncommaaccent: 0x0145,
  26110. Ndotaccent: 0x1E44,
  26111. Ndotbelow: 0x1E46,
  26112. Nhookleft: 0x019D,
  26113. Nineroman: 0x2168,
  26114. Nj: 0x01CB,
  26115. Njecyrillic: 0x040A,
  26116. Nlinebelow: 0x1E48,
  26117. Nmonospace: 0xFF2E,
  26118. Nowarmenian: 0x0546,
  26119. Nsmall: 0xF76E,
  26120. Ntilde: 0x00D1,
  26121. Ntildesmall: 0xF7F1,
  26122. Nu: 0x039D,
  26123. O: 0x004F,
  26124. OE: 0x0152,
  26125. OEsmall: 0xF6FA,
  26126. Oacute: 0x00D3,
  26127. Oacutesmall: 0xF7F3,
  26128. Obarredcyrillic: 0x04E8,
  26129. Obarreddieresiscyrillic: 0x04EA,
  26130. Obreve: 0x014E,
  26131. Ocaron: 0x01D1,
  26132. Ocenteredtilde: 0x019F,
  26133. Ocircle: 0x24C4,
  26134. Ocircumflex: 0x00D4,
  26135. Ocircumflexacute: 0x1ED0,
  26136. Ocircumflexdotbelow: 0x1ED8,
  26137. Ocircumflexgrave: 0x1ED2,
  26138. Ocircumflexhookabove: 0x1ED4,
  26139. Ocircumflexsmall: 0xF7F4,
  26140. Ocircumflextilde: 0x1ED6,
  26141. Ocyrillic: 0x041E,
  26142. Odblacute: 0x0150,
  26143. Odblgrave: 0x020C,
  26144. Odieresis: 0x00D6,
  26145. Odieresiscyrillic: 0x04E6,
  26146. Odieresissmall: 0xF7F6,
  26147. Odotbelow: 0x1ECC,
  26148. Ogoneksmall: 0xF6FB,
  26149. Ograve: 0x00D2,
  26150. Ogravesmall: 0xF7F2,
  26151. Oharmenian: 0x0555,
  26152. Ohm: 0x2126,
  26153. Ohookabove: 0x1ECE,
  26154. Ohorn: 0x01A0,
  26155. Ohornacute: 0x1EDA,
  26156. Ohorndotbelow: 0x1EE2,
  26157. Ohorngrave: 0x1EDC,
  26158. Ohornhookabove: 0x1EDE,
  26159. Ohorntilde: 0x1EE0,
  26160. Ohungarumlaut: 0x0150,
  26161. Oi: 0x01A2,
  26162. Oinvertedbreve: 0x020E,
  26163. Omacron: 0x014C,
  26164. Omacronacute: 0x1E52,
  26165. Omacrongrave: 0x1E50,
  26166. Omega: 0x2126,
  26167. Omegacyrillic: 0x0460,
  26168. Omegagreek: 0x03A9,
  26169. Omegaroundcyrillic: 0x047A,
  26170. Omegatitlocyrillic: 0x047C,
  26171. Omegatonos: 0x038F,
  26172. Omicron: 0x039F,
  26173. Omicrontonos: 0x038C,
  26174. Omonospace: 0xFF2F,
  26175. Oneroman: 0x2160,
  26176. Oogonek: 0x01EA,
  26177. Oogonekmacron: 0x01EC,
  26178. Oopen: 0x0186,
  26179. Oslash: 0x00D8,
  26180. Oslashacute: 0x01FE,
  26181. Oslashsmall: 0xF7F8,
  26182. Osmall: 0xF76F,
  26183. Ostrokeacute: 0x01FE,
  26184. Otcyrillic: 0x047E,
  26185. Otilde: 0x00D5,
  26186. Otildeacute: 0x1E4C,
  26187. Otildedieresis: 0x1E4E,
  26188. Otildesmall: 0xF7F5,
  26189. P: 0x0050,
  26190. Pacute: 0x1E54,
  26191. Pcircle: 0x24C5,
  26192. Pdotaccent: 0x1E56,
  26193. Pecyrillic: 0x041F,
  26194. Peharmenian: 0x054A,
  26195. Pemiddlehookcyrillic: 0x04A6,
  26196. Phi: 0x03A6,
  26197. Phook: 0x01A4,
  26198. Pi: 0x03A0,
  26199. Piwrarmenian: 0x0553,
  26200. Pmonospace: 0xFF30,
  26201. Psi: 0x03A8,
  26202. Psicyrillic: 0x0470,
  26203. Psmall: 0xF770,
  26204. Q: 0x0051,
  26205. Qcircle: 0x24C6,
  26206. Qmonospace: 0xFF31,
  26207. Qsmall: 0xF771,
  26208. R: 0x0052,
  26209. Raarmenian: 0x054C,
  26210. Racute: 0x0154,
  26211. Rcaron: 0x0158,
  26212. Rcedilla: 0x0156,
  26213. Rcircle: 0x24C7,
  26214. Rcommaaccent: 0x0156,
  26215. Rdblgrave: 0x0210,
  26216. Rdotaccent: 0x1E58,
  26217. Rdotbelow: 0x1E5A,
  26218. Rdotbelowmacron: 0x1E5C,
  26219. Reharmenian: 0x0550,
  26220. Rfraktur: 0x211C,
  26221. Rho: 0x03A1,
  26222. Ringsmall: 0xF6FC,
  26223. Rinvertedbreve: 0x0212,
  26224. Rlinebelow: 0x1E5E,
  26225. Rmonospace: 0xFF32,
  26226. Rsmall: 0xF772,
  26227. Rsmallinverted: 0x0281,
  26228. Rsmallinvertedsuperior: 0x02B6,
  26229. S: 0x0053,
  26230. SF010000: 0x250C,
  26231. SF020000: 0x2514,
  26232. SF030000: 0x2510,
  26233. SF040000: 0x2518,
  26234. SF050000: 0x253C,
  26235. SF060000: 0x252C,
  26236. SF070000: 0x2534,
  26237. SF080000: 0x251C,
  26238. SF090000: 0x2524,
  26239. SF100000: 0x2500,
  26240. SF110000: 0x2502,
  26241. SF190000: 0x2561,
  26242. SF200000: 0x2562,
  26243. SF210000: 0x2556,
  26244. SF220000: 0x2555,
  26245. SF230000: 0x2563,
  26246. SF240000: 0x2551,
  26247. SF250000: 0x2557,
  26248. SF260000: 0x255D,
  26249. SF270000: 0x255C,
  26250. SF280000: 0x255B,
  26251. SF360000: 0x255E,
  26252. SF370000: 0x255F,
  26253. SF380000: 0x255A,
  26254. SF390000: 0x2554,
  26255. SF400000: 0x2569,
  26256. SF410000: 0x2566,
  26257. SF420000: 0x2560,
  26258. SF430000: 0x2550,
  26259. SF440000: 0x256C,
  26260. SF450000: 0x2567,
  26261. SF460000: 0x2568,
  26262. SF470000: 0x2564,
  26263. SF480000: 0x2565,
  26264. SF490000: 0x2559,
  26265. SF500000: 0x2558,
  26266. SF510000: 0x2552,
  26267. SF520000: 0x2553,
  26268. SF530000: 0x256B,
  26269. SF540000: 0x256A,
  26270. Sacute: 0x015A,
  26271. Sacutedotaccent: 0x1E64,
  26272. Sampigreek: 0x03E0,
  26273. Scaron: 0x0160,
  26274. Scarondotaccent: 0x1E66,
  26275. Scaronsmall: 0xF6FD,
  26276. Scedilla: 0x015E,
  26277. Schwa: 0x018F,
  26278. Schwacyrillic: 0x04D8,
  26279. Schwadieresiscyrillic: 0x04DA,
  26280. Scircle: 0x24C8,
  26281. Scircumflex: 0x015C,
  26282. Scommaaccent: 0x0218,
  26283. Sdotaccent: 0x1E60,
  26284. Sdotbelow: 0x1E62,
  26285. Sdotbelowdotaccent: 0x1E68,
  26286. Seharmenian: 0x054D,
  26287. Sevenroman: 0x2166,
  26288. Shaarmenian: 0x0547,
  26289. Shacyrillic: 0x0428,
  26290. Shchacyrillic: 0x0429,
  26291. Sheicoptic: 0x03E2,
  26292. Shhacyrillic: 0x04BA,
  26293. Shimacoptic: 0x03EC,
  26294. Sigma: 0x03A3,
  26295. Sixroman: 0x2165,
  26296. Smonospace: 0xFF33,
  26297. Softsigncyrillic: 0x042C,
  26298. Ssmall: 0xF773,
  26299. Stigmagreek: 0x03DA,
  26300. T: 0x0054,
  26301. Tau: 0x03A4,
  26302. Tbar: 0x0166,
  26303. Tcaron: 0x0164,
  26304. Tcedilla: 0x0162,
  26305. Tcircle: 0x24C9,
  26306. Tcircumflexbelow: 0x1E70,
  26307. Tcommaaccent: 0x0162,
  26308. Tdotaccent: 0x1E6A,
  26309. Tdotbelow: 0x1E6C,
  26310. Tecyrillic: 0x0422,
  26311. Tedescendercyrillic: 0x04AC,
  26312. Tenroman: 0x2169,
  26313. Tetsecyrillic: 0x04B4,
  26314. Theta: 0x0398,
  26315. Thook: 0x01AC,
  26316. Thorn: 0x00DE,
  26317. Thornsmall: 0xF7FE,
  26318. Threeroman: 0x2162,
  26319. Tildesmall: 0xF6FE,
  26320. Tiwnarmenian: 0x054F,
  26321. Tlinebelow: 0x1E6E,
  26322. Tmonospace: 0xFF34,
  26323. Toarmenian: 0x0539,
  26324. Tonefive: 0x01BC,
  26325. Tonesix: 0x0184,
  26326. Tonetwo: 0x01A7,
  26327. Tretroflexhook: 0x01AE,
  26328. Tsecyrillic: 0x0426,
  26329. Tshecyrillic: 0x040B,
  26330. Tsmall: 0xF774,
  26331. Twelveroman: 0x216B,
  26332. Tworoman: 0x2161,
  26333. U: 0x0055,
  26334. Uacute: 0x00DA,
  26335. Uacutesmall: 0xF7FA,
  26336. Ubreve: 0x016C,
  26337. Ucaron: 0x01D3,
  26338. Ucircle: 0x24CA,
  26339. Ucircumflex: 0x00DB,
  26340. Ucircumflexbelow: 0x1E76,
  26341. Ucircumflexsmall: 0xF7FB,
  26342. Ucyrillic: 0x0423,
  26343. Udblacute: 0x0170,
  26344. Udblgrave: 0x0214,
  26345. Udieresis: 0x00DC,
  26346. Udieresisacute: 0x01D7,
  26347. Udieresisbelow: 0x1E72,
  26348. Udieresiscaron: 0x01D9,
  26349. Udieresiscyrillic: 0x04F0,
  26350. Udieresisgrave: 0x01DB,
  26351. Udieresismacron: 0x01D5,
  26352. Udieresissmall: 0xF7FC,
  26353. Udotbelow: 0x1EE4,
  26354. Ugrave: 0x00D9,
  26355. Ugravesmall: 0xF7F9,
  26356. Uhookabove: 0x1EE6,
  26357. Uhorn: 0x01AF,
  26358. Uhornacute: 0x1EE8,
  26359. Uhorndotbelow: 0x1EF0,
  26360. Uhorngrave: 0x1EEA,
  26361. Uhornhookabove: 0x1EEC,
  26362. Uhorntilde: 0x1EEE,
  26363. Uhungarumlaut: 0x0170,
  26364. Uhungarumlautcyrillic: 0x04F2,
  26365. Uinvertedbreve: 0x0216,
  26366. Ukcyrillic: 0x0478,
  26367. Umacron: 0x016A,
  26368. Umacroncyrillic: 0x04EE,
  26369. Umacrondieresis: 0x1E7A,
  26370. Umonospace: 0xFF35,
  26371. Uogonek: 0x0172,
  26372. Upsilon: 0x03A5,
  26373. Upsilon1: 0x03D2,
  26374. Upsilonacutehooksymbolgreek: 0x03D3,
  26375. Upsilonafrican: 0x01B1,
  26376. Upsilondieresis: 0x03AB,
  26377. Upsilondieresishooksymbolgreek: 0x03D4,
  26378. Upsilonhooksymbol: 0x03D2,
  26379. Upsilontonos: 0x038E,
  26380. Uring: 0x016E,
  26381. Ushortcyrillic: 0x040E,
  26382. Usmall: 0xF775,
  26383. Ustraightcyrillic: 0x04AE,
  26384. Ustraightstrokecyrillic: 0x04B0,
  26385. Utilde: 0x0168,
  26386. Utildeacute: 0x1E78,
  26387. Utildebelow: 0x1E74,
  26388. V: 0x0056,
  26389. Vcircle: 0x24CB,
  26390. Vdotbelow: 0x1E7E,
  26391. Vecyrillic: 0x0412,
  26392. Vewarmenian: 0x054E,
  26393. Vhook: 0x01B2,
  26394. Vmonospace: 0xFF36,
  26395. Voarmenian: 0x0548,
  26396. Vsmall: 0xF776,
  26397. Vtilde: 0x1E7C,
  26398. W: 0x0057,
  26399. Wacute: 0x1E82,
  26400. Wcircle: 0x24CC,
  26401. Wcircumflex: 0x0174,
  26402. Wdieresis: 0x1E84,
  26403. Wdotaccent: 0x1E86,
  26404. Wdotbelow: 0x1E88,
  26405. Wgrave: 0x1E80,
  26406. Wmonospace: 0xFF37,
  26407. Wsmall: 0xF777,
  26408. X: 0x0058,
  26409. Xcircle: 0x24CD,
  26410. Xdieresis: 0x1E8C,
  26411. Xdotaccent: 0x1E8A,
  26412. Xeharmenian: 0x053D,
  26413. Xi: 0x039E,
  26414. Xmonospace: 0xFF38,
  26415. Xsmall: 0xF778,
  26416. Y: 0x0059,
  26417. Yacute: 0x00DD,
  26418. Yacutesmall: 0xF7FD,
  26419. Yatcyrillic: 0x0462,
  26420. Ycircle: 0x24CE,
  26421. Ycircumflex: 0x0176,
  26422. Ydieresis: 0x0178,
  26423. Ydieresissmall: 0xF7FF,
  26424. Ydotaccent: 0x1E8E,
  26425. Ydotbelow: 0x1EF4,
  26426. Yericyrillic: 0x042B,
  26427. Yerudieresiscyrillic: 0x04F8,
  26428. Ygrave: 0x1EF2,
  26429. Yhook: 0x01B3,
  26430. Yhookabove: 0x1EF6,
  26431. Yiarmenian: 0x0545,
  26432. Yicyrillic: 0x0407,
  26433. Yiwnarmenian: 0x0552,
  26434. Ymonospace: 0xFF39,
  26435. Ysmall: 0xF779,
  26436. Ytilde: 0x1EF8,
  26437. Yusbigcyrillic: 0x046A,
  26438. Yusbigiotifiedcyrillic: 0x046C,
  26439. Yuslittlecyrillic: 0x0466,
  26440. Yuslittleiotifiedcyrillic: 0x0468,
  26441. Z: 0x005A,
  26442. Zaarmenian: 0x0536,
  26443. Zacute: 0x0179,
  26444. Zcaron: 0x017D,
  26445. Zcaronsmall: 0xF6FF,
  26446. Zcircle: 0x24CF,
  26447. Zcircumflex: 0x1E90,
  26448. Zdot: 0x017B,
  26449. Zdotaccent: 0x017B,
  26450. Zdotbelow: 0x1E92,
  26451. Zecyrillic: 0x0417,
  26452. Zedescendercyrillic: 0x0498,
  26453. Zedieresiscyrillic: 0x04DE,
  26454. Zeta: 0x0396,
  26455. Zhearmenian: 0x053A,
  26456. Zhebrevecyrillic: 0x04C1,
  26457. Zhecyrillic: 0x0416,
  26458. Zhedescendercyrillic: 0x0496,
  26459. Zhedieresiscyrillic: 0x04DC,
  26460. Zlinebelow: 0x1E94,
  26461. Zmonospace: 0xFF3A,
  26462. Zsmall: 0xF77A,
  26463. Zstroke: 0x01B5,
  26464. a: 0x0061,
  26465. aabengali: 0x0986,
  26466. aacute: 0x00E1,
  26467. aadeva: 0x0906,
  26468. aagujarati: 0x0A86,
  26469. aagurmukhi: 0x0A06,
  26470. aamatragurmukhi: 0x0A3E,
  26471. aarusquare: 0x3303,
  26472. aavowelsignbengali: 0x09BE,
  26473. aavowelsigndeva: 0x093E,
  26474. aavowelsigngujarati: 0x0ABE,
  26475. abbreviationmarkarmenian: 0x055F,
  26476. abbreviationsigndeva: 0x0970,
  26477. abengali: 0x0985,
  26478. abopomofo: 0x311A,
  26479. abreve: 0x0103,
  26480. abreveacute: 0x1EAF,
  26481. abrevecyrillic: 0x04D1,
  26482. abrevedotbelow: 0x1EB7,
  26483. abrevegrave: 0x1EB1,
  26484. abrevehookabove: 0x1EB3,
  26485. abrevetilde: 0x1EB5,
  26486. acaron: 0x01CE,
  26487. acircle: 0x24D0,
  26488. acircumflex: 0x00E2,
  26489. acircumflexacute: 0x1EA5,
  26490. acircumflexdotbelow: 0x1EAD,
  26491. acircumflexgrave: 0x1EA7,
  26492. acircumflexhookabove: 0x1EA9,
  26493. acircumflextilde: 0x1EAB,
  26494. acute: 0x00B4,
  26495. acutebelowcmb: 0x0317,
  26496. acutecmb: 0x0301,
  26497. acutecomb: 0x0301,
  26498. acutedeva: 0x0954,
  26499. acutelowmod: 0x02CF,
  26500. acutetonecmb: 0x0341,
  26501. acyrillic: 0x0430,
  26502. adblgrave: 0x0201,
  26503. addakgurmukhi: 0x0A71,
  26504. adeva: 0x0905,
  26505. adieresis: 0x00E4,
  26506. adieresiscyrillic: 0x04D3,
  26507. adieresismacron: 0x01DF,
  26508. adotbelow: 0x1EA1,
  26509. adotmacron: 0x01E1,
  26510. ae: 0x00E6,
  26511. aeacute: 0x01FD,
  26512. aekorean: 0x3150,
  26513. aemacron: 0x01E3,
  26514. afii00208: 0x2015,
  26515. afii08941: 0x20A4,
  26516. afii10017: 0x0410,
  26517. afii10018: 0x0411,
  26518. afii10019: 0x0412,
  26519. afii10020: 0x0413,
  26520. afii10021: 0x0414,
  26521. afii10022: 0x0415,
  26522. afii10023: 0x0401,
  26523. afii10024: 0x0416,
  26524. afii10025: 0x0417,
  26525. afii10026: 0x0418,
  26526. afii10027: 0x0419,
  26527. afii10028: 0x041A,
  26528. afii10029: 0x041B,
  26529. afii10030: 0x041C,
  26530. afii10031: 0x041D,
  26531. afii10032: 0x041E,
  26532. afii10033: 0x041F,
  26533. afii10034: 0x0420,
  26534. afii10035: 0x0421,
  26535. afii10036: 0x0422,
  26536. afii10037: 0x0423,
  26537. afii10038: 0x0424,
  26538. afii10039: 0x0425,
  26539. afii10040: 0x0426,
  26540. afii10041: 0x0427,
  26541. afii10042: 0x0428,
  26542. afii10043: 0x0429,
  26543. afii10044: 0x042A,
  26544. afii10045: 0x042B,
  26545. afii10046: 0x042C,
  26546. afii10047: 0x042D,
  26547. afii10048: 0x042E,
  26548. afii10049: 0x042F,
  26549. afii10050: 0x0490,
  26550. afii10051: 0x0402,
  26551. afii10052: 0x0403,
  26552. afii10053: 0x0404,
  26553. afii10054: 0x0405,
  26554. afii10055: 0x0406,
  26555. afii10056: 0x0407,
  26556. afii10057: 0x0408,
  26557. afii10058: 0x0409,
  26558. afii10059: 0x040A,
  26559. afii10060: 0x040B,
  26560. afii10061: 0x040C,
  26561. afii10062: 0x040E,
  26562. afii10063: 0xF6C4,
  26563. afii10064: 0xF6C5,
  26564. afii10065: 0x0430,
  26565. afii10066: 0x0431,
  26566. afii10067: 0x0432,
  26567. afii10068: 0x0433,
  26568. afii10069: 0x0434,
  26569. afii10070: 0x0435,
  26570. afii10071: 0x0451,
  26571. afii10072: 0x0436,
  26572. afii10073: 0x0437,
  26573. afii10074: 0x0438,
  26574. afii10075: 0x0439,
  26575. afii10076: 0x043A,
  26576. afii10077: 0x043B,
  26577. afii10078: 0x043C,
  26578. afii10079: 0x043D,
  26579. afii10080: 0x043E,
  26580. afii10081: 0x043F,
  26581. afii10082: 0x0440,
  26582. afii10083: 0x0441,
  26583. afii10084: 0x0442,
  26584. afii10085: 0x0443,
  26585. afii10086: 0x0444,
  26586. afii10087: 0x0445,
  26587. afii10088: 0x0446,
  26588. afii10089: 0x0447,
  26589. afii10090: 0x0448,
  26590. afii10091: 0x0449,
  26591. afii10092: 0x044A,
  26592. afii10093: 0x044B,
  26593. afii10094: 0x044C,
  26594. afii10095: 0x044D,
  26595. afii10096: 0x044E,
  26596. afii10097: 0x044F,
  26597. afii10098: 0x0491,
  26598. afii10099: 0x0452,
  26599. afii10100: 0x0453,
  26600. afii10101: 0x0454,
  26601. afii10102: 0x0455,
  26602. afii10103: 0x0456,
  26603. afii10104: 0x0457,
  26604. afii10105: 0x0458,
  26605. afii10106: 0x0459,
  26606. afii10107: 0x045A,
  26607. afii10108: 0x045B,
  26608. afii10109: 0x045C,
  26609. afii10110: 0x045E,
  26610. afii10145: 0x040F,
  26611. afii10146: 0x0462,
  26612. afii10147: 0x0472,
  26613. afii10148: 0x0474,
  26614. afii10192: 0xF6C6,
  26615. afii10193: 0x045F,
  26616. afii10194: 0x0463,
  26617. afii10195: 0x0473,
  26618. afii10196: 0x0475,
  26619. afii10831: 0xF6C7,
  26620. afii10832: 0xF6C8,
  26621. afii10846: 0x04D9,
  26622. afii299: 0x200E,
  26623. afii300: 0x200F,
  26624. afii301: 0x200D,
  26625. afii57381: 0x066A,
  26626. afii57388: 0x060C,
  26627. afii57392: 0x0660,
  26628. afii57393: 0x0661,
  26629. afii57394: 0x0662,
  26630. afii57395: 0x0663,
  26631. afii57396: 0x0664,
  26632. afii57397: 0x0665,
  26633. afii57398: 0x0666,
  26634. afii57399: 0x0667,
  26635. afii57400: 0x0668,
  26636. afii57401: 0x0669,
  26637. afii57403: 0x061B,
  26638. afii57407: 0x061F,
  26639. afii57409: 0x0621,
  26640. afii57410: 0x0622,
  26641. afii57411: 0x0623,
  26642. afii57412: 0x0624,
  26643. afii57413: 0x0625,
  26644. afii57414: 0x0626,
  26645. afii57415: 0x0627,
  26646. afii57416: 0x0628,
  26647. afii57417: 0x0629,
  26648. afii57418: 0x062A,
  26649. afii57419: 0x062B,
  26650. afii57420: 0x062C,
  26651. afii57421: 0x062D,
  26652. afii57422: 0x062E,
  26653. afii57423: 0x062F,
  26654. afii57424: 0x0630,
  26655. afii57425: 0x0631,
  26656. afii57426: 0x0632,
  26657. afii57427: 0x0633,
  26658. afii57428: 0x0634,
  26659. afii57429: 0x0635,
  26660. afii57430: 0x0636,
  26661. afii57431: 0x0637,
  26662. afii57432: 0x0638,
  26663. afii57433: 0x0639,
  26664. afii57434: 0x063A,
  26665. afii57440: 0x0640,
  26666. afii57441: 0x0641,
  26667. afii57442: 0x0642,
  26668. afii57443: 0x0643,
  26669. afii57444: 0x0644,
  26670. afii57445: 0x0645,
  26671. afii57446: 0x0646,
  26672. afii57448: 0x0648,
  26673. afii57449: 0x0649,
  26674. afii57450: 0x064A,
  26675. afii57451: 0x064B,
  26676. afii57452: 0x064C,
  26677. afii57453: 0x064D,
  26678. afii57454: 0x064E,
  26679. afii57455: 0x064F,
  26680. afii57456: 0x0650,
  26681. afii57457: 0x0651,
  26682. afii57458: 0x0652,
  26683. afii57470: 0x0647,
  26684. afii57505: 0x06A4,
  26685. afii57506: 0x067E,
  26686. afii57507: 0x0686,
  26687. afii57508: 0x0698,
  26688. afii57509: 0x06AF,
  26689. afii57511: 0x0679,
  26690. afii57512: 0x0688,
  26691. afii57513: 0x0691,
  26692. afii57514: 0x06BA,
  26693. afii57519: 0x06D2,
  26694. afii57534: 0x06D5,
  26695. afii57636: 0x20AA,
  26696. afii57645: 0x05BE,
  26697. afii57658: 0x05C3,
  26698. afii57664: 0x05D0,
  26699. afii57665: 0x05D1,
  26700. afii57666: 0x05D2,
  26701. afii57667: 0x05D3,
  26702. afii57668: 0x05D4,
  26703. afii57669: 0x05D5,
  26704. afii57670: 0x05D6,
  26705. afii57671: 0x05D7,
  26706. afii57672: 0x05D8,
  26707. afii57673: 0x05D9,
  26708. afii57674: 0x05DA,
  26709. afii57675: 0x05DB,
  26710. afii57676: 0x05DC,
  26711. afii57677: 0x05DD,
  26712. afii57678: 0x05DE,
  26713. afii57679: 0x05DF,
  26714. afii57680: 0x05E0,
  26715. afii57681: 0x05E1,
  26716. afii57682: 0x05E2,
  26717. afii57683: 0x05E3,
  26718. afii57684: 0x05E4,
  26719. afii57685: 0x05E5,
  26720. afii57686: 0x05E6,
  26721. afii57687: 0x05E7,
  26722. afii57688: 0x05E8,
  26723. afii57689: 0x05E9,
  26724. afii57690: 0x05EA,
  26725. afii57694: 0xFB2A,
  26726. afii57695: 0xFB2B,
  26727. afii57700: 0xFB4B,
  26728. afii57705: 0xFB1F,
  26729. afii57716: 0x05F0,
  26730. afii57717: 0x05F1,
  26731. afii57718: 0x05F2,
  26732. afii57723: 0xFB35,
  26733. afii57793: 0x05B4,
  26734. afii57794: 0x05B5,
  26735. afii57795: 0x05B6,
  26736. afii57796: 0x05BB,
  26737. afii57797: 0x05B8,
  26738. afii57798: 0x05B7,
  26739. afii57799: 0x05B0,
  26740. afii57800: 0x05B2,
  26741. afii57801: 0x05B1,
  26742. afii57802: 0x05B3,
  26743. afii57803: 0x05C2,
  26744. afii57804: 0x05C1,
  26745. afii57806: 0x05B9,
  26746. afii57807: 0x05BC,
  26747. afii57839: 0x05BD,
  26748. afii57841: 0x05BF,
  26749. afii57842: 0x05C0,
  26750. afii57929: 0x02BC,
  26751. afii61248: 0x2105,
  26752. afii61289: 0x2113,
  26753. afii61352: 0x2116,
  26754. afii61573: 0x202C,
  26755. afii61574: 0x202D,
  26756. afii61575: 0x202E,
  26757. afii61664: 0x200C,
  26758. afii63167: 0x066D,
  26759. afii64937: 0x02BD,
  26760. agrave: 0x00E0,
  26761. agujarati: 0x0A85,
  26762. agurmukhi: 0x0A05,
  26763. ahiragana: 0x3042,
  26764. ahookabove: 0x1EA3,
  26765. aibengali: 0x0990,
  26766. aibopomofo: 0x311E,
  26767. aideva: 0x0910,
  26768. aiecyrillic: 0x04D5,
  26769. aigujarati: 0x0A90,
  26770. aigurmukhi: 0x0A10,
  26771. aimatragurmukhi: 0x0A48,
  26772. ainarabic: 0x0639,
  26773. ainfinalarabic: 0xFECA,
  26774. aininitialarabic: 0xFECB,
  26775. ainmedialarabic: 0xFECC,
  26776. ainvertedbreve: 0x0203,
  26777. aivowelsignbengali: 0x09C8,
  26778. aivowelsigndeva: 0x0948,
  26779. aivowelsigngujarati: 0x0AC8,
  26780. akatakana: 0x30A2,
  26781. akatakanahalfwidth: 0xFF71,
  26782. akorean: 0x314F,
  26783. alef: 0x05D0,
  26784. alefarabic: 0x0627,
  26785. alefdageshhebrew: 0xFB30,
  26786. aleffinalarabic: 0xFE8E,
  26787. alefhamzaabovearabic: 0x0623,
  26788. alefhamzaabovefinalarabic: 0xFE84,
  26789. alefhamzabelowarabic: 0x0625,
  26790. alefhamzabelowfinalarabic: 0xFE88,
  26791. alefhebrew: 0x05D0,
  26792. aleflamedhebrew: 0xFB4F,
  26793. alefmaddaabovearabic: 0x0622,
  26794. alefmaddaabovefinalarabic: 0xFE82,
  26795. alefmaksuraarabic: 0x0649,
  26796. alefmaksurafinalarabic: 0xFEF0,
  26797. alefmaksurainitialarabic: 0xFEF3,
  26798. alefmaksuramedialarabic: 0xFEF4,
  26799. alefpatahhebrew: 0xFB2E,
  26800. alefqamatshebrew: 0xFB2F,
  26801. aleph: 0x2135,
  26802. allequal: 0x224C,
  26803. alpha: 0x03B1,
  26804. alphatonos: 0x03AC,
  26805. amacron: 0x0101,
  26806. amonospace: 0xFF41,
  26807. ampersand: 0x0026,
  26808. ampersandmonospace: 0xFF06,
  26809. ampersandsmall: 0xF726,
  26810. amsquare: 0x33C2,
  26811. anbopomofo: 0x3122,
  26812. angbopomofo: 0x3124,
  26813. angbracketleft: 0x3008, // This glyph is missing from Adobe's original list.
  26814. angbracketright: 0x3009, // This glyph is missing from Adobe's original list.
  26815. angkhankhuthai: 0x0E5A,
  26816. angle: 0x2220,
  26817. anglebracketleft: 0x3008,
  26818. anglebracketleftvertical: 0xFE3F,
  26819. anglebracketright: 0x3009,
  26820. anglebracketrightvertical: 0xFE40,
  26821. angleleft: 0x2329,
  26822. angleright: 0x232A,
  26823. angstrom: 0x212B,
  26824. anoteleia: 0x0387,
  26825. anudattadeva: 0x0952,
  26826. anusvarabengali: 0x0982,
  26827. anusvaradeva: 0x0902,
  26828. anusvaragujarati: 0x0A82,
  26829. aogonek: 0x0105,
  26830. apaatosquare: 0x3300,
  26831. aparen: 0x249C,
  26832. apostrophearmenian: 0x055A,
  26833. apostrophemod: 0x02BC,
  26834. apple: 0xF8FF,
  26835. approaches: 0x2250,
  26836. approxequal: 0x2248,
  26837. approxequalorimage: 0x2252,
  26838. approximatelyequal: 0x2245,
  26839. araeaekorean: 0x318E,
  26840. araeakorean: 0x318D,
  26841. arc: 0x2312,
  26842. arighthalfring: 0x1E9A,
  26843. aring: 0x00E5,
  26844. aringacute: 0x01FB,
  26845. aringbelow: 0x1E01,
  26846. arrowboth: 0x2194,
  26847. arrowdashdown: 0x21E3,
  26848. arrowdashleft: 0x21E0,
  26849. arrowdashright: 0x21E2,
  26850. arrowdashup: 0x21E1,
  26851. arrowdblboth: 0x21D4,
  26852. arrowdbldown: 0x21D3,
  26853. arrowdblleft: 0x21D0,
  26854. arrowdblright: 0x21D2,
  26855. arrowdblup: 0x21D1,
  26856. arrowdown: 0x2193,
  26857. arrowdownleft: 0x2199,
  26858. arrowdownright: 0x2198,
  26859. arrowdownwhite: 0x21E9,
  26860. arrowheaddownmod: 0x02C5,
  26861. arrowheadleftmod: 0x02C2,
  26862. arrowheadrightmod: 0x02C3,
  26863. arrowheadupmod: 0x02C4,
  26864. arrowhorizex: 0xF8E7,
  26865. arrowleft: 0x2190,
  26866. arrowleftdbl: 0x21D0,
  26867. arrowleftdblstroke: 0x21CD,
  26868. arrowleftoverright: 0x21C6,
  26869. arrowleftwhite: 0x21E6,
  26870. arrowright: 0x2192,
  26871. arrowrightdblstroke: 0x21CF,
  26872. arrowrightheavy: 0x279E,
  26873. arrowrightoverleft: 0x21C4,
  26874. arrowrightwhite: 0x21E8,
  26875. arrowtableft: 0x21E4,
  26876. arrowtabright: 0x21E5,
  26877. arrowup: 0x2191,
  26878. arrowupdn: 0x2195,
  26879. arrowupdnbse: 0x21A8,
  26880. arrowupdownbase: 0x21A8,
  26881. arrowupleft: 0x2196,
  26882. arrowupleftofdown: 0x21C5,
  26883. arrowupright: 0x2197,
  26884. arrowupwhite: 0x21E7,
  26885. arrowvertex: 0xF8E6,
  26886. asciicircum: 0x005E,
  26887. asciicircummonospace: 0xFF3E,
  26888. asciitilde: 0x007E,
  26889. asciitildemonospace: 0xFF5E,
  26890. ascript: 0x0251,
  26891. ascriptturned: 0x0252,
  26892. asmallhiragana: 0x3041,
  26893. asmallkatakana: 0x30A1,
  26894. asmallkatakanahalfwidth: 0xFF67,
  26895. asterisk: 0x002A,
  26896. asteriskaltonearabic: 0x066D,
  26897. asteriskarabic: 0x066D,
  26898. asteriskmath: 0x2217,
  26899. asteriskmonospace: 0xFF0A,
  26900. asterisksmall: 0xFE61,
  26901. asterism: 0x2042,
  26902. asuperior: 0xF6E9,
  26903. asymptoticallyequal: 0x2243,
  26904. at: 0x0040,
  26905. atilde: 0x00E3,
  26906. atmonospace: 0xFF20,
  26907. atsmall: 0xFE6B,
  26908. aturned: 0x0250,
  26909. aubengali: 0x0994,
  26910. aubopomofo: 0x3120,
  26911. audeva: 0x0914,
  26912. augujarati: 0x0A94,
  26913. augurmukhi: 0x0A14,
  26914. aulengthmarkbengali: 0x09D7,
  26915. aumatragurmukhi: 0x0A4C,
  26916. auvowelsignbengali: 0x09CC,
  26917. auvowelsigndeva: 0x094C,
  26918. auvowelsigngujarati: 0x0ACC,
  26919. avagrahadeva: 0x093D,
  26920. aybarmenian: 0x0561,
  26921. ayin: 0x05E2,
  26922. ayinaltonehebrew: 0xFB20,
  26923. ayinhebrew: 0x05E2,
  26924. b: 0x0062,
  26925. babengali: 0x09AC,
  26926. backslash: 0x005C,
  26927. backslashmonospace: 0xFF3C,
  26928. badeva: 0x092C,
  26929. bagujarati: 0x0AAC,
  26930. bagurmukhi: 0x0A2C,
  26931. bahiragana: 0x3070,
  26932. bahtthai: 0x0E3F,
  26933. bakatakana: 0x30D0,
  26934. bar: 0x007C,
  26935. barmonospace: 0xFF5C,
  26936. bbopomofo: 0x3105,
  26937. bcircle: 0x24D1,
  26938. bdotaccent: 0x1E03,
  26939. bdotbelow: 0x1E05,
  26940. beamedsixteenthnotes: 0x266C,
  26941. because: 0x2235,
  26942. becyrillic: 0x0431,
  26943. beharabic: 0x0628,
  26944. behfinalarabic: 0xFE90,
  26945. behinitialarabic: 0xFE91,
  26946. behiragana: 0x3079,
  26947. behmedialarabic: 0xFE92,
  26948. behmeeminitialarabic: 0xFC9F,
  26949. behmeemisolatedarabic: 0xFC08,
  26950. behnoonfinalarabic: 0xFC6D,
  26951. bekatakana: 0x30D9,
  26952. benarmenian: 0x0562,
  26953. bet: 0x05D1,
  26954. beta: 0x03B2,
  26955. betasymbolgreek: 0x03D0,
  26956. betdagesh: 0xFB31,
  26957. betdageshhebrew: 0xFB31,
  26958. bethebrew: 0x05D1,
  26959. betrafehebrew: 0xFB4C,
  26960. bhabengali: 0x09AD,
  26961. bhadeva: 0x092D,
  26962. bhagujarati: 0x0AAD,
  26963. bhagurmukhi: 0x0A2D,
  26964. bhook: 0x0253,
  26965. bihiragana: 0x3073,
  26966. bikatakana: 0x30D3,
  26967. bilabialclick: 0x0298,
  26968. bindigurmukhi: 0x0A02,
  26969. birusquare: 0x3331,
  26970. blackcircle: 0x25CF,
  26971. blackdiamond: 0x25C6,
  26972. blackdownpointingtriangle: 0x25BC,
  26973. blackleftpointingpointer: 0x25C4,
  26974. blackleftpointingtriangle: 0x25C0,
  26975. blacklenticularbracketleft: 0x3010,
  26976. blacklenticularbracketleftvertical: 0xFE3B,
  26977. blacklenticularbracketright: 0x3011,
  26978. blacklenticularbracketrightvertical: 0xFE3C,
  26979. blacklowerlefttriangle: 0x25E3,
  26980. blacklowerrighttriangle: 0x25E2,
  26981. blackrectangle: 0x25AC,
  26982. blackrightpointingpointer: 0x25BA,
  26983. blackrightpointingtriangle: 0x25B6,
  26984. blacksmallsquare: 0x25AA,
  26985. blacksmilingface: 0x263B,
  26986. blacksquare: 0x25A0,
  26987. blackstar: 0x2605,
  26988. blackupperlefttriangle: 0x25E4,
  26989. blackupperrighttriangle: 0x25E5,
  26990. blackuppointingsmalltriangle: 0x25B4,
  26991. blackuppointingtriangle: 0x25B2,
  26992. blank: 0x2423,
  26993. blinebelow: 0x1E07,
  26994. block: 0x2588,
  26995. bmonospace: 0xFF42,
  26996. bobaimaithai: 0x0E1A,
  26997. bohiragana: 0x307C,
  26998. bokatakana: 0x30DC,
  26999. bparen: 0x249D,
  27000. bqsquare: 0x33C3,
  27001. braceex: 0xF8F4,
  27002. braceleft: 0x007B,
  27003. braceleftbt: 0xF8F3,
  27004. braceleftmid: 0xF8F2,
  27005. braceleftmonospace: 0xFF5B,
  27006. braceleftsmall: 0xFE5B,
  27007. bracelefttp: 0xF8F1,
  27008. braceleftvertical: 0xFE37,
  27009. braceright: 0x007D,
  27010. bracerightbt: 0xF8FE,
  27011. bracerightmid: 0xF8FD,
  27012. bracerightmonospace: 0xFF5D,
  27013. bracerightsmall: 0xFE5C,
  27014. bracerighttp: 0xF8FC,
  27015. bracerightvertical: 0xFE38,
  27016. bracketleft: 0x005B,
  27017. bracketleftbt: 0xF8F0,
  27018. bracketleftex: 0xF8EF,
  27019. bracketleftmonospace: 0xFF3B,
  27020. bracketlefttp: 0xF8EE,
  27021. bracketright: 0x005D,
  27022. bracketrightbt: 0xF8FB,
  27023. bracketrightex: 0xF8FA,
  27024. bracketrightmonospace: 0xFF3D,
  27025. bracketrighttp: 0xF8F9,
  27026. breve: 0x02D8,
  27027. brevebelowcmb: 0x032E,
  27028. brevecmb: 0x0306,
  27029. breveinvertedbelowcmb: 0x032F,
  27030. breveinvertedcmb: 0x0311,
  27031. breveinverteddoublecmb: 0x0361,
  27032. bridgebelowcmb: 0x032A,
  27033. bridgeinvertedbelowcmb: 0x033A,
  27034. brokenbar: 0x00A6,
  27035. bstroke: 0x0180,
  27036. bsuperior: 0xF6EA,
  27037. btopbar: 0x0183,
  27038. buhiragana: 0x3076,
  27039. bukatakana: 0x30D6,
  27040. bullet: 0x2022,
  27041. bulletinverse: 0x25D8,
  27042. bulletoperator: 0x2219,
  27043. bullseye: 0x25CE,
  27044. c: 0x0063,
  27045. caarmenian: 0x056E,
  27046. cabengali: 0x099A,
  27047. cacute: 0x0107,
  27048. cadeva: 0x091A,
  27049. cagujarati: 0x0A9A,
  27050. cagurmukhi: 0x0A1A,
  27051. calsquare: 0x3388,
  27052. candrabindubengali: 0x0981,
  27053. candrabinducmb: 0x0310,
  27054. candrabindudeva: 0x0901,
  27055. candrabindugujarati: 0x0A81,
  27056. capslock: 0x21EA,
  27057. careof: 0x2105,
  27058. caron: 0x02C7,
  27059. caronbelowcmb: 0x032C,
  27060. caroncmb: 0x030C,
  27061. carriagereturn: 0x21B5,
  27062. cbopomofo: 0x3118,
  27063. ccaron: 0x010D,
  27064. ccedilla: 0x00E7,
  27065. ccedillaacute: 0x1E09,
  27066. ccircle: 0x24D2,
  27067. ccircumflex: 0x0109,
  27068. ccurl: 0x0255,
  27069. cdot: 0x010B,
  27070. cdotaccent: 0x010B,
  27071. cdsquare: 0x33C5,
  27072. cedilla: 0x00B8,
  27073. cedillacmb: 0x0327,
  27074. cent: 0x00A2,
  27075. centigrade: 0x2103,
  27076. centinferior: 0xF6DF,
  27077. centmonospace: 0xFFE0,
  27078. centoldstyle: 0xF7A2,
  27079. centsuperior: 0xF6E0,
  27080. chaarmenian: 0x0579,
  27081. chabengali: 0x099B,
  27082. chadeva: 0x091B,
  27083. chagujarati: 0x0A9B,
  27084. chagurmukhi: 0x0A1B,
  27085. chbopomofo: 0x3114,
  27086. cheabkhasiancyrillic: 0x04BD,
  27087. checkmark: 0x2713,
  27088. checyrillic: 0x0447,
  27089. chedescenderabkhasiancyrillic: 0x04BF,
  27090. chedescendercyrillic: 0x04B7,
  27091. chedieresiscyrillic: 0x04F5,
  27092. cheharmenian: 0x0573,
  27093. chekhakassiancyrillic: 0x04CC,
  27094. cheverticalstrokecyrillic: 0x04B9,
  27095. chi: 0x03C7,
  27096. chieuchacirclekorean: 0x3277,
  27097. chieuchaparenkorean: 0x3217,
  27098. chieuchcirclekorean: 0x3269,
  27099. chieuchkorean: 0x314A,
  27100. chieuchparenkorean: 0x3209,
  27101. chochangthai: 0x0E0A,
  27102. chochanthai: 0x0E08,
  27103. chochingthai: 0x0E09,
  27104. chochoethai: 0x0E0C,
  27105. chook: 0x0188,
  27106. cieucacirclekorean: 0x3276,
  27107. cieucaparenkorean: 0x3216,
  27108. cieuccirclekorean: 0x3268,
  27109. cieuckorean: 0x3148,
  27110. cieucparenkorean: 0x3208,
  27111. cieucuparenkorean: 0x321C,
  27112. circle: 0x25CB,
  27113. circlecopyrt: 0x00A9, // This glyph is missing from Adobe's original list.
  27114. circlemultiply: 0x2297,
  27115. circleot: 0x2299,
  27116. circleplus: 0x2295,
  27117. circlepostalmark: 0x3036,
  27118. circlewithlefthalfblack: 0x25D0,
  27119. circlewithrighthalfblack: 0x25D1,
  27120. circumflex: 0x02C6,
  27121. circumflexbelowcmb: 0x032D,
  27122. circumflexcmb: 0x0302,
  27123. clear: 0x2327,
  27124. clickalveolar: 0x01C2,
  27125. clickdental: 0x01C0,
  27126. clicklateral: 0x01C1,
  27127. clickretroflex: 0x01C3,
  27128. club: 0x2663,
  27129. clubsuitblack: 0x2663,
  27130. clubsuitwhite: 0x2667,
  27131. cmcubedsquare: 0x33A4,
  27132. cmonospace: 0xFF43,
  27133. cmsquaredsquare: 0x33A0,
  27134. coarmenian: 0x0581,
  27135. colon: 0x003A,
  27136. colonmonetary: 0x20A1,
  27137. colonmonospace: 0xFF1A,
  27138. colonsign: 0x20A1,
  27139. colonsmall: 0xFE55,
  27140. colontriangularhalfmod: 0x02D1,
  27141. colontriangularmod: 0x02D0,
  27142. comma: 0x002C,
  27143. commaabovecmb: 0x0313,
  27144. commaaboverightcmb: 0x0315,
  27145. commaaccent: 0xF6C3,
  27146. commaarabic: 0x060C,
  27147. commaarmenian: 0x055D,
  27148. commainferior: 0xF6E1,
  27149. commamonospace: 0xFF0C,
  27150. commareversedabovecmb: 0x0314,
  27151. commareversedmod: 0x02BD,
  27152. commasmall: 0xFE50,
  27153. commasuperior: 0xF6E2,
  27154. commaturnedabovecmb: 0x0312,
  27155. commaturnedmod: 0x02BB,
  27156. compass: 0x263C,
  27157. congruent: 0x2245,
  27158. contourintegral: 0x222E,
  27159. control: 0x2303,
  27160. controlACK: 0x0006,
  27161. controlBEL: 0x0007,
  27162. controlBS: 0x0008,
  27163. controlCAN: 0x0018,
  27164. controlCR: 0x000D,
  27165. controlDC1: 0x0011,
  27166. controlDC2: 0x0012,
  27167. controlDC3: 0x0013,
  27168. controlDC4: 0x0014,
  27169. controlDEL: 0x007F,
  27170. controlDLE: 0x0010,
  27171. controlEM: 0x0019,
  27172. controlENQ: 0x0005,
  27173. controlEOT: 0x0004,
  27174. controlESC: 0x001B,
  27175. controlETB: 0x0017,
  27176. controlETX: 0x0003,
  27177. controlFF: 0x000C,
  27178. controlFS: 0x001C,
  27179. controlGS: 0x001D,
  27180. controlHT: 0x0009,
  27181. controlLF: 0x000A,
  27182. controlNAK: 0x0015,
  27183. controlRS: 0x001E,
  27184. controlSI: 0x000F,
  27185. controlSO: 0x000E,
  27186. controlSOT: 0x0002,
  27187. controlSTX: 0x0001,
  27188. controlSUB: 0x001A,
  27189. controlSYN: 0x0016,
  27190. controlUS: 0x001F,
  27191. controlVT: 0x000B,
  27192. copyright: 0x00A9,
  27193. copyrightsans: 0xF8E9,
  27194. copyrightserif: 0xF6D9,
  27195. cornerbracketleft: 0x300C,
  27196. cornerbracketlefthalfwidth: 0xFF62,
  27197. cornerbracketleftvertical: 0xFE41,
  27198. cornerbracketright: 0x300D,
  27199. cornerbracketrighthalfwidth: 0xFF63,
  27200. cornerbracketrightvertical: 0xFE42,
  27201. corporationsquare: 0x337F,
  27202. cosquare: 0x33C7,
  27203. coverkgsquare: 0x33C6,
  27204. cparen: 0x249E,
  27205. cruzeiro: 0x20A2,
  27206. cstretched: 0x0297,
  27207. curlyand: 0x22CF,
  27208. curlyor: 0x22CE,
  27209. currency: 0x00A4,
  27210. cyrBreve: 0xF6D1,
  27211. cyrFlex: 0xF6D2,
  27212. cyrbreve: 0xF6D4,
  27213. cyrflex: 0xF6D5,
  27214. d: 0x0064,
  27215. daarmenian: 0x0564,
  27216. dabengali: 0x09A6,
  27217. dadarabic: 0x0636,
  27218. dadeva: 0x0926,
  27219. dadfinalarabic: 0xFEBE,
  27220. dadinitialarabic: 0xFEBF,
  27221. dadmedialarabic: 0xFEC0,
  27222. dagesh: 0x05BC,
  27223. dageshhebrew: 0x05BC,
  27224. dagger: 0x2020,
  27225. daggerdbl: 0x2021,
  27226. dagujarati: 0x0AA6,
  27227. dagurmukhi: 0x0A26,
  27228. dahiragana: 0x3060,
  27229. dakatakana: 0x30C0,
  27230. dalarabic: 0x062F,
  27231. dalet: 0x05D3,
  27232. daletdagesh: 0xFB33,
  27233. daletdageshhebrew: 0xFB33,
  27234. dalethebrew: 0x05D3,
  27235. dalfinalarabic: 0xFEAA,
  27236. dammaarabic: 0x064F,
  27237. dammalowarabic: 0x064F,
  27238. dammatanaltonearabic: 0x064C,
  27239. dammatanarabic: 0x064C,
  27240. danda: 0x0964,
  27241. dargahebrew: 0x05A7,
  27242. dargalefthebrew: 0x05A7,
  27243. dasiapneumatacyrilliccmb: 0x0485,
  27244. dblGrave: 0xF6D3,
  27245. dblanglebracketleft: 0x300A,
  27246. dblanglebracketleftvertical: 0xFE3D,
  27247. dblanglebracketright: 0x300B,
  27248. dblanglebracketrightvertical: 0xFE3E,
  27249. dblarchinvertedbelowcmb: 0x032B,
  27250. dblarrowleft: 0x21D4,
  27251. dblarrowright: 0x21D2,
  27252. dbldanda: 0x0965,
  27253. dblgrave: 0xF6D6,
  27254. dblgravecmb: 0x030F,
  27255. dblintegral: 0x222C,
  27256. dbllowline: 0x2017,
  27257. dbllowlinecmb: 0x0333,
  27258. dbloverlinecmb: 0x033F,
  27259. dblprimemod: 0x02BA,
  27260. dblverticalbar: 0x2016,
  27261. dblverticallineabovecmb: 0x030E,
  27262. dbopomofo: 0x3109,
  27263. dbsquare: 0x33C8,
  27264. dcaron: 0x010F,
  27265. dcedilla: 0x1E11,
  27266. dcircle: 0x24D3,
  27267. dcircumflexbelow: 0x1E13,
  27268. dcroat: 0x0111,
  27269. ddabengali: 0x09A1,
  27270. ddadeva: 0x0921,
  27271. ddagujarati: 0x0AA1,
  27272. ddagurmukhi: 0x0A21,
  27273. ddalarabic: 0x0688,
  27274. ddalfinalarabic: 0xFB89,
  27275. dddhadeva: 0x095C,
  27276. ddhabengali: 0x09A2,
  27277. ddhadeva: 0x0922,
  27278. ddhagujarati: 0x0AA2,
  27279. ddhagurmukhi: 0x0A22,
  27280. ddotaccent: 0x1E0B,
  27281. ddotbelow: 0x1E0D,
  27282. decimalseparatorarabic: 0x066B,
  27283. decimalseparatorpersian: 0x066B,
  27284. decyrillic: 0x0434,
  27285. degree: 0x00B0,
  27286. dehihebrew: 0x05AD,
  27287. dehiragana: 0x3067,
  27288. deicoptic: 0x03EF,
  27289. dekatakana: 0x30C7,
  27290. deleteleft: 0x232B,
  27291. deleteright: 0x2326,
  27292. delta: 0x03B4,
  27293. deltaturned: 0x018D,
  27294. denominatorminusonenumeratorbengali: 0x09F8,
  27295. dezh: 0x02A4,
  27296. dhabengali: 0x09A7,
  27297. dhadeva: 0x0927,
  27298. dhagujarati: 0x0AA7,
  27299. dhagurmukhi: 0x0A27,
  27300. dhook: 0x0257,
  27301. dialytikatonos: 0x0385,
  27302. dialytikatonoscmb: 0x0344,
  27303. diamond: 0x2666,
  27304. diamondsuitwhite: 0x2662,
  27305. dieresis: 0x00A8,
  27306. dieresisacute: 0xF6D7,
  27307. dieresisbelowcmb: 0x0324,
  27308. dieresiscmb: 0x0308,
  27309. dieresisgrave: 0xF6D8,
  27310. dieresistonos: 0x0385,
  27311. dihiragana: 0x3062,
  27312. dikatakana: 0x30C2,
  27313. dittomark: 0x3003,
  27314. divide: 0x00F7,
  27315. divides: 0x2223,
  27316. divisionslash: 0x2215,
  27317. djecyrillic: 0x0452,
  27318. dkshade: 0x2593,
  27319. dlinebelow: 0x1E0F,
  27320. dlsquare: 0x3397,
  27321. dmacron: 0x0111,
  27322. dmonospace: 0xFF44,
  27323. dnblock: 0x2584,
  27324. dochadathai: 0x0E0E,
  27325. dodekthai: 0x0E14,
  27326. dohiragana: 0x3069,
  27327. dokatakana: 0x30C9,
  27328. dollar: 0x0024,
  27329. dollarinferior: 0xF6E3,
  27330. dollarmonospace: 0xFF04,
  27331. dollaroldstyle: 0xF724,
  27332. dollarsmall: 0xFE69,
  27333. dollarsuperior: 0xF6E4,
  27334. dong: 0x20AB,
  27335. dorusquare: 0x3326,
  27336. dotaccent: 0x02D9,
  27337. dotaccentcmb: 0x0307,
  27338. dotbelowcmb: 0x0323,
  27339. dotbelowcomb: 0x0323,
  27340. dotkatakana: 0x30FB,
  27341. dotlessi: 0x0131,
  27342. dotlessj: 0xF6BE,
  27343. dotlessjstrokehook: 0x0284,
  27344. dotmath: 0x22C5,
  27345. dottedcircle: 0x25CC,
  27346. doubleyodpatah: 0xFB1F,
  27347. doubleyodpatahhebrew: 0xFB1F,
  27348. downtackbelowcmb: 0x031E,
  27349. downtackmod: 0x02D5,
  27350. dparen: 0x249F,
  27351. dsuperior: 0xF6EB,
  27352. dtail: 0x0256,
  27353. dtopbar: 0x018C,
  27354. duhiragana: 0x3065,
  27355. dukatakana: 0x30C5,
  27356. dz: 0x01F3,
  27357. dzaltone: 0x02A3,
  27358. dzcaron: 0x01C6,
  27359. dzcurl: 0x02A5,
  27360. dzeabkhasiancyrillic: 0x04E1,
  27361. dzecyrillic: 0x0455,
  27362. dzhecyrillic: 0x045F,
  27363. e: 0x0065,
  27364. eacute: 0x00E9,
  27365. earth: 0x2641,
  27366. ebengali: 0x098F,
  27367. ebopomofo: 0x311C,
  27368. ebreve: 0x0115,
  27369. ecandradeva: 0x090D,
  27370. ecandragujarati: 0x0A8D,
  27371. ecandravowelsigndeva: 0x0945,
  27372. ecandravowelsigngujarati: 0x0AC5,
  27373. ecaron: 0x011B,
  27374. ecedillabreve: 0x1E1D,
  27375. echarmenian: 0x0565,
  27376. echyiwnarmenian: 0x0587,
  27377. ecircle: 0x24D4,
  27378. ecircumflex: 0x00EA,
  27379. ecircumflexacute: 0x1EBF,
  27380. ecircumflexbelow: 0x1E19,
  27381. ecircumflexdotbelow: 0x1EC7,
  27382. ecircumflexgrave: 0x1EC1,
  27383. ecircumflexhookabove: 0x1EC3,
  27384. ecircumflextilde: 0x1EC5,
  27385. ecyrillic: 0x0454,
  27386. edblgrave: 0x0205,
  27387. edeva: 0x090F,
  27388. edieresis: 0x00EB,
  27389. edot: 0x0117,
  27390. edotaccent: 0x0117,
  27391. edotbelow: 0x1EB9,
  27392. eegurmukhi: 0x0A0F,
  27393. eematragurmukhi: 0x0A47,
  27394. efcyrillic: 0x0444,
  27395. egrave: 0x00E8,
  27396. egujarati: 0x0A8F,
  27397. eharmenian: 0x0567,
  27398. ehbopomofo: 0x311D,
  27399. ehiragana: 0x3048,
  27400. ehookabove: 0x1EBB,
  27401. eibopomofo: 0x311F,
  27402. eight: 0x0038,
  27403. eightarabic: 0x0668,
  27404. eightbengali: 0x09EE,
  27405. eightcircle: 0x2467,
  27406. eightcircleinversesansserif: 0x2791,
  27407. eightdeva: 0x096E,
  27408. eighteencircle: 0x2471,
  27409. eighteenparen: 0x2485,
  27410. eighteenperiod: 0x2499,
  27411. eightgujarati: 0x0AEE,
  27412. eightgurmukhi: 0x0A6E,
  27413. eighthackarabic: 0x0668,
  27414. eighthangzhou: 0x3028,
  27415. eighthnotebeamed: 0x266B,
  27416. eightideographicparen: 0x3227,
  27417. eightinferior: 0x2088,
  27418. eightmonospace: 0xFF18,
  27419. eightoldstyle: 0xF738,
  27420. eightparen: 0x247B,
  27421. eightperiod: 0x248F,
  27422. eightpersian: 0x06F8,
  27423. eightroman: 0x2177,
  27424. eightsuperior: 0x2078,
  27425. eightthai: 0x0E58,
  27426. einvertedbreve: 0x0207,
  27427. eiotifiedcyrillic: 0x0465,
  27428. ekatakana: 0x30A8,
  27429. ekatakanahalfwidth: 0xFF74,
  27430. ekonkargurmukhi: 0x0A74,
  27431. ekorean: 0x3154,
  27432. elcyrillic: 0x043B,
  27433. element: 0x2208,
  27434. elevencircle: 0x246A,
  27435. elevenparen: 0x247E,
  27436. elevenperiod: 0x2492,
  27437. elevenroman: 0x217A,
  27438. ellipsis: 0x2026,
  27439. ellipsisvertical: 0x22EE,
  27440. emacron: 0x0113,
  27441. emacronacute: 0x1E17,
  27442. emacrongrave: 0x1E15,
  27443. emcyrillic: 0x043C,
  27444. emdash: 0x2014,
  27445. emdashvertical: 0xFE31,
  27446. emonospace: 0xFF45,
  27447. emphasismarkarmenian: 0x055B,
  27448. emptyset: 0x2205,
  27449. enbopomofo: 0x3123,
  27450. encyrillic: 0x043D,
  27451. endash: 0x2013,
  27452. endashvertical: 0xFE32,
  27453. endescendercyrillic: 0x04A3,
  27454. eng: 0x014B,
  27455. engbopomofo: 0x3125,
  27456. enghecyrillic: 0x04A5,
  27457. enhookcyrillic: 0x04C8,
  27458. enspace: 0x2002,
  27459. eogonek: 0x0119,
  27460. eokorean: 0x3153,
  27461. eopen: 0x025B,
  27462. eopenclosed: 0x029A,
  27463. eopenreversed: 0x025C,
  27464. eopenreversedclosed: 0x025E,
  27465. eopenreversedhook: 0x025D,
  27466. eparen: 0x24A0,
  27467. epsilon: 0x03B5,
  27468. epsilontonos: 0x03AD,
  27469. equal: 0x003D,
  27470. equalmonospace: 0xFF1D,
  27471. equalsmall: 0xFE66,
  27472. equalsuperior: 0x207C,
  27473. equivalence: 0x2261,
  27474. erbopomofo: 0x3126,
  27475. ercyrillic: 0x0440,
  27476. ereversed: 0x0258,
  27477. ereversedcyrillic: 0x044D,
  27478. escyrillic: 0x0441,
  27479. esdescendercyrillic: 0x04AB,
  27480. esh: 0x0283,
  27481. eshcurl: 0x0286,
  27482. eshortdeva: 0x090E,
  27483. eshortvowelsigndeva: 0x0946,
  27484. eshreversedloop: 0x01AA,
  27485. eshsquatreversed: 0x0285,
  27486. esmallhiragana: 0x3047,
  27487. esmallkatakana: 0x30A7,
  27488. esmallkatakanahalfwidth: 0xFF6A,
  27489. estimated: 0x212E,
  27490. esuperior: 0xF6EC,
  27491. eta: 0x03B7,
  27492. etarmenian: 0x0568,
  27493. etatonos: 0x03AE,
  27494. eth: 0x00F0,
  27495. etilde: 0x1EBD,
  27496. etildebelow: 0x1E1B,
  27497. etnahtafoukhhebrew: 0x0591,
  27498. etnahtafoukhlefthebrew: 0x0591,
  27499. etnahtahebrew: 0x0591,
  27500. etnahtalefthebrew: 0x0591,
  27501. eturned: 0x01DD,
  27502. eukorean: 0x3161,
  27503. euro: 0x20AC,
  27504. evowelsignbengali: 0x09C7,
  27505. evowelsigndeva: 0x0947,
  27506. evowelsigngujarati: 0x0AC7,
  27507. exclam: 0x0021,
  27508. exclamarmenian: 0x055C,
  27509. exclamdbl: 0x203C,
  27510. exclamdown: 0x00A1,
  27511. exclamdownsmall: 0xF7A1,
  27512. exclammonospace: 0xFF01,
  27513. exclamsmall: 0xF721,
  27514. existential: 0x2203,
  27515. ezh: 0x0292,
  27516. ezhcaron: 0x01EF,
  27517. ezhcurl: 0x0293,
  27518. ezhreversed: 0x01B9,
  27519. ezhtail: 0x01BA,
  27520. f: 0x0066,
  27521. fadeva: 0x095E,
  27522. fagurmukhi: 0x0A5E,
  27523. fahrenheit: 0x2109,
  27524. fathaarabic: 0x064E,
  27525. fathalowarabic: 0x064E,
  27526. fathatanarabic: 0x064B,
  27527. fbopomofo: 0x3108,
  27528. fcircle: 0x24D5,
  27529. fdotaccent: 0x1E1F,
  27530. feharabic: 0x0641,
  27531. feharmenian: 0x0586,
  27532. fehfinalarabic: 0xFED2,
  27533. fehinitialarabic: 0xFED3,
  27534. fehmedialarabic: 0xFED4,
  27535. feicoptic: 0x03E5,
  27536. female: 0x2640,
  27537. ff: 0xFB00,
  27538. ffi: 0xFB03,
  27539. ffl: 0xFB04,
  27540. fi: 0xFB01,
  27541. fifteencircle: 0x246E,
  27542. fifteenparen: 0x2482,
  27543. fifteenperiod: 0x2496,
  27544. figuredash: 0x2012,
  27545. filledbox: 0x25A0,
  27546. filledrect: 0x25AC,
  27547. finalkaf: 0x05DA,
  27548. finalkafdagesh: 0xFB3A,
  27549. finalkafdageshhebrew: 0xFB3A,
  27550. finalkafhebrew: 0x05DA,
  27551. finalmem: 0x05DD,
  27552. finalmemhebrew: 0x05DD,
  27553. finalnun: 0x05DF,
  27554. finalnunhebrew: 0x05DF,
  27555. finalpe: 0x05E3,
  27556. finalpehebrew: 0x05E3,
  27557. finaltsadi: 0x05E5,
  27558. finaltsadihebrew: 0x05E5,
  27559. firsttonechinese: 0x02C9,
  27560. fisheye: 0x25C9,
  27561. fitacyrillic: 0x0473,
  27562. five: 0x0035,
  27563. fivearabic: 0x0665,
  27564. fivebengali: 0x09EB,
  27565. fivecircle: 0x2464,
  27566. fivecircleinversesansserif: 0x278E,
  27567. fivedeva: 0x096B,
  27568. fiveeighths: 0x215D,
  27569. fivegujarati: 0x0AEB,
  27570. fivegurmukhi: 0x0A6B,
  27571. fivehackarabic: 0x0665,
  27572. fivehangzhou: 0x3025,
  27573. fiveideographicparen: 0x3224,
  27574. fiveinferior: 0x2085,
  27575. fivemonospace: 0xFF15,
  27576. fiveoldstyle: 0xF735,
  27577. fiveparen: 0x2478,
  27578. fiveperiod: 0x248C,
  27579. fivepersian: 0x06F5,
  27580. fiveroman: 0x2174,
  27581. fivesuperior: 0x2075,
  27582. fivethai: 0x0E55,
  27583. fl: 0xFB02,
  27584. florin: 0x0192,
  27585. fmonospace: 0xFF46,
  27586. fmsquare: 0x3399,
  27587. fofanthai: 0x0E1F,
  27588. fofathai: 0x0E1D,
  27589. fongmanthai: 0x0E4F,
  27590. forall: 0x2200,
  27591. four: 0x0034,
  27592. fourarabic: 0x0664,
  27593. fourbengali: 0x09EA,
  27594. fourcircle: 0x2463,
  27595. fourcircleinversesansserif: 0x278D,
  27596. fourdeva: 0x096A,
  27597. fourgujarati: 0x0AEA,
  27598. fourgurmukhi: 0x0A6A,
  27599. fourhackarabic: 0x0664,
  27600. fourhangzhou: 0x3024,
  27601. fourideographicparen: 0x3223,
  27602. fourinferior: 0x2084,
  27603. fourmonospace: 0xFF14,
  27604. fournumeratorbengali: 0x09F7,
  27605. fouroldstyle: 0xF734,
  27606. fourparen: 0x2477,
  27607. fourperiod: 0x248B,
  27608. fourpersian: 0x06F4,
  27609. fourroman: 0x2173,
  27610. foursuperior: 0x2074,
  27611. fourteencircle: 0x246D,
  27612. fourteenparen: 0x2481,
  27613. fourteenperiod: 0x2495,
  27614. fourthai: 0x0E54,
  27615. fourthtonechinese: 0x02CB,
  27616. fparen: 0x24A1,
  27617. fraction: 0x2044,
  27618. franc: 0x20A3,
  27619. g: 0x0067,
  27620. gabengali: 0x0997,
  27621. gacute: 0x01F5,
  27622. gadeva: 0x0917,
  27623. gafarabic: 0x06AF,
  27624. gaffinalarabic: 0xFB93,
  27625. gafinitialarabic: 0xFB94,
  27626. gafmedialarabic: 0xFB95,
  27627. gagujarati: 0x0A97,
  27628. gagurmukhi: 0x0A17,
  27629. gahiragana: 0x304C,
  27630. gakatakana: 0x30AC,
  27631. gamma: 0x03B3,
  27632. gammalatinsmall: 0x0263,
  27633. gammasuperior: 0x02E0,
  27634. gangiacoptic: 0x03EB,
  27635. gbopomofo: 0x310D,
  27636. gbreve: 0x011F,
  27637. gcaron: 0x01E7,
  27638. gcedilla: 0x0123,
  27639. gcircle: 0x24D6,
  27640. gcircumflex: 0x011D,
  27641. gcommaaccent: 0x0123,
  27642. gdot: 0x0121,
  27643. gdotaccent: 0x0121,
  27644. gecyrillic: 0x0433,
  27645. gehiragana: 0x3052,
  27646. gekatakana: 0x30B2,
  27647. geometricallyequal: 0x2251,
  27648. gereshaccenthebrew: 0x059C,
  27649. gereshhebrew: 0x05F3,
  27650. gereshmuqdamhebrew: 0x059D,
  27651. germandbls: 0x00DF,
  27652. gershayimaccenthebrew: 0x059E,
  27653. gershayimhebrew: 0x05F4,
  27654. getamark: 0x3013,
  27655. ghabengali: 0x0998,
  27656. ghadarmenian: 0x0572,
  27657. ghadeva: 0x0918,
  27658. ghagujarati: 0x0A98,
  27659. ghagurmukhi: 0x0A18,
  27660. ghainarabic: 0x063A,
  27661. ghainfinalarabic: 0xFECE,
  27662. ghaininitialarabic: 0xFECF,
  27663. ghainmedialarabic: 0xFED0,
  27664. ghemiddlehookcyrillic: 0x0495,
  27665. ghestrokecyrillic: 0x0493,
  27666. gheupturncyrillic: 0x0491,
  27667. ghhadeva: 0x095A,
  27668. ghhagurmukhi: 0x0A5A,
  27669. ghook: 0x0260,
  27670. ghzsquare: 0x3393,
  27671. gihiragana: 0x304E,
  27672. gikatakana: 0x30AE,
  27673. gimarmenian: 0x0563,
  27674. gimel: 0x05D2,
  27675. gimeldagesh: 0xFB32,
  27676. gimeldageshhebrew: 0xFB32,
  27677. gimelhebrew: 0x05D2,
  27678. gjecyrillic: 0x0453,
  27679. glottalinvertedstroke: 0x01BE,
  27680. glottalstop: 0x0294,
  27681. glottalstopinverted: 0x0296,
  27682. glottalstopmod: 0x02C0,
  27683. glottalstopreversed: 0x0295,
  27684. glottalstopreversedmod: 0x02C1,
  27685. glottalstopreversedsuperior: 0x02E4,
  27686. glottalstopstroke: 0x02A1,
  27687. glottalstopstrokereversed: 0x02A2,
  27688. gmacron: 0x1E21,
  27689. gmonospace: 0xFF47,
  27690. gohiragana: 0x3054,
  27691. gokatakana: 0x30B4,
  27692. gparen: 0x24A2,
  27693. gpasquare: 0x33AC,
  27694. gradient: 0x2207,
  27695. grave: 0x0060,
  27696. gravebelowcmb: 0x0316,
  27697. gravecmb: 0x0300,
  27698. gravecomb: 0x0300,
  27699. gravedeva: 0x0953,
  27700. gravelowmod: 0x02CE,
  27701. gravemonospace: 0xFF40,
  27702. gravetonecmb: 0x0340,
  27703. greater: 0x003E,
  27704. greaterequal: 0x2265,
  27705. greaterequalorless: 0x22DB,
  27706. greatermonospace: 0xFF1E,
  27707. greaterorequivalent: 0x2273,
  27708. greaterorless: 0x2277,
  27709. greateroverequal: 0x2267,
  27710. greatersmall: 0xFE65,
  27711. gscript: 0x0261,
  27712. gstroke: 0x01E5,
  27713. guhiragana: 0x3050,
  27714. guillemotleft: 0x00AB,
  27715. guillemotright: 0x00BB,
  27716. guilsinglleft: 0x2039,
  27717. guilsinglright: 0x203A,
  27718. gukatakana: 0x30B0,
  27719. guramusquare: 0x3318,
  27720. gysquare: 0x33C9,
  27721. h: 0x0068,
  27722. haabkhasiancyrillic: 0x04A9,
  27723. haaltonearabic: 0x06C1,
  27724. habengali: 0x09B9,
  27725. hadescendercyrillic: 0x04B3,
  27726. hadeva: 0x0939,
  27727. hagujarati: 0x0AB9,
  27728. hagurmukhi: 0x0A39,
  27729. haharabic: 0x062D,
  27730. hahfinalarabic: 0xFEA2,
  27731. hahinitialarabic: 0xFEA3,
  27732. hahiragana: 0x306F,
  27733. hahmedialarabic: 0xFEA4,
  27734. haitusquare: 0x332A,
  27735. hakatakana: 0x30CF,
  27736. hakatakanahalfwidth: 0xFF8A,
  27737. halantgurmukhi: 0x0A4D,
  27738. hamzaarabic: 0x0621,
  27739. hamzalowarabic: 0x0621,
  27740. hangulfiller: 0x3164,
  27741. hardsigncyrillic: 0x044A,
  27742. harpoonleftbarbup: 0x21BC,
  27743. harpoonrightbarbup: 0x21C0,
  27744. hasquare: 0x33CA,
  27745. hatafpatah: 0x05B2,
  27746. hatafpatah16: 0x05B2,
  27747. hatafpatah23: 0x05B2,
  27748. hatafpatah2f: 0x05B2,
  27749. hatafpatahhebrew: 0x05B2,
  27750. hatafpatahnarrowhebrew: 0x05B2,
  27751. hatafpatahquarterhebrew: 0x05B2,
  27752. hatafpatahwidehebrew: 0x05B2,
  27753. hatafqamats: 0x05B3,
  27754. hatafqamats1b: 0x05B3,
  27755. hatafqamats28: 0x05B3,
  27756. hatafqamats34: 0x05B3,
  27757. hatafqamatshebrew: 0x05B3,
  27758. hatafqamatsnarrowhebrew: 0x05B3,
  27759. hatafqamatsquarterhebrew: 0x05B3,
  27760. hatafqamatswidehebrew: 0x05B3,
  27761. hatafsegol: 0x05B1,
  27762. hatafsegol17: 0x05B1,
  27763. hatafsegol24: 0x05B1,
  27764. hatafsegol30: 0x05B1,
  27765. hatafsegolhebrew: 0x05B1,
  27766. hatafsegolnarrowhebrew: 0x05B1,
  27767. hatafsegolquarterhebrew: 0x05B1,
  27768. hatafsegolwidehebrew: 0x05B1,
  27769. hbar: 0x0127,
  27770. hbopomofo: 0x310F,
  27771. hbrevebelow: 0x1E2B,
  27772. hcedilla: 0x1E29,
  27773. hcircle: 0x24D7,
  27774. hcircumflex: 0x0125,
  27775. hdieresis: 0x1E27,
  27776. hdotaccent: 0x1E23,
  27777. hdotbelow: 0x1E25,
  27778. he: 0x05D4,
  27779. heart: 0x2665,
  27780. heartsuitblack: 0x2665,
  27781. heartsuitwhite: 0x2661,
  27782. hedagesh: 0xFB34,
  27783. hedageshhebrew: 0xFB34,
  27784. hehaltonearabic: 0x06C1,
  27785. heharabic: 0x0647,
  27786. hehebrew: 0x05D4,
  27787. hehfinalaltonearabic: 0xFBA7,
  27788. hehfinalalttwoarabic: 0xFEEA,
  27789. hehfinalarabic: 0xFEEA,
  27790. hehhamzaabovefinalarabic: 0xFBA5,
  27791. hehhamzaaboveisolatedarabic: 0xFBA4,
  27792. hehinitialaltonearabic: 0xFBA8,
  27793. hehinitialarabic: 0xFEEB,
  27794. hehiragana: 0x3078,
  27795. hehmedialaltonearabic: 0xFBA9,
  27796. hehmedialarabic: 0xFEEC,
  27797. heiseierasquare: 0x337B,
  27798. hekatakana: 0x30D8,
  27799. hekatakanahalfwidth: 0xFF8D,
  27800. hekutaarusquare: 0x3336,
  27801. henghook: 0x0267,
  27802. herutusquare: 0x3339,
  27803. het: 0x05D7,
  27804. hethebrew: 0x05D7,
  27805. hhook: 0x0266,
  27806. hhooksuperior: 0x02B1,
  27807. hieuhacirclekorean: 0x327B,
  27808. hieuhaparenkorean: 0x321B,
  27809. hieuhcirclekorean: 0x326D,
  27810. hieuhkorean: 0x314E,
  27811. hieuhparenkorean: 0x320D,
  27812. hihiragana: 0x3072,
  27813. hikatakana: 0x30D2,
  27814. hikatakanahalfwidth: 0xFF8B,
  27815. hiriq: 0x05B4,
  27816. hiriq14: 0x05B4,
  27817. hiriq21: 0x05B4,
  27818. hiriq2d: 0x05B4,
  27819. hiriqhebrew: 0x05B4,
  27820. hiriqnarrowhebrew: 0x05B4,
  27821. hiriqquarterhebrew: 0x05B4,
  27822. hiriqwidehebrew: 0x05B4,
  27823. hlinebelow: 0x1E96,
  27824. hmonospace: 0xFF48,
  27825. hoarmenian: 0x0570,
  27826. hohipthai: 0x0E2B,
  27827. hohiragana: 0x307B,
  27828. hokatakana: 0x30DB,
  27829. hokatakanahalfwidth: 0xFF8E,
  27830. holam: 0x05B9,
  27831. holam19: 0x05B9,
  27832. holam26: 0x05B9,
  27833. holam32: 0x05B9,
  27834. holamhebrew: 0x05B9,
  27835. holamnarrowhebrew: 0x05B9,
  27836. holamquarterhebrew: 0x05B9,
  27837. holamwidehebrew: 0x05B9,
  27838. honokhukthai: 0x0E2E,
  27839. hookabovecomb: 0x0309,
  27840. hookcmb: 0x0309,
  27841. hookpalatalizedbelowcmb: 0x0321,
  27842. hookretroflexbelowcmb: 0x0322,
  27843. hoonsquare: 0x3342,
  27844. horicoptic: 0x03E9,
  27845. horizontalbar: 0x2015,
  27846. horncmb: 0x031B,
  27847. hotsprings: 0x2668,
  27848. house: 0x2302,
  27849. hparen: 0x24A3,
  27850. hsuperior: 0x02B0,
  27851. hturned: 0x0265,
  27852. huhiragana: 0x3075,
  27853. huiitosquare: 0x3333,
  27854. hukatakana: 0x30D5,
  27855. hukatakanahalfwidth: 0xFF8C,
  27856. hungarumlaut: 0x02DD,
  27857. hungarumlautcmb: 0x030B,
  27858. hv: 0x0195,
  27859. hyphen: 0x002D,
  27860. hypheninferior: 0xF6E5,
  27861. hyphenmonospace: 0xFF0D,
  27862. hyphensmall: 0xFE63,
  27863. hyphensuperior: 0xF6E6,
  27864. hyphentwo: 0x2010,
  27865. i: 0x0069,
  27866. iacute: 0x00ED,
  27867. iacyrillic: 0x044F,
  27868. ibengali: 0x0987,
  27869. ibopomofo: 0x3127,
  27870. ibreve: 0x012D,
  27871. icaron: 0x01D0,
  27872. icircle: 0x24D8,
  27873. icircumflex: 0x00EE,
  27874. icyrillic: 0x0456,
  27875. idblgrave: 0x0209,
  27876. ideographearthcircle: 0x328F,
  27877. ideographfirecircle: 0x328B,
  27878. ideographicallianceparen: 0x323F,
  27879. ideographiccallparen: 0x323A,
  27880. ideographiccentrecircle: 0x32A5,
  27881. ideographicclose: 0x3006,
  27882. ideographiccomma: 0x3001,
  27883. ideographiccommaleft: 0xFF64,
  27884. ideographiccongratulationparen: 0x3237,
  27885. ideographiccorrectcircle: 0x32A3,
  27886. ideographicearthparen: 0x322F,
  27887. ideographicenterpriseparen: 0x323D,
  27888. ideographicexcellentcircle: 0x329D,
  27889. ideographicfestivalparen: 0x3240,
  27890. ideographicfinancialcircle: 0x3296,
  27891. ideographicfinancialparen: 0x3236,
  27892. ideographicfireparen: 0x322B,
  27893. ideographichaveparen: 0x3232,
  27894. ideographichighcircle: 0x32A4,
  27895. ideographiciterationmark: 0x3005,
  27896. ideographiclaborcircle: 0x3298,
  27897. ideographiclaborparen: 0x3238,
  27898. ideographicleftcircle: 0x32A7,
  27899. ideographiclowcircle: 0x32A6,
  27900. ideographicmedicinecircle: 0x32A9,
  27901. ideographicmetalparen: 0x322E,
  27902. ideographicmoonparen: 0x322A,
  27903. ideographicnameparen: 0x3234,
  27904. ideographicperiod: 0x3002,
  27905. ideographicprintcircle: 0x329E,
  27906. ideographicreachparen: 0x3243,
  27907. ideographicrepresentparen: 0x3239,
  27908. ideographicresourceparen: 0x323E,
  27909. ideographicrightcircle: 0x32A8,
  27910. ideographicsecretcircle: 0x3299,
  27911. ideographicselfparen: 0x3242,
  27912. ideographicsocietyparen: 0x3233,
  27913. ideographicspace: 0x3000,
  27914. ideographicspecialparen: 0x3235,
  27915. ideographicstockparen: 0x3231,
  27916. ideographicstudyparen: 0x323B,
  27917. ideographicsunparen: 0x3230,
  27918. ideographicsuperviseparen: 0x323C,
  27919. ideographicwaterparen: 0x322C,
  27920. ideographicwoodparen: 0x322D,
  27921. ideographiczero: 0x3007,
  27922. ideographmetalcircle: 0x328E,
  27923. ideographmooncircle: 0x328A,
  27924. ideographnamecircle: 0x3294,
  27925. ideographsuncircle: 0x3290,
  27926. ideographwatercircle: 0x328C,
  27927. ideographwoodcircle: 0x328D,
  27928. ideva: 0x0907,
  27929. idieresis: 0x00EF,
  27930. idieresisacute: 0x1E2F,
  27931. idieresiscyrillic: 0x04E5,
  27932. idotbelow: 0x1ECB,
  27933. iebrevecyrillic: 0x04D7,
  27934. iecyrillic: 0x0435,
  27935. ieungacirclekorean: 0x3275,
  27936. ieungaparenkorean: 0x3215,
  27937. ieungcirclekorean: 0x3267,
  27938. ieungkorean: 0x3147,
  27939. ieungparenkorean: 0x3207,
  27940. igrave: 0x00EC,
  27941. igujarati: 0x0A87,
  27942. igurmukhi: 0x0A07,
  27943. ihiragana: 0x3044,
  27944. ihookabove: 0x1EC9,
  27945. iibengali: 0x0988,
  27946. iicyrillic: 0x0438,
  27947. iideva: 0x0908,
  27948. iigujarati: 0x0A88,
  27949. iigurmukhi: 0x0A08,
  27950. iimatragurmukhi: 0x0A40,
  27951. iinvertedbreve: 0x020B,
  27952. iishortcyrillic: 0x0439,
  27953. iivowelsignbengali: 0x09C0,
  27954. iivowelsigndeva: 0x0940,
  27955. iivowelsigngujarati: 0x0AC0,
  27956. ij: 0x0133,
  27957. ikatakana: 0x30A4,
  27958. ikatakanahalfwidth: 0xFF72,
  27959. ikorean: 0x3163,
  27960. ilde: 0x02DC,
  27961. iluyhebrew: 0x05AC,
  27962. imacron: 0x012B,
  27963. imacroncyrillic: 0x04E3,
  27964. imageorapproximatelyequal: 0x2253,
  27965. imatragurmukhi: 0x0A3F,
  27966. imonospace: 0xFF49,
  27967. increment: 0x2206,
  27968. infinity: 0x221E,
  27969. iniarmenian: 0x056B,
  27970. integral: 0x222B,
  27971. integralbottom: 0x2321,
  27972. integralbt: 0x2321,
  27973. integralex: 0xF8F5,
  27974. integraltop: 0x2320,
  27975. integraltp: 0x2320,
  27976. intersection: 0x2229,
  27977. intisquare: 0x3305,
  27978. invbullet: 0x25D8,
  27979. invcircle: 0x25D9,
  27980. invsmileface: 0x263B,
  27981. iocyrillic: 0x0451,
  27982. iogonek: 0x012F,
  27983. iota: 0x03B9,
  27984. iotadieresis: 0x03CA,
  27985. iotadieresistonos: 0x0390,
  27986. iotalatin: 0x0269,
  27987. iotatonos: 0x03AF,
  27988. iparen: 0x24A4,
  27989. irigurmukhi: 0x0A72,
  27990. ismallhiragana: 0x3043,
  27991. ismallkatakana: 0x30A3,
  27992. ismallkatakanahalfwidth: 0xFF68,
  27993. issharbengali: 0x09FA,
  27994. istroke: 0x0268,
  27995. isuperior: 0xF6ED,
  27996. iterationhiragana: 0x309D,
  27997. iterationkatakana: 0x30FD,
  27998. itilde: 0x0129,
  27999. itildebelow: 0x1E2D,
  28000. iubopomofo: 0x3129,
  28001. iucyrillic: 0x044E,
  28002. ivowelsignbengali: 0x09BF,
  28003. ivowelsigndeva: 0x093F,
  28004. ivowelsigngujarati: 0x0ABF,
  28005. izhitsacyrillic: 0x0475,
  28006. izhitsadblgravecyrillic: 0x0477,
  28007. j: 0x006A,
  28008. jaarmenian: 0x0571,
  28009. jabengali: 0x099C,
  28010. jadeva: 0x091C,
  28011. jagujarati: 0x0A9C,
  28012. jagurmukhi: 0x0A1C,
  28013. jbopomofo: 0x3110,
  28014. jcaron: 0x01F0,
  28015. jcircle: 0x24D9,
  28016. jcircumflex: 0x0135,
  28017. jcrossedtail: 0x029D,
  28018. jdotlessstroke: 0x025F,
  28019. jecyrillic: 0x0458,
  28020. jeemarabic: 0x062C,
  28021. jeemfinalarabic: 0xFE9E,
  28022. jeeminitialarabic: 0xFE9F,
  28023. jeemmedialarabic: 0xFEA0,
  28024. jeharabic: 0x0698,
  28025. jehfinalarabic: 0xFB8B,
  28026. jhabengali: 0x099D,
  28027. jhadeva: 0x091D,
  28028. jhagujarati: 0x0A9D,
  28029. jhagurmukhi: 0x0A1D,
  28030. jheharmenian: 0x057B,
  28031. jis: 0x3004,
  28032. jmonospace: 0xFF4A,
  28033. jparen: 0x24A5,
  28034. jsuperior: 0x02B2,
  28035. k: 0x006B,
  28036. kabashkircyrillic: 0x04A1,
  28037. kabengali: 0x0995,
  28038. kacute: 0x1E31,
  28039. kacyrillic: 0x043A,
  28040. kadescendercyrillic: 0x049B,
  28041. kadeva: 0x0915,
  28042. kaf: 0x05DB,
  28043. kafarabic: 0x0643,
  28044. kafdagesh: 0xFB3B,
  28045. kafdageshhebrew: 0xFB3B,
  28046. kaffinalarabic: 0xFEDA,
  28047. kafhebrew: 0x05DB,
  28048. kafinitialarabic: 0xFEDB,
  28049. kafmedialarabic: 0xFEDC,
  28050. kafrafehebrew: 0xFB4D,
  28051. kagujarati: 0x0A95,
  28052. kagurmukhi: 0x0A15,
  28053. kahiragana: 0x304B,
  28054. kahookcyrillic: 0x04C4,
  28055. kakatakana: 0x30AB,
  28056. kakatakanahalfwidth: 0xFF76,
  28057. kappa: 0x03BA,
  28058. kappasymbolgreek: 0x03F0,
  28059. kapyeounmieumkorean: 0x3171,
  28060. kapyeounphieuphkorean: 0x3184,
  28061. kapyeounpieupkorean: 0x3178,
  28062. kapyeounssangpieupkorean: 0x3179,
  28063. karoriisquare: 0x330D,
  28064. kashidaautoarabic: 0x0640,
  28065. kashidaautonosidebearingarabic: 0x0640,
  28066. kasmallkatakana: 0x30F5,
  28067. kasquare: 0x3384,
  28068. kasraarabic: 0x0650,
  28069. kasratanarabic: 0x064D,
  28070. kastrokecyrillic: 0x049F,
  28071. katahiraprolongmarkhalfwidth: 0xFF70,
  28072. kaverticalstrokecyrillic: 0x049D,
  28073. kbopomofo: 0x310E,
  28074. kcalsquare: 0x3389,
  28075. kcaron: 0x01E9,
  28076. kcedilla: 0x0137,
  28077. kcircle: 0x24DA,
  28078. kcommaaccent: 0x0137,
  28079. kdotbelow: 0x1E33,
  28080. keharmenian: 0x0584,
  28081. kehiragana: 0x3051,
  28082. kekatakana: 0x30B1,
  28083. kekatakanahalfwidth: 0xFF79,
  28084. kenarmenian: 0x056F,
  28085. kesmallkatakana: 0x30F6,
  28086. kgreenlandic: 0x0138,
  28087. khabengali: 0x0996,
  28088. khacyrillic: 0x0445,
  28089. khadeva: 0x0916,
  28090. khagujarati: 0x0A96,
  28091. khagurmukhi: 0x0A16,
  28092. khaharabic: 0x062E,
  28093. khahfinalarabic: 0xFEA6,
  28094. khahinitialarabic: 0xFEA7,
  28095. khahmedialarabic: 0xFEA8,
  28096. kheicoptic: 0x03E7,
  28097. khhadeva: 0x0959,
  28098. khhagurmukhi: 0x0A59,
  28099. khieukhacirclekorean: 0x3278,
  28100. khieukhaparenkorean: 0x3218,
  28101. khieukhcirclekorean: 0x326A,
  28102. khieukhkorean: 0x314B,
  28103. khieukhparenkorean: 0x320A,
  28104. khokhaithai: 0x0E02,
  28105. khokhonthai: 0x0E05,
  28106. khokhuatthai: 0x0E03,
  28107. khokhwaithai: 0x0E04,
  28108. khomutthai: 0x0E5B,
  28109. khook: 0x0199,
  28110. khorakhangthai: 0x0E06,
  28111. khzsquare: 0x3391,
  28112. kihiragana: 0x304D,
  28113. kikatakana: 0x30AD,
  28114. kikatakanahalfwidth: 0xFF77,
  28115. kiroguramusquare: 0x3315,
  28116. kiromeetorusquare: 0x3316,
  28117. kirosquare: 0x3314,
  28118. kiyeokacirclekorean: 0x326E,
  28119. kiyeokaparenkorean: 0x320E,
  28120. kiyeokcirclekorean: 0x3260,
  28121. kiyeokkorean: 0x3131,
  28122. kiyeokparenkorean: 0x3200,
  28123. kiyeoksioskorean: 0x3133,
  28124. kjecyrillic: 0x045C,
  28125. klinebelow: 0x1E35,
  28126. klsquare: 0x3398,
  28127. kmcubedsquare: 0x33A6,
  28128. kmonospace: 0xFF4B,
  28129. kmsquaredsquare: 0x33A2,
  28130. kohiragana: 0x3053,
  28131. kohmsquare: 0x33C0,
  28132. kokaithai: 0x0E01,
  28133. kokatakana: 0x30B3,
  28134. kokatakanahalfwidth: 0xFF7A,
  28135. kooposquare: 0x331E,
  28136. koppacyrillic: 0x0481,
  28137. koreanstandardsymbol: 0x327F,
  28138. koroniscmb: 0x0343,
  28139. kparen: 0x24A6,
  28140. kpasquare: 0x33AA,
  28141. ksicyrillic: 0x046F,
  28142. ktsquare: 0x33CF,
  28143. kturned: 0x029E,
  28144. kuhiragana: 0x304F,
  28145. kukatakana: 0x30AF,
  28146. kukatakanahalfwidth: 0xFF78,
  28147. kvsquare: 0x33B8,
  28148. kwsquare: 0x33BE,
  28149. l: 0x006C,
  28150. labengali: 0x09B2,
  28151. lacute: 0x013A,
  28152. ladeva: 0x0932,
  28153. lagujarati: 0x0AB2,
  28154. lagurmukhi: 0x0A32,
  28155. lakkhangyaothai: 0x0E45,
  28156. lamaleffinalarabic: 0xFEFC,
  28157. lamalefhamzaabovefinalarabic: 0xFEF8,
  28158. lamalefhamzaaboveisolatedarabic: 0xFEF7,
  28159. lamalefhamzabelowfinalarabic: 0xFEFA,
  28160. lamalefhamzabelowisolatedarabic: 0xFEF9,
  28161. lamalefisolatedarabic: 0xFEFB,
  28162. lamalefmaddaabovefinalarabic: 0xFEF6,
  28163. lamalefmaddaaboveisolatedarabic: 0xFEF5,
  28164. lamarabic: 0x0644,
  28165. lambda: 0x03BB,
  28166. lambdastroke: 0x019B,
  28167. lamed: 0x05DC,
  28168. lameddagesh: 0xFB3C,
  28169. lameddageshhebrew: 0xFB3C,
  28170. lamedhebrew: 0x05DC,
  28171. lamfinalarabic: 0xFEDE,
  28172. lamhahinitialarabic: 0xFCCA,
  28173. laminitialarabic: 0xFEDF,
  28174. lamjeeminitialarabic: 0xFCC9,
  28175. lamkhahinitialarabic: 0xFCCB,
  28176. lamlamhehisolatedarabic: 0xFDF2,
  28177. lammedialarabic: 0xFEE0,
  28178. lammeemhahinitialarabic: 0xFD88,
  28179. lammeeminitialarabic: 0xFCCC,
  28180. largecircle: 0x25EF,
  28181. lbar: 0x019A,
  28182. lbelt: 0x026C,
  28183. lbopomofo: 0x310C,
  28184. lcaron: 0x013E,
  28185. lcedilla: 0x013C,
  28186. lcircle: 0x24DB,
  28187. lcircumflexbelow: 0x1E3D,
  28188. lcommaaccent: 0x013C,
  28189. ldot: 0x0140,
  28190. ldotaccent: 0x0140,
  28191. ldotbelow: 0x1E37,
  28192. ldotbelowmacron: 0x1E39,
  28193. leftangleabovecmb: 0x031A,
  28194. lefttackbelowcmb: 0x0318,
  28195. less: 0x003C,
  28196. lessequal: 0x2264,
  28197. lessequalorgreater: 0x22DA,
  28198. lessmonospace: 0xFF1C,
  28199. lessorequivalent: 0x2272,
  28200. lessorgreater: 0x2276,
  28201. lessoverequal: 0x2266,
  28202. lesssmall: 0xFE64,
  28203. lezh: 0x026E,
  28204. lfblock: 0x258C,
  28205. lhookretroflex: 0x026D,
  28206. lira: 0x20A4,
  28207. liwnarmenian: 0x056C,
  28208. lj: 0x01C9,
  28209. ljecyrillic: 0x0459,
  28210. ll: 0xF6C0,
  28211. lladeva: 0x0933,
  28212. llagujarati: 0x0AB3,
  28213. llinebelow: 0x1E3B,
  28214. llladeva: 0x0934,
  28215. llvocalicbengali: 0x09E1,
  28216. llvocalicdeva: 0x0961,
  28217. llvocalicvowelsignbengali: 0x09E3,
  28218. llvocalicvowelsigndeva: 0x0963,
  28219. lmiddletilde: 0x026B,
  28220. lmonospace: 0xFF4C,
  28221. lmsquare: 0x33D0,
  28222. lochulathai: 0x0E2C,
  28223. logicaland: 0x2227,
  28224. logicalnot: 0x00AC,
  28225. logicalnotreversed: 0x2310,
  28226. logicalor: 0x2228,
  28227. lolingthai: 0x0E25,
  28228. longs: 0x017F,
  28229. lowlinecenterline: 0xFE4E,
  28230. lowlinecmb: 0x0332,
  28231. lowlinedashed: 0xFE4D,
  28232. lozenge: 0x25CA,
  28233. lparen: 0x24A7,
  28234. lslash: 0x0142,
  28235. lsquare: 0x2113,
  28236. lsuperior: 0xF6EE,
  28237. ltshade: 0x2591,
  28238. luthai: 0x0E26,
  28239. lvocalicbengali: 0x098C,
  28240. lvocalicdeva: 0x090C,
  28241. lvocalicvowelsignbengali: 0x09E2,
  28242. lvocalicvowelsigndeva: 0x0962,
  28243. lxsquare: 0x33D3,
  28244. m: 0x006D,
  28245. mabengali: 0x09AE,
  28246. macron: 0x00AF,
  28247. macronbelowcmb: 0x0331,
  28248. macroncmb: 0x0304,
  28249. macronlowmod: 0x02CD,
  28250. macronmonospace: 0xFFE3,
  28251. macute: 0x1E3F,
  28252. madeva: 0x092E,
  28253. magujarati: 0x0AAE,
  28254. magurmukhi: 0x0A2E,
  28255. mahapakhhebrew: 0x05A4,
  28256. mahapakhlefthebrew: 0x05A4,
  28257. mahiragana: 0x307E,
  28258. maichattawalowleftthai: 0xF895,
  28259. maichattawalowrightthai: 0xF894,
  28260. maichattawathai: 0x0E4B,
  28261. maichattawaupperleftthai: 0xF893,
  28262. maieklowleftthai: 0xF88C,
  28263. maieklowrightthai: 0xF88B,
  28264. maiekthai: 0x0E48,
  28265. maiekupperleftthai: 0xF88A,
  28266. maihanakatleftthai: 0xF884,
  28267. maihanakatthai: 0x0E31,
  28268. maitaikhuleftthai: 0xF889,
  28269. maitaikhuthai: 0x0E47,
  28270. maitholowleftthai: 0xF88F,
  28271. maitholowrightthai: 0xF88E,
  28272. maithothai: 0x0E49,
  28273. maithoupperleftthai: 0xF88D,
  28274. maitrilowleftthai: 0xF892,
  28275. maitrilowrightthai: 0xF891,
  28276. maitrithai: 0x0E4A,
  28277. maitriupperleftthai: 0xF890,
  28278. maiyamokthai: 0x0E46,
  28279. makatakana: 0x30DE,
  28280. makatakanahalfwidth: 0xFF8F,
  28281. male: 0x2642,
  28282. mansyonsquare: 0x3347,
  28283. maqafhebrew: 0x05BE,
  28284. mars: 0x2642,
  28285. masoracirclehebrew: 0x05AF,
  28286. masquare: 0x3383,
  28287. mbopomofo: 0x3107,
  28288. mbsquare: 0x33D4,
  28289. mcircle: 0x24DC,
  28290. mcubedsquare: 0x33A5,
  28291. mdotaccent: 0x1E41,
  28292. mdotbelow: 0x1E43,
  28293. meemarabic: 0x0645,
  28294. meemfinalarabic: 0xFEE2,
  28295. meeminitialarabic: 0xFEE3,
  28296. meemmedialarabic: 0xFEE4,
  28297. meemmeeminitialarabic: 0xFCD1,
  28298. meemmeemisolatedarabic: 0xFC48,
  28299. meetorusquare: 0x334D,
  28300. mehiragana: 0x3081,
  28301. meizierasquare: 0x337E,
  28302. mekatakana: 0x30E1,
  28303. mekatakanahalfwidth: 0xFF92,
  28304. mem: 0x05DE,
  28305. memdagesh: 0xFB3E,
  28306. memdageshhebrew: 0xFB3E,
  28307. memhebrew: 0x05DE,
  28308. menarmenian: 0x0574,
  28309. merkhahebrew: 0x05A5,
  28310. merkhakefulahebrew: 0x05A6,
  28311. merkhakefulalefthebrew: 0x05A6,
  28312. merkhalefthebrew: 0x05A5,
  28313. mhook: 0x0271,
  28314. mhzsquare: 0x3392,
  28315. middledotkatakanahalfwidth: 0xFF65,
  28316. middot: 0x00B7,
  28317. mieumacirclekorean: 0x3272,
  28318. mieumaparenkorean: 0x3212,
  28319. mieumcirclekorean: 0x3264,
  28320. mieumkorean: 0x3141,
  28321. mieumpansioskorean: 0x3170,
  28322. mieumparenkorean: 0x3204,
  28323. mieumpieupkorean: 0x316E,
  28324. mieumsioskorean: 0x316F,
  28325. mihiragana: 0x307F,
  28326. mikatakana: 0x30DF,
  28327. mikatakanahalfwidth: 0xFF90,
  28328. minus: 0x2212,
  28329. minusbelowcmb: 0x0320,
  28330. minuscircle: 0x2296,
  28331. minusmod: 0x02D7,
  28332. minusplus: 0x2213,
  28333. minute: 0x2032,
  28334. miribaarusquare: 0x334A,
  28335. mirisquare: 0x3349,
  28336. mlonglegturned: 0x0270,
  28337. mlsquare: 0x3396,
  28338. mmcubedsquare: 0x33A3,
  28339. mmonospace: 0xFF4D,
  28340. mmsquaredsquare: 0x339F,
  28341. mohiragana: 0x3082,
  28342. mohmsquare: 0x33C1,
  28343. mokatakana: 0x30E2,
  28344. mokatakanahalfwidth: 0xFF93,
  28345. molsquare: 0x33D6,
  28346. momathai: 0x0E21,
  28347. moverssquare: 0x33A7,
  28348. moverssquaredsquare: 0x33A8,
  28349. mparen: 0x24A8,
  28350. mpasquare: 0x33AB,
  28351. mssquare: 0x33B3,
  28352. msuperior: 0xF6EF,
  28353. mturned: 0x026F,
  28354. mu: 0x00B5,
  28355. mu1: 0x00B5,
  28356. muasquare: 0x3382,
  28357. muchgreater: 0x226B,
  28358. muchless: 0x226A,
  28359. mufsquare: 0x338C,
  28360. mugreek: 0x03BC,
  28361. mugsquare: 0x338D,
  28362. muhiragana: 0x3080,
  28363. mukatakana: 0x30E0,
  28364. mukatakanahalfwidth: 0xFF91,
  28365. mulsquare: 0x3395,
  28366. multiply: 0x00D7,
  28367. mumsquare: 0x339B,
  28368. munahhebrew: 0x05A3,
  28369. munahlefthebrew: 0x05A3,
  28370. musicalnote: 0x266A,
  28371. musicalnotedbl: 0x266B,
  28372. musicflatsign: 0x266D,
  28373. musicsharpsign: 0x266F,
  28374. mussquare: 0x33B2,
  28375. muvsquare: 0x33B6,
  28376. muwsquare: 0x33BC,
  28377. mvmegasquare: 0x33B9,
  28378. mvsquare: 0x33B7,
  28379. mwmegasquare: 0x33BF,
  28380. mwsquare: 0x33BD,
  28381. n: 0x006E,
  28382. nabengali: 0x09A8,
  28383. nabla: 0x2207,
  28384. nacute: 0x0144,
  28385. nadeva: 0x0928,
  28386. nagujarati: 0x0AA8,
  28387. nagurmukhi: 0x0A28,
  28388. nahiragana: 0x306A,
  28389. nakatakana: 0x30CA,
  28390. nakatakanahalfwidth: 0xFF85,
  28391. napostrophe: 0x0149,
  28392. nasquare: 0x3381,
  28393. nbopomofo: 0x310B,
  28394. nbspace: 0x00A0,
  28395. ncaron: 0x0148,
  28396. ncedilla: 0x0146,
  28397. ncircle: 0x24DD,
  28398. ncircumflexbelow: 0x1E4B,
  28399. ncommaaccent: 0x0146,
  28400. ndotaccent: 0x1E45,
  28401. ndotbelow: 0x1E47,
  28402. nehiragana: 0x306D,
  28403. nekatakana: 0x30CD,
  28404. nekatakanahalfwidth: 0xFF88,
  28405. newsheqelsign: 0x20AA,
  28406. nfsquare: 0x338B,
  28407. ngabengali: 0x0999,
  28408. ngadeva: 0x0919,
  28409. ngagujarati: 0x0A99,
  28410. ngagurmukhi: 0x0A19,
  28411. ngonguthai: 0x0E07,
  28412. nhiragana: 0x3093,
  28413. nhookleft: 0x0272,
  28414. nhookretroflex: 0x0273,
  28415. nieunacirclekorean: 0x326F,
  28416. nieunaparenkorean: 0x320F,
  28417. nieuncieuckorean: 0x3135,
  28418. nieuncirclekorean: 0x3261,
  28419. nieunhieuhkorean: 0x3136,
  28420. nieunkorean: 0x3134,
  28421. nieunpansioskorean: 0x3168,
  28422. nieunparenkorean: 0x3201,
  28423. nieunsioskorean: 0x3167,
  28424. nieuntikeutkorean: 0x3166,
  28425. nihiragana: 0x306B,
  28426. nikatakana: 0x30CB,
  28427. nikatakanahalfwidth: 0xFF86,
  28428. nikhahitleftthai: 0xF899,
  28429. nikhahitthai: 0x0E4D,
  28430. nine: 0x0039,
  28431. ninearabic: 0x0669,
  28432. ninebengali: 0x09EF,
  28433. ninecircle: 0x2468,
  28434. ninecircleinversesansserif: 0x2792,
  28435. ninedeva: 0x096F,
  28436. ninegujarati: 0x0AEF,
  28437. ninegurmukhi: 0x0A6F,
  28438. ninehackarabic: 0x0669,
  28439. ninehangzhou: 0x3029,
  28440. nineideographicparen: 0x3228,
  28441. nineinferior: 0x2089,
  28442. ninemonospace: 0xFF19,
  28443. nineoldstyle: 0xF739,
  28444. nineparen: 0x247C,
  28445. nineperiod: 0x2490,
  28446. ninepersian: 0x06F9,
  28447. nineroman: 0x2178,
  28448. ninesuperior: 0x2079,
  28449. nineteencircle: 0x2472,
  28450. nineteenparen: 0x2486,
  28451. nineteenperiod: 0x249A,
  28452. ninethai: 0x0E59,
  28453. nj: 0x01CC,
  28454. njecyrillic: 0x045A,
  28455. nkatakana: 0x30F3,
  28456. nkatakanahalfwidth: 0xFF9D,
  28457. nlegrightlong: 0x019E,
  28458. nlinebelow: 0x1E49,
  28459. nmonospace: 0xFF4E,
  28460. nmsquare: 0x339A,
  28461. nnabengali: 0x09A3,
  28462. nnadeva: 0x0923,
  28463. nnagujarati: 0x0AA3,
  28464. nnagurmukhi: 0x0A23,
  28465. nnnadeva: 0x0929,
  28466. nohiragana: 0x306E,
  28467. nokatakana: 0x30CE,
  28468. nokatakanahalfwidth: 0xFF89,
  28469. nonbreakingspace: 0x00A0,
  28470. nonenthai: 0x0E13,
  28471. nonuthai: 0x0E19,
  28472. noonarabic: 0x0646,
  28473. noonfinalarabic: 0xFEE6,
  28474. noonghunnaarabic: 0x06BA,
  28475. noonghunnafinalarabic: 0xFB9F,
  28476. nooninitialarabic: 0xFEE7,
  28477. noonjeeminitialarabic: 0xFCD2,
  28478. noonjeemisolatedarabic: 0xFC4B,
  28479. noonmedialarabic: 0xFEE8,
  28480. noonmeeminitialarabic: 0xFCD5,
  28481. noonmeemisolatedarabic: 0xFC4E,
  28482. noonnoonfinalarabic: 0xFC8D,
  28483. notcontains: 0x220C,
  28484. notelement: 0x2209,
  28485. notelementof: 0x2209,
  28486. notequal: 0x2260,
  28487. notgreater: 0x226F,
  28488. notgreaternorequal: 0x2271,
  28489. notgreaternorless: 0x2279,
  28490. notidentical: 0x2262,
  28491. notless: 0x226E,
  28492. notlessnorequal: 0x2270,
  28493. notparallel: 0x2226,
  28494. notprecedes: 0x2280,
  28495. notsubset: 0x2284,
  28496. notsucceeds: 0x2281,
  28497. notsuperset: 0x2285,
  28498. nowarmenian: 0x0576,
  28499. nparen: 0x24A9,
  28500. nssquare: 0x33B1,
  28501. nsuperior: 0x207F,
  28502. ntilde: 0x00F1,
  28503. nu: 0x03BD,
  28504. nuhiragana: 0x306C,
  28505. nukatakana: 0x30CC,
  28506. nukatakanahalfwidth: 0xFF87,
  28507. nuktabengali: 0x09BC,
  28508. nuktadeva: 0x093C,
  28509. nuktagujarati: 0x0ABC,
  28510. nuktagurmukhi: 0x0A3C,
  28511. numbersign: 0x0023,
  28512. numbersignmonospace: 0xFF03,
  28513. numbersignsmall: 0xFE5F,
  28514. numeralsigngreek: 0x0374,
  28515. numeralsignlowergreek: 0x0375,
  28516. numero: 0x2116,
  28517. nun: 0x05E0,
  28518. nundagesh: 0xFB40,
  28519. nundageshhebrew: 0xFB40,
  28520. nunhebrew: 0x05E0,
  28521. nvsquare: 0x33B5,
  28522. nwsquare: 0x33BB,
  28523. nyabengali: 0x099E,
  28524. nyadeva: 0x091E,
  28525. nyagujarati: 0x0A9E,
  28526. nyagurmukhi: 0x0A1E,
  28527. o: 0x006F,
  28528. oacute: 0x00F3,
  28529. oangthai: 0x0E2D,
  28530. obarred: 0x0275,
  28531. obarredcyrillic: 0x04E9,
  28532. obarreddieresiscyrillic: 0x04EB,
  28533. obengali: 0x0993,
  28534. obopomofo: 0x311B,
  28535. obreve: 0x014F,
  28536. ocandradeva: 0x0911,
  28537. ocandragujarati: 0x0A91,
  28538. ocandravowelsigndeva: 0x0949,
  28539. ocandravowelsigngujarati: 0x0AC9,
  28540. ocaron: 0x01D2,
  28541. ocircle: 0x24DE,
  28542. ocircumflex: 0x00F4,
  28543. ocircumflexacute: 0x1ED1,
  28544. ocircumflexdotbelow: 0x1ED9,
  28545. ocircumflexgrave: 0x1ED3,
  28546. ocircumflexhookabove: 0x1ED5,
  28547. ocircumflextilde: 0x1ED7,
  28548. ocyrillic: 0x043E,
  28549. odblacute: 0x0151,
  28550. odblgrave: 0x020D,
  28551. odeva: 0x0913,
  28552. odieresis: 0x00F6,
  28553. odieresiscyrillic: 0x04E7,
  28554. odotbelow: 0x1ECD,
  28555. oe: 0x0153,
  28556. oekorean: 0x315A,
  28557. ogonek: 0x02DB,
  28558. ogonekcmb: 0x0328,
  28559. ograve: 0x00F2,
  28560. ogujarati: 0x0A93,
  28561. oharmenian: 0x0585,
  28562. ohiragana: 0x304A,
  28563. ohookabove: 0x1ECF,
  28564. ohorn: 0x01A1,
  28565. ohornacute: 0x1EDB,
  28566. ohorndotbelow: 0x1EE3,
  28567. ohorngrave: 0x1EDD,
  28568. ohornhookabove: 0x1EDF,
  28569. ohorntilde: 0x1EE1,
  28570. ohungarumlaut: 0x0151,
  28571. oi: 0x01A3,
  28572. oinvertedbreve: 0x020F,
  28573. okatakana: 0x30AA,
  28574. okatakanahalfwidth: 0xFF75,
  28575. okorean: 0x3157,
  28576. olehebrew: 0x05AB,
  28577. omacron: 0x014D,
  28578. omacronacute: 0x1E53,
  28579. omacrongrave: 0x1E51,
  28580. omdeva: 0x0950,
  28581. omega: 0x03C9,
  28582. omega1: 0x03D6,
  28583. omegacyrillic: 0x0461,
  28584. omegalatinclosed: 0x0277,
  28585. omegaroundcyrillic: 0x047B,
  28586. omegatitlocyrillic: 0x047D,
  28587. omegatonos: 0x03CE,
  28588. omgujarati: 0x0AD0,
  28589. omicron: 0x03BF,
  28590. omicrontonos: 0x03CC,
  28591. omonospace: 0xFF4F,
  28592. one: 0x0031,
  28593. onearabic: 0x0661,
  28594. onebengali: 0x09E7,
  28595. onecircle: 0x2460,
  28596. onecircleinversesansserif: 0x278A,
  28597. onedeva: 0x0967,
  28598. onedotenleader: 0x2024,
  28599. oneeighth: 0x215B,
  28600. onefitted: 0xF6DC,
  28601. onegujarati: 0x0AE7,
  28602. onegurmukhi: 0x0A67,
  28603. onehackarabic: 0x0661,
  28604. onehalf: 0x00BD,
  28605. onehangzhou: 0x3021,
  28606. oneideographicparen: 0x3220,
  28607. oneinferior: 0x2081,
  28608. onemonospace: 0xFF11,
  28609. onenumeratorbengali: 0x09F4,
  28610. oneoldstyle: 0xF731,
  28611. oneparen: 0x2474,
  28612. oneperiod: 0x2488,
  28613. onepersian: 0x06F1,
  28614. onequarter: 0x00BC,
  28615. oneroman: 0x2170,
  28616. onesuperior: 0x00B9,
  28617. onethai: 0x0E51,
  28618. onethird: 0x2153,
  28619. oogonek: 0x01EB,
  28620. oogonekmacron: 0x01ED,
  28621. oogurmukhi: 0x0A13,
  28622. oomatragurmukhi: 0x0A4B,
  28623. oopen: 0x0254,
  28624. oparen: 0x24AA,
  28625. openbullet: 0x25E6,
  28626. option: 0x2325,
  28627. ordfeminine: 0x00AA,
  28628. ordmasculine: 0x00BA,
  28629. orthogonal: 0x221F,
  28630. oshortdeva: 0x0912,
  28631. oshortvowelsigndeva: 0x094A,
  28632. oslash: 0x00F8,
  28633. oslashacute: 0x01FF,
  28634. osmallhiragana: 0x3049,
  28635. osmallkatakana: 0x30A9,
  28636. osmallkatakanahalfwidth: 0xFF6B,
  28637. ostrokeacute: 0x01FF,
  28638. osuperior: 0xF6F0,
  28639. otcyrillic: 0x047F,
  28640. otilde: 0x00F5,
  28641. otildeacute: 0x1E4D,
  28642. otildedieresis: 0x1E4F,
  28643. oubopomofo: 0x3121,
  28644. overline: 0x203E,
  28645. overlinecenterline: 0xFE4A,
  28646. overlinecmb: 0x0305,
  28647. overlinedashed: 0xFE49,
  28648. overlinedblwavy: 0xFE4C,
  28649. overlinewavy: 0xFE4B,
  28650. overscore: 0x00AF,
  28651. ovowelsignbengali: 0x09CB,
  28652. ovowelsigndeva: 0x094B,
  28653. ovowelsigngujarati: 0x0ACB,
  28654. p: 0x0070,
  28655. paampssquare: 0x3380,
  28656. paasentosquare: 0x332B,
  28657. pabengali: 0x09AA,
  28658. pacute: 0x1E55,
  28659. padeva: 0x092A,
  28660. pagedown: 0x21DF,
  28661. pageup: 0x21DE,
  28662. pagujarati: 0x0AAA,
  28663. pagurmukhi: 0x0A2A,
  28664. pahiragana: 0x3071,
  28665. paiyannoithai: 0x0E2F,
  28666. pakatakana: 0x30D1,
  28667. palatalizationcyrilliccmb: 0x0484,
  28668. palochkacyrillic: 0x04C0,
  28669. pansioskorean: 0x317F,
  28670. paragraph: 0x00B6,
  28671. parallel: 0x2225,
  28672. parenleft: 0x0028,
  28673. parenleftaltonearabic: 0xFD3E,
  28674. parenleftbt: 0xF8ED,
  28675. parenleftex: 0xF8EC,
  28676. parenleftinferior: 0x208D,
  28677. parenleftmonospace: 0xFF08,
  28678. parenleftsmall: 0xFE59,
  28679. parenleftsuperior: 0x207D,
  28680. parenlefttp: 0xF8EB,
  28681. parenleftvertical: 0xFE35,
  28682. parenright: 0x0029,
  28683. parenrightaltonearabic: 0xFD3F,
  28684. parenrightbt: 0xF8F8,
  28685. parenrightex: 0xF8F7,
  28686. parenrightinferior: 0x208E,
  28687. parenrightmonospace: 0xFF09,
  28688. parenrightsmall: 0xFE5A,
  28689. parenrightsuperior: 0x207E,
  28690. parenrighttp: 0xF8F6,
  28691. parenrightvertical: 0xFE36,
  28692. partialdiff: 0x2202,
  28693. paseqhebrew: 0x05C0,
  28694. pashtahebrew: 0x0599,
  28695. pasquare: 0x33A9,
  28696. patah: 0x05B7,
  28697. patah11: 0x05B7,
  28698. patah1d: 0x05B7,
  28699. patah2a: 0x05B7,
  28700. patahhebrew: 0x05B7,
  28701. patahnarrowhebrew: 0x05B7,
  28702. patahquarterhebrew: 0x05B7,
  28703. patahwidehebrew: 0x05B7,
  28704. pazerhebrew: 0x05A1,
  28705. pbopomofo: 0x3106,
  28706. pcircle: 0x24DF,
  28707. pdotaccent: 0x1E57,
  28708. pe: 0x05E4,
  28709. pecyrillic: 0x043F,
  28710. pedagesh: 0xFB44,
  28711. pedageshhebrew: 0xFB44,
  28712. peezisquare: 0x333B,
  28713. pefinaldageshhebrew: 0xFB43,
  28714. peharabic: 0x067E,
  28715. peharmenian: 0x057A,
  28716. pehebrew: 0x05E4,
  28717. pehfinalarabic: 0xFB57,
  28718. pehinitialarabic: 0xFB58,
  28719. pehiragana: 0x307A,
  28720. pehmedialarabic: 0xFB59,
  28721. pekatakana: 0x30DA,
  28722. pemiddlehookcyrillic: 0x04A7,
  28723. perafehebrew: 0xFB4E,
  28724. percent: 0x0025,
  28725. percentarabic: 0x066A,
  28726. percentmonospace: 0xFF05,
  28727. percentsmall: 0xFE6A,
  28728. period: 0x002E,
  28729. periodarmenian: 0x0589,
  28730. periodcentered: 0x00B7,
  28731. periodhalfwidth: 0xFF61,
  28732. periodinferior: 0xF6E7,
  28733. periodmonospace: 0xFF0E,
  28734. periodsmall: 0xFE52,
  28735. periodsuperior: 0xF6E8,
  28736. perispomenigreekcmb: 0x0342,
  28737. perpendicular: 0x22A5,
  28738. perthousand: 0x2030,
  28739. peseta: 0x20A7,
  28740. pfsquare: 0x338A,
  28741. phabengali: 0x09AB,
  28742. phadeva: 0x092B,
  28743. phagujarati: 0x0AAB,
  28744. phagurmukhi: 0x0A2B,
  28745. phi: 0x03C6,
  28746. phi1: 0x03D5,
  28747. phieuphacirclekorean: 0x327A,
  28748. phieuphaparenkorean: 0x321A,
  28749. phieuphcirclekorean: 0x326C,
  28750. phieuphkorean: 0x314D,
  28751. phieuphparenkorean: 0x320C,
  28752. philatin: 0x0278,
  28753. phinthuthai: 0x0E3A,
  28754. phisymbolgreek: 0x03D5,
  28755. phook: 0x01A5,
  28756. phophanthai: 0x0E1E,
  28757. phophungthai: 0x0E1C,
  28758. phosamphaothai: 0x0E20,
  28759. pi: 0x03C0,
  28760. pieupacirclekorean: 0x3273,
  28761. pieupaparenkorean: 0x3213,
  28762. pieupcieuckorean: 0x3176,
  28763. pieupcirclekorean: 0x3265,
  28764. pieupkiyeokkorean: 0x3172,
  28765. pieupkorean: 0x3142,
  28766. pieupparenkorean: 0x3205,
  28767. pieupsioskiyeokkorean: 0x3174,
  28768. pieupsioskorean: 0x3144,
  28769. pieupsiostikeutkorean: 0x3175,
  28770. pieupthieuthkorean: 0x3177,
  28771. pieuptikeutkorean: 0x3173,
  28772. pihiragana: 0x3074,
  28773. pikatakana: 0x30D4,
  28774. pisymbolgreek: 0x03D6,
  28775. piwrarmenian: 0x0583,
  28776. plus: 0x002B,
  28777. plusbelowcmb: 0x031F,
  28778. pluscircle: 0x2295,
  28779. plusminus: 0x00B1,
  28780. plusmod: 0x02D6,
  28781. plusmonospace: 0xFF0B,
  28782. plussmall: 0xFE62,
  28783. plussuperior: 0x207A,
  28784. pmonospace: 0xFF50,
  28785. pmsquare: 0x33D8,
  28786. pohiragana: 0x307D,
  28787. pointingindexdownwhite: 0x261F,
  28788. pointingindexleftwhite: 0x261C,
  28789. pointingindexrightwhite: 0x261E,
  28790. pointingindexupwhite: 0x261D,
  28791. pokatakana: 0x30DD,
  28792. poplathai: 0x0E1B,
  28793. postalmark: 0x3012,
  28794. postalmarkface: 0x3020,
  28795. pparen: 0x24AB,
  28796. precedes: 0x227A,
  28797. prescription: 0x211E,
  28798. primemod: 0x02B9,
  28799. primereversed: 0x2035,
  28800. product: 0x220F,
  28801. projective: 0x2305,
  28802. prolongedkana: 0x30FC,
  28803. propellor: 0x2318,
  28804. propersubset: 0x2282,
  28805. propersuperset: 0x2283,
  28806. proportion: 0x2237,
  28807. proportional: 0x221D,
  28808. psi: 0x03C8,
  28809. psicyrillic: 0x0471,
  28810. psilipneumatacyrilliccmb: 0x0486,
  28811. pssquare: 0x33B0,
  28812. puhiragana: 0x3077,
  28813. pukatakana: 0x30D7,
  28814. pvsquare: 0x33B4,
  28815. pwsquare: 0x33BA,
  28816. q: 0x0071,
  28817. qadeva: 0x0958,
  28818. qadmahebrew: 0x05A8,
  28819. qafarabic: 0x0642,
  28820. qaffinalarabic: 0xFED6,
  28821. qafinitialarabic: 0xFED7,
  28822. qafmedialarabic: 0xFED8,
  28823. qamats: 0x05B8,
  28824. qamats10: 0x05B8,
  28825. qamats1a: 0x05B8,
  28826. qamats1c: 0x05B8,
  28827. qamats27: 0x05B8,
  28828. qamats29: 0x05B8,
  28829. qamats33: 0x05B8,
  28830. qamatsde: 0x05B8,
  28831. qamatshebrew: 0x05B8,
  28832. qamatsnarrowhebrew: 0x05B8,
  28833. qamatsqatanhebrew: 0x05B8,
  28834. qamatsqatannarrowhebrew: 0x05B8,
  28835. qamatsqatanquarterhebrew: 0x05B8,
  28836. qamatsqatanwidehebrew: 0x05B8,
  28837. qamatsquarterhebrew: 0x05B8,
  28838. qamatswidehebrew: 0x05B8,
  28839. qarneyparahebrew: 0x059F,
  28840. qbopomofo: 0x3111,
  28841. qcircle: 0x24E0,
  28842. qhook: 0x02A0,
  28843. qmonospace: 0xFF51,
  28844. qof: 0x05E7,
  28845. qofdagesh: 0xFB47,
  28846. qofdageshhebrew: 0xFB47,
  28847. qofhebrew: 0x05E7,
  28848. qparen: 0x24AC,
  28849. quarternote: 0x2669,
  28850. qubuts: 0x05BB,
  28851. qubuts18: 0x05BB,
  28852. qubuts25: 0x05BB,
  28853. qubuts31: 0x05BB,
  28854. qubutshebrew: 0x05BB,
  28855. qubutsnarrowhebrew: 0x05BB,
  28856. qubutsquarterhebrew: 0x05BB,
  28857. qubutswidehebrew: 0x05BB,
  28858. question: 0x003F,
  28859. questionarabic: 0x061F,
  28860. questionarmenian: 0x055E,
  28861. questiondown: 0x00BF,
  28862. questiondownsmall: 0xF7BF,
  28863. questiongreek: 0x037E,
  28864. questionmonospace: 0xFF1F,
  28865. questionsmall: 0xF73F,
  28866. quotedbl: 0x0022,
  28867. quotedblbase: 0x201E,
  28868. quotedblleft: 0x201C,
  28869. quotedblmonospace: 0xFF02,
  28870. quotedblprime: 0x301E,
  28871. quotedblprimereversed: 0x301D,
  28872. quotedblright: 0x201D,
  28873. quoteleft: 0x2018,
  28874. quoteleftreversed: 0x201B,
  28875. quotereversed: 0x201B,
  28876. quoteright: 0x2019,
  28877. quoterightn: 0x0149,
  28878. quotesinglbase: 0x201A,
  28879. quotesingle: 0x0027,
  28880. quotesinglemonospace: 0xFF07,
  28881. r: 0x0072,
  28882. raarmenian: 0x057C,
  28883. rabengali: 0x09B0,
  28884. racute: 0x0155,
  28885. radeva: 0x0930,
  28886. radical: 0x221A,
  28887. radicalex: 0xF8E5,
  28888. radoverssquare: 0x33AE,
  28889. radoverssquaredsquare: 0x33AF,
  28890. radsquare: 0x33AD,
  28891. rafe: 0x05BF,
  28892. rafehebrew: 0x05BF,
  28893. ragujarati: 0x0AB0,
  28894. ragurmukhi: 0x0A30,
  28895. rahiragana: 0x3089,
  28896. rakatakana: 0x30E9,
  28897. rakatakanahalfwidth: 0xFF97,
  28898. ralowerdiagonalbengali: 0x09F1,
  28899. ramiddlediagonalbengali: 0x09F0,
  28900. ramshorn: 0x0264,
  28901. ratio: 0x2236,
  28902. rbopomofo: 0x3116,
  28903. rcaron: 0x0159,
  28904. rcedilla: 0x0157,
  28905. rcircle: 0x24E1,
  28906. rcommaaccent: 0x0157,
  28907. rdblgrave: 0x0211,
  28908. rdotaccent: 0x1E59,
  28909. rdotbelow: 0x1E5B,
  28910. rdotbelowmacron: 0x1E5D,
  28911. referencemark: 0x203B,
  28912. reflexsubset: 0x2286,
  28913. reflexsuperset: 0x2287,
  28914. registered: 0x00AE,
  28915. registersans: 0xF8E8,
  28916. registerserif: 0xF6DA,
  28917. reharabic: 0x0631,
  28918. reharmenian: 0x0580,
  28919. rehfinalarabic: 0xFEAE,
  28920. rehiragana: 0x308C,
  28921. rekatakana: 0x30EC,
  28922. rekatakanahalfwidth: 0xFF9A,
  28923. resh: 0x05E8,
  28924. reshdageshhebrew: 0xFB48,
  28925. reshhebrew: 0x05E8,
  28926. reversedtilde: 0x223D,
  28927. reviahebrew: 0x0597,
  28928. reviamugrashhebrew: 0x0597,
  28929. revlogicalnot: 0x2310,
  28930. rfishhook: 0x027E,
  28931. rfishhookreversed: 0x027F,
  28932. rhabengali: 0x09DD,
  28933. rhadeva: 0x095D,
  28934. rho: 0x03C1,
  28935. rhook: 0x027D,
  28936. rhookturned: 0x027B,
  28937. rhookturnedsuperior: 0x02B5,
  28938. rhosymbolgreek: 0x03F1,
  28939. rhotichookmod: 0x02DE,
  28940. rieulacirclekorean: 0x3271,
  28941. rieulaparenkorean: 0x3211,
  28942. rieulcirclekorean: 0x3263,
  28943. rieulhieuhkorean: 0x3140,
  28944. rieulkiyeokkorean: 0x313A,
  28945. rieulkiyeoksioskorean: 0x3169,
  28946. rieulkorean: 0x3139,
  28947. rieulmieumkorean: 0x313B,
  28948. rieulpansioskorean: 0x316C,
  28949. rieulparenkorean: 0x3203,
  28950. rieulphieuphkorean: 0x313F,
  28951. rieulpieupkorean: 0x313C,
  28952. rieulpieupsioskorean: 0x316B,
  28953. rieulsioskorean: 0x313D,
  28954. rieulthieuthkorean: 0x313E,
  28955. rieultikeutkorean: 0x316A,
  28956. rieulyeorinhieuhkorean: 0x316D,
  28957. rightangle: 0x221F,
  28958. righttackbelowcmb: 0x0319,
  28959. righttriangle: 0x22BF,
  28960. rihiragana: 0x308A,
  28961. rikatakana: 0x30EA,
  28962. rikatakanahalfwidth: 0xFF98,
  28963. ring: 0x02DA,
  28964. ringbelowcmb: 0x0325,
  28965. ringcmb: 0x030A,
  28966. ringhalfleft: 0x02BF,
  28967. ringhalfleftarmenian: 0x0559,
  28968. ringhalfleftbelowcmb: 0x031C,
  28969. ringhalfleftcentered: 0x02D3,
  28970. ringhalfright: 0x02BE,
  28971. ringhalfrightbelowcmb: 0x0339,
  28972. ringhalfrightcentered: 0x02D2,
  28973. rinvertedbreve: 0x0213,
  28974. rittorusquare: 0x3351,
  28975. rlinebelow: 0x1E5F,
  28976. rlongleg: 0x027C,
  28977. rlonglegturned: 0x027A,
  28978. rmonospace: 0xFF52,
  28979. rohiragana: 0x308D,
  28980. rokatakana: 0x30ED,
  28981. rokatakanahalfwidth: 0xFF9B,
  28982. roruathai: 0x0E23,
  28983. rparen: 0x24AD,
  28984. rrabengali: 0x09DC,
  28985. rradeva: 0x0931,
  28986. rragurmukhi: 0x0A5C,
  28987. rreharabic: 0x0691,
  28988. rrehfinalarabic: 0xFB8D,
  28989. rrvocalicbengali: 0x09E0,
  28990. rrvocalicdeva: 0x0960,
  28991. rrvocalicgujarati: 0x0AE0,
  28992. rrvocalicvowelsignbengali: 0x09C4,
  28993. rrvocalicvowelsigndeva: 0x0944,
  28994. rrvocalicvowelsigngujarati: 0x0AC4,
  28995. rsuperior: 0xF6F1,
  28996. rtblock: 0x2590,
  28997. rturned: 0x0279,
  28998. rturnedsuperior: 0x02B4,
  28999. ruhiragana: 0x308B,
  29000. rukatakana: 0x30EB,
  29001. rukatakanahalfwidth: 0xFF99,
  29002. rupeemarkbengali: 0x09F2,
  29003. rupeesignbengali: 0x09F3,
  29004. rupiah: 0xF6DD,
  29005. ruthai: 0x0E24,
  29006. rvocalicbengali: 0x098B,
  29007. rvocalicdeva: 0x090B,
  29008. rvocalicgujarati: 0x0A8B,
  29009. rvocalicvowelsignbengali: 0x09C3,
  29010. rvocalicvowelsigndeva: 0x0943,
  29011. rvocalicvowelsigngujarati: 0x0AC3,
  29012. s: 0x0073,
  29013. sabengali: 0x09B8,
  29014. sacute: 0x015B,
  29015. sacutedotaccent: 0x1E65,
  29016. sadarabic: 0x0635,
  29017. sadeva: 0x0938,
  29018. sadfinalarabic: 0xFEBA,
  29019. sadinitialarabic: 0xFEBB,
  29020. sadmedialarabic: 0xFEBC,
  29021. sagujarati: 0x0AB8,
  29022. sagurmukhi: 0x0A38,
  29023. sahiragana: 0x3055,
  29024. sakatakana: 0x30B5,
  29025. sakatakanahalfwidth: 0xFF7B,
  29026. sallallahoualayhewasallamarabic: 0xFDFA,
  29027. samekh: 0x05E1,
  29028. samekhdagesh: 0xFB41,
  29029. samekhdageshhebrew: 0xFB41,
  29030. samekhhebrew: 0x05E1,
  29031. saraaathai: 0x0E32,
  29032. saraaethai: 0x0E41,
  29033. saraaimaimalaithai: 0x0E44,
  29034. saraaimaimuanthai: 0x0E43,
  29035. saraamthai: 0x0E33,
  29036. saraathai: 0x0E30,
  29037. saraethai: 0x0E40,
  29038. saraiileftthai: 0xF886,
  29039. saraiithai: 0x0E35,
  29040. saraileftthai: 0xF885,
  29041. saraithai: 0x0E34,
  29042. saraothai: 0x0E42,
  29043. saraueeleftthai: 0xF888,
  29044. saraueethai: 0x0E37,
  29045. saraueleftthai: 0xF887,
  29046. sarauethai: 0x0E36,
  29047. sarauthai: 0x0E38,
  29048. sarauuthai: 0x0E39,
  29049. sbopomofo: 0x3119,
  29050. scaron: 0x0161,
  29051. scarondotaccent: 0x1E67,
  29052. scedilla: 0x015F,
  29053. schwa: 0x0259,
  29054. schwacyrillic: 0x04D9,
  29055. schwadieresiscyrillic: 0x04DB,
  29056. schwahook: 0x025A,
  29057. scircle: 0x24E2,
  29058. scircumflex: 0x015D,
  29059. scommaaccent: 0x0219,
  29060. sdotaccent: 0x1E61,
  29061. sdotbelow: 0x1E63,
  29062. sdotbelowdotaccent: 0x1E69,
  29063. seagullbelowcmb: 0x033C,
  29064. second: 0x2033,
  29065. secondtonechinese: 0x02CA,
  29066. section: 0x00A7,
  29067. seenarabic: 0x0633,
  29068. seenfinalarabic: 0xFEB2,
  29069. seeninitialarabic: 0xFEB3,
  29070. seenmedialarabic: 0xFEB4,
  29071. segol: 0x05B6,
  29072. segol13: 0x05B6,
  29073. segol1f: 0x05B6,
  29074. segol2c: 0x05B6,
  29075. segolhebrew: 0x05B6,
  29076. segolnarrowhebrew: 0x05B6,
  29077. segolquarterhebrew: 0x05B6,
  29078. segoltahebrew: 0x0592,
  29079. segolwidehebrew: 0x05B6,
  29080. seharmenian: 0x057D,
  29081. sehiragana: 0x305B,
  29082. sekatakana: 0x30BB,
  29083. sekatakanahalfwidth: 0xFF7E,
  29084. semicolon: 0x003B,
  29085. semicolonarabic: 0x061B,
  29086. semicolonmonospace: 0xFF1B,
  29087. semicolonsmall: 0xFE54,
  29088. semivoicedmarkkana: 0x309C,
  29089. semivoicedmarkkanahalfwidth: 0xFF9F,
  29090. sentisquare: 0x3322,
  29091. sentosquare: 0x3323,
  29092. seven: 0x0037,
  29093. sevenarabic: 0x0667,
  29094. sevenbengali: 0x09ED,
  29095. sevencircle: 0x2466,
  29096. sevencircleinversesansserif: 0x2790,
  29097. sevendeva: 0x096D,
  29098. seveneighths: 0x215E,
  29099. sevengujarati: 0x0AED,
  29100. sevengurmukhi: 0x0A6D,
  29101. sevenhackarabic: 0x0667,
  29102. sevenhangzhou: 0x3027,
  29103. sevenideographicparen: 0x3226,
  29104. seveninferior: 0x2087,
  29105. sevenmonospace: 0xFF17,
  29106. sevenoldstyle: 0xF737,
  29107. sevenparen: 0x247A,
  29108. sevenperiod: 0x248E,
  29109. sevenpersian: 0x06F7,
  29110. sevenroman: 0x2176,
  29111. sevensuperior: 0x2077,
  29112. seventeencircle: 0x2470,
  29113. seventeenparen: 0x2484,
  29114. seventeenperiod: 0x2498,
  29115. seventhai: 0x0E57,
  29116. sfthyphen: 0x00AD,
  29117. shaarmenian: 0x0577,
  29118. shabengali: 0x09B6,
  29119. shacyrillic: 0x0448,
  29120. shaddaarabic: 0x0651,
  29121. shaddadammaarabic: 0xFC61,
  29122. shaddadammatanarabic: 0xFC5E,
  29123. shaddafathaarabic: 0xFC60,
  29124. shaddakasraarabic: 0xFC62,
  29125. shaddakasratanarabic: 0xFC5F,
  29126. shade: 0x2592,
  29127. shadedark: 0x2593,
  29128. shadelight: 0x2591,
  29129. shademedium: 0x2592,
  29130. shadeva: 0x0936,
  29131. shagujarati: 0x0AB6,
  29132. shagurmukhi: 0x0A36,
  29133. shalshelethebrew: 0x0593,
  29134. shbopomofo: 0x3115,
  29135. shchacyrillic: 0x0449,
  29136. sheenarabic: 0x0634,
  29137. sheenfinalarabic: 0xFEB6,
  29138. sheeninitialarabic: 0xFEB7,
  29139. sheenmedialarabic: 0xFEB8,
  29140. sheicoptic: 0x03E3,
  29141. sheqel: 0x20AA,
  29142. sheqelhebrew: 0x20AA,
  29143. sheva: 0x05B0,
  29144. sheva115: 0x05B0,
  29145. sheva15: 0x05B0,
  29146. sheva22: 0x05B0,
  29147. sheva2e: 0x05B0,
  29148. shevahebrew: 0x05B0,
  29149. shevanarrowhebrew: 0x05B0,
  29150. shevaquarterhebrew: 0x05B0,
  29151. shevawidehebrew: 0x05B0,
  29152. shhacyrillic: 0x04BB,
  29153. shimacoptic: 0x03ED,
  29154. shin: 0x05E9,
  29155. shindagesh: 0xFB49,
  29156. shindageshhebrew: 0xFB49,
  29157. shindageshshindot: 0xFB2C,
  29158. shindageshshindothebrew: 0xFB2C,
  29159. shindageshsindot: 0xFB2D,
  29160. shindageshsindothebrew: 0xFB2D,
  29161. shindothebrew: 0x05C1,
  29162. shinhebrew: 0x05E9,
  29163. shinshindot: 0xFB2A,
  29164. shinshindothebrew: 0xFB2A,
  29165. shinsindot: 0xFB2B,
  29166. shinsindothebrew: 0xFB2B,
  29167. shook: 0x0282,
  29168. sigma: 0x03C3,
  29169. sigma1: 0x03C2,
  29170. sigmafinal: 0x03C2,
  29171. sigmalunatesymbolgreek: 0x03F2,
  29172. sihiragana: 0x3057,
  29173. sikatakana: 0x30B7,
  29174. sikatakanahalfwidth: 0xFF7C,
  29175. siluqhebrew: 0x05BD,
  29176. siluqlefthebrew: 0x05BD,
  29177. similar: 0x223C,
  29178. sindothebrew: 0x05C2,
  29179. siosacirclekorean: 0x3274,
  29180. siosaparenkorean: 0x3214,
  29181. sioscieuckorean: 0x317E,
  29182. sioscirclekorean: 0x3266,
  29183. sioskiyeokkorean: 0x317A,
  29184. sioskorean: 0x3145,
  29185. siosnieunkorean: 0x317B,
  29186. siosparenkorean: 0x3206,
  29187. siospieupkorean: 0x317D,
  29188. siostikeutkorean: 0x317C,
  29189. six: 0x0036,
  29190. sixarabic: 0x0666,
  29191. sixbengali: 0x09EC,
  29192. sixcircle: 0x2465,
  29193. sixcircleinversesansserif: 0x278F,
  29194. sixdeva: 0x096C,
  29195. sixgujarati: 0x0AEC,
  29196. sixgurmukhi: 0x0A6C,
  29197. sixhackarabic: 0x0666,
  29198. sixhangzhou: 0x3026,
  29199. sixideographicparen: 0x3225,
  29200. sixinferior: 0x2086,
  29201. sixmonospace: 0xFF16,
  29202. sixoldstyle: 0xF736,
  29203. sixparen: 0x2479,
  29204. sixperiod: 0x248D,
  29205. sixpersian: 0x06F6,
  29206. sixroman: 0x2175,
  29207. sixsuperior: 0x2076,
  29208. sixteencircle: 0x246F,
  29209. sixteencurrencydenominatorbengali: 0x09F9,
  29210. sixteenparen: 0x2483,
  29211. sixteenperiod: 0x2497,
  29212. sixthai: 0x0E56,
  29213. slash: 0x002F,
  29214. slashmonospace: 0xFF0F,
  29215. slong: 0x017F,
  29216. slongdotaccent: 0x1E9B,
  29217. smileface: 0x263A,
  29218. smonospace: 0xFF53,
  29219. sofpasuqhebrew: 0x05C3,
  29220. softhyphen: 0x00AD,
  29221. softsigncyrillic: 0x044C,
  29222. sohiragana: 0x305D,
  29223. sokatakana: 0x30BD,
  29224. sokatakanahalfwidth: 0xFF7F,
  29225. soliduslongoverlaycmb: 0x0338,
  29226. solidusshortoverlaycmb: 0x0337,
  29227. sorusithai: 0x0E29,
  29228. sosalathai: 0x0E28,
  29229. sosothai: 0x0E0B,
  29230. sosuathai: 0x0E2A,
  29231. space: 0x0020,
  29232. spacehackarabic: 0x0020,
  29233. spade: 0x2660,
  29234. spadesuitblack: 0x2660,
  29235. spadesuitwhite: 0x2664,
  29236. sparen: 0x24AE,
  29237. squarebelowcmb: 0x033B,
  29238. squarecc: 0x33C4,
  29239. squarecm: 0x339D,
  29240. squarediagonalcrosshatchfill: 0x25A9,
  29241. squarehorizontalfill: 0x25A4,
  29242. squarekg: 0x338F,
  29243. squarekm: 0x339E,
  29244. squarekmcapital: 0x33CE,
  29245. squareln: 0x33D1,
  29246. squarelog: 0x33D2,
  29247. squaremg: 0x338E,
  29248. squaremil: 0x33D5,
  29249. squaremm: 0x339C,
  29250. squaremsquared: 0x33A1,
  29251. squareorthogonalcrosshatchfill: 0x25A6,
  29252. squareupperlefttolowerrightfill: 0x25A7,
  29253. squareupperrighttolowerleftfill: 0x25A8,
  29254. squareverticalfill: 0x25A5,
  29255. squarewhitewithsmallblack: 0x25A3,
  29256. srsquare: 0x33DB,
  29257. ssabengali: 0x09B7,
  29258. ssadeva: 0x0937,
  29259. ssagujarati: 0x0AB7,
  29260. ssangcieuckorean: 0x3149,
  29261. ssanghieuhkorean: 0x3185,
  29262. ssangieungkorean: 0x3180,
  29263. ssangkiyeokkorean: 0x3132,
  29264. ssangnieunkorean: 0x3165,
  29265. ssangpieupkorean: 0x3143,
  29266. ssangsioskorean: 0x3146,
  29267. ssangtikeutkorean: 0x3138,
  29268. ssuperior: 0xF6F2,
  29269. sterling: 0x00A3,
  29270. sterlingmonospace: 0xFFE1,
  29271. strokelongoverlaycmb: 0x0336,
  29272. strokeshortoverlaycmb: 0x0335,
  29273. subset: 0x2282,
  29274. subsetnotequal: 0x228A,
  29275. subsetorequal: 0x2286,
  29276. succeeds: 0x227B,
  29277. suchthat: 0x220B,
  29278. suhiragana: 0x3059,
  29279. sukatakana: 0x30B9,
  29280. sukatakanahalfwidth: 0xFF7D,
  29281. sukunarabic: 0x0652,
  29282. summation: 0x2211,
  29283. sun: 0x263C,
  29284. superset: 0x2283,
  29285. supersetnotequal: 0x228B,
  29286. supersetorequal: 0x2287,
  29287. svsquare: 0x33DC,
  29288. syouwaerasquare: 0x337C,
  29289. t: 0x0074,
  29290. tabengali: 0x09A4,
  29291. tackdown: 0x22A4,
  29292. tackleft: 0x22A3,
  29293. tadeva: 0x0924,
  29294. tagujarati: 0x0AA4,
  29295. tagurmukhi: 0x0A24,
  29296. taharabic: 0x0637,
  29297. tahfinalarabic: 0xFEC2,
  29298. tahinitialarabic: 0xFEC3,
  29299. tahiragana: 0x305F,
  29300. tahmedialarabic: 0xFEC4,
  29301. taisyouerasquare: 0x337D,
  29302. takatakana: 0x30BF,
  29303. takatakanahalfwidth: 0xFF80,
  29304. tatweelarabic: 0x0640,
  29305. tau: 0x03C4,
  29306. tav: 0x05EA,
  29307. tavdages: 0xFB4A,
  29308. tavdagesh: 0xFB4A,
  29309. tavdageshhebrew: 0xFB4A,
  29310. tavhebrew: 0x05EA,
  29311. tbar: 0x0167,
  29312. tbopomofo: 0x310A,
  29313. tcaron: 0x0165,
  29314. tccurl: 0x02A8,
  29315. tcedilla: 0x0163,
  29316. tcheharabic: 0x0686,
  29317. tchehfinalarabic: 0xFB7B,
  29318. tchehinitialarabic: 0xFB7C,
  29319. tchehmedialarabic: 0xFB7D,
  29320. tcircle: 0x24E3,
  29321. tcircumflexbelow: 0x1E71,
  29322. tcommaaccent: 0x0163,
  29323. tdieresis: 0x1E97,
  29324. tdotaccent: 0x1E6B,
  29325. tdotbelow: 0x1E6D,
  29326. tecyrillic: 0x0442,
  29327. tedescendercyrillic: 0x04AD,
  29328. teharabic: 0x062A,
  29329. tehfinalarabic: 0xFE96,
  29330. tehhahinitialarabic: 0xFCA2,
  29331. tehhahisolatedarabic: 0xFC0C,
  29332. tehinitialarabic: 0xFE97,
  29333. tehiragana: 0x3066,
  29334. tehjeeminitialarabic: 0xFCA1,
  29335. tehjeemisolatedarabic: 0xFC0B,
  29336. tehmarbutaarabic: 0x0629,
  29337. tehmarbutafinalarabic: 0xFE94,
  29338. tehmedialarabic: 0xFE98,
  29339. tehmeeminitialarabic: 0xFCA4,
  29340. tehmeemisolatedarabic: 0xFC0E,
  29341. tehnoonfinalarabic: 0xFC73,
  29342. tekatakana: 0x30C6,
  29343. tekatakanahalfwidth: 0xFF83,
  29344. telephone: 0x2121,
  29345. telephoneblack: 0x260E,
  29346. telishagedolahebrew: 0x05A0,
  29347. telishaqetanahebrew: 0x05A9,
  29348. tencircle: 0x2469,
  29349. tenideographicparen: 0x3229,
  29350. tenparen: 0x247D,
  29351. tenperiod: 0x2491,
  29352. tenroman: 0x2179,
  29353. tesh: 0x02A7,
  29354. tet: 0x05D8,
  29355. tetdagesh: 0xFB38,
  29356. tetdageshhebrew: 0xFB38,
  29357. tethebrew: 0x05D8,
  29358. tetsecyrillic: 0x04B5,
  29359. tevirhebrew: 0x059B,
  29360. tevirlefthebrew: 0x059B,
  29361. thabengali: 0x09A5,
  29362. thadeva: 0x0925,
  29363. thagujarati: 0x0AA5,
  29364. thagurmukhi: 0x0A25,
  29365. thalarabic: 0x0630,
  29366. thalfinalarabic: 0xFEAC,
  29367. thanthakhatlowleftthai: 0xF898,
  29368. thanthakhatlowrightthai: 0xF897,
  29369. thanthakhatthai: 0x0E4C,
  29370. thanthakhatupperleftthai: 0xF896,
  29371. theharabic: 0x062B,
  29372. thehfinalarabic: 0xFE9A,
  29373. thehinitialarabic: 0xFE9B,
  29374. thehmedialarabic: 0xFE9C,
  29375. thereexists: 0x2203,
  29376. therefore: 0x2234,
  29377. theta: 0x03B8,
  29378. theta1: 0x03D1,
  29379. thetasymbolgreek: 0x03D1,
  29380. thieuthacirclekorean: 0x3279,
  29381. thieuthaparenkorean: 0x3219,
  29382. thieuthcirclekorean: 0x326B,
  29383. thieuthkorean: 0x314C,
  29384. thieuthparenkorean: 0x320B,
  29385. thirteencircle: 0x246C,
  29386. thirteenparen: 0x2480,
  29387. thirteenperiod: 0x2494,
  29388. thonangmonthothai: 0x0E11,
  29389. thook: 0x01AD,
  29390. thophuthaothai: 0x0E12,
  29391. thorn: 0x00FE,
  29392. thothahanthai: 0x0E17,
  29393. thothanthai: 0x0E10,
  29394. thothongthai: 0x0E18,
  29395. thothungthai: 0x0E16,
  29396. thousandcyrillic: 0x0482,
  29397. thousandsseparatorarabic: 0x066C,
  29398. thousandsseparatorpersian: 0x066C,
  29399. three: 0x0033,
  29400. threearabic: 0x0663,
  29401. threebengali: 0x09E9,
  29402. threecircle: 0x2462,
  29403. threecircleinversesansserif: 0x278C,
  29404. threedeva: 0x0969,
  29405. threeeighths: 0x215C,
  29406. threegujarati: 0x0AE9,
  29407. threegurmukhi: 0x0A69,
  29408. threehackarabic: 0x0663,
  29409. threehangzhou: 0x3023,
  29410. threeideographicparen: 0x3222,
  29411. threeinferior: 0x2083,
  29412. threemonospace: 0xFF13,
  29413. threenumeratorbengali: 0x09F6,
  29414. threeoldstyle: 0xF733,
  29415. threeparen: 0x2476,
  29416. threeperiod: 0x248A,
  29417. threepersian: 0x06F3,
  29418. threequarters: 0x00BE,
  29419. threequartersemdash: 0xF6DE,
  29420. threeroman: 0x2172,
  29421. threesuperior: 0x00B3,
  29422. threethai: 0x0E53,
  29423. thzsquare: 0x3394,
  29424. tihiragana: 0x3061,
  29425. tikatakana: 0x30C1,
  29426. tikatakanahalfwidth: 0xFF81,
  29427. tikeutacirclekorean: 0x3270,
  29428. tikeutaparenkorean: 0x3210,
  29429. tikeutcirclekorean: 0x3262,
  29430. tikeutkorean: 0x3137,
  29431. tikeutparenkorean: 0x3202,
  29432. tilde: 0x02DC,
  29433. tildebelowcmb: 0x0330,
  29434. tildecmb: 0x0303,
  29435. tildecomb: 0x0303,
  29436. tildedoublecmb: 0x0360,
  29437. tildeoperator: 0x223C,
  29438. tildeoverlaycmb: 0x0334,
  29439. tildeverticalcmb: 0x033E,
  29440. timescircle: 0x2297,
  29441. tipehahebrew: 0x0596,
  29442. tipehalefthebrew: 0x0596,
  29443. tippigurmukhi: 0x0A70,
  29444. titlocyrilliccmb: 0x0483,
  29445. tiwnarmenian: 0x057F,
  29446. tlinebelow: 0x1E6F,
  29447. tmonospace: 0xFF54,
  29448. toarmenian: 0x0569,
  29449. tohiragana: 0x3068,
  29450. tokatakana: 0x30C8,
  29451. tokatakanahalfwidth: 0xFF84,
  29452. tonebarextrahighmod: 0x02E5,
  29453. tonebarextralowmod: 0x02E9,
  29454. tonebarhighmod: 0x02E6,
  29455. tonebarlowmod: 0x02E8,
  29456. tonebarmidmod: 0x02E7,
  29457. tonefive: 0x01BD,
  29458. tonesix: 0x0185,
  29459. tonetwo: 0x01A8,
  29460. tonos: 0x0384,
  29461. tonsquare: 0x3327,
  29462. topatakthai: 0x0E0F,
  29463. tortoiseshellbracketleft: 0x3014,
  29464. tortoiseshellbracketleftsmall: 0xFE5D,
  29465. tortoiseshellbracketleftvertical: 0xFE39,
  29466. tortoiseshellbracketright: 0x3015,
  29467. tortoiseshellbracketrightsmall: 0xFE5E,
  29468. tortoiseshellbracketrightvertical: 0xFE3A,
  29469. totaothai: 0x0E15,
  29470. tpalatalhook: 0x01AB,
  29471. tparen: 0x24AF,
  29472. trademark: 0x2122,
  29473. trademarksans: 0xF8EA,
  29474. trademarkserif: 0xF6DB,
  29475. tretroflexhook: 0x0288,
  29476. triagdn: 0x25BC,
  29477. triaglf: 0x25C4,
  29478. triagrt: 0x25BA,
  29479. triagup: 0x25B2,
  29480. ts: 0x02A6,
  29481. tsadi: 0x05E6,
  29482. tsadidagesh: 0xFB46,
  29483. tsadidageshhebrew: 0xFB46,
  29484. tsadihebrew: 0x05E6,
  29485. tsecyrillic: 0x0446,
  29486. tsere: 0x05B5,
  29487. tsere12: 0x05B5,
  29488. tsere1e: 0x05B5,
  29489. tsere2b: 0x05B5,
  29490. tserehebrew: 0x05B5,
  29491. tserenarrowhebrew: 0x05B5,
  29492. tserequarterhebrew: 0x05B5,
  29493. tserewidehebrew: 0x05B5,
  29494. tshecyrillic: 0x045B,
  29495. tsuperior: 0xF6F3,
  29496. ttabengali: 0x099F,
  29497. ttadeva: 0x091F,
  29498. ttagujarati: 0x0A9F,
  29499. ttagurmukhi: 0x0A1F,
  29500. tteharabic: 0x0679,
  29501. ttehfinalarabic: 0xFB67,
  29502. ttehinitialarabic: 0xFB68,
  29503. ttehmedialarabic: 0xFB69,
  29504. tthabengali: 0x09A0,
  29505. tthadeva: 0x0920,
  29506. tthagujarati: 0x0AA0,
  29507. tthagurmukhi: 0x0A20,
  29508. tturned: 0x0287,
  29509. tuhiragana: 0x3064,
  29510. tukatakana: 0x30C4,
  29511. tukatakanahalfwidth: 0xFF82,
  29512. tusmallhiragana: 0x3063,
  29513. tusmallkatakana: 0x30C3,
  29514. tusmallkatakanahalfwidth: 0xFF6F,
  29515. twelvecircle: 0x246B,
  29516. twelveparen: 0x247F,
  29517. twelveperiod: 0x2493,
  29518. twelveroman: 0x217B,
  29519. twentycircle: 0x2473,
  29520. twentyhangzhou: 0x5344,
  29521. twentyparen: 0x2487,
  29522. twentyperiod: 0x249B,
  29523. two: 0x0032,
  29524. twoarabic: 0x0662,
  29525. twobengali: 0x09E8,
  29526. twocircle: 0x2461,
  29527. twocircleinversesansserif: 0x278B,
  29528. twodeva: 0x0968,
  29529. twodotenleader: 0x2025,
  29530. twodotleader: 0x2025,
  29531. twodotleadervertical: 0xFE30,
  29532. twogujarati: 0x0AE8,
  29533. twogurmukhi: 0x0A68,
  29534. twohackarabic: 0x0662,
  29535. twohangzhou: 0x3022,
  29536. twoideographicparen: 0x3221,
  29537. twoinferior: 0x2082,
  29538. twomonospace: 0xFF12,
  29539. twonumeratorbengali: 0x09F5,
  29540. twooldstyle: 0xF732,
  29541. twoparen: 0x2475,
  29542. twoperiod: 0x2489,
  29543. twopersian: 0x06F2,
  29544. tworoman: 0x2171,
  29545. twostroke: 0x01BB,
  29546. twosuperior: 0x00B2,
  29547. twothai: 0x0E52,
  29548. twothirds: 0x2154,
  29549. u: 0x0075,
  29550. uacute: 0x00FA,
  29551. ubar: 0x0289,
  29552. ubengali: 0x0989,
  29553. ubopomofo: 0x3128,
  29554. ubreve: 0x016D,
  29555. ucaron: 0x01D4,
  29556. ucircle: 0x24E4,
  29557. ucircumflex: 0x00FB,
  29558. ucircumflexbelow: 0x1E77,
  29559. ucyrillic: 0x0443,
  29560. udattadeva: 0x0951,
  29561. udblacute: 0x0171,
  29562. udblgrave: 0x0215,
  29563. udeva: 0x0909,
  29564. udieresis: 0x00FC,
  29565. udieresisacute: 0x01D8,
  29566. udieresisbelow: 0x1E73,
  29567. udieresiscaron: 0x01DA,
  29568. udieresiscyrillic: 0x04F1,
  29569. udieresisgrave: 0x01DC,
  29570. udieresismacron: 0x01D6,
  29571. udotbelow: 0x1EE5,
  29572. ugrave: 0x00F9,
  29573. ugujarati: 0x0A89,
  29574. ugurmukhi: 0x0A09,
  29575. uhiragana: 0x3046,
  29576. uhookabove: 0x1EE7,
  29577. uhorn: 0x01B0,
  29578. uhornacute: 0x1EE9,
  29579. uhorndotbelow: 0x1EF1,
  29580. uhorngrave: 0x1EEB,
  29581. uhornhookabove: 0x1EED,
  29582. uhorntilde: 0x1EEF,
  29583. uhungarumlaut: 0x0171,
  29584. uhungarumlautcyrillic: 0x04F3,
  29585. uinvertedbreve: 0x0217,
  29586. ukatakana: 0x30A6,
  29587. ukatakanahalfwidth: 0xFF73,
  29588. ukcyrillic: 0x0479,
  29589. ukorean: 0x315C,
  29590. umacron: 0x016B,
  29591. umacroncyrillic: 0x04EF,
  29592. umacrondieresis: 0x1E7B,
  29593. umatragurmukhi: 0x0A41,
  29594. umonospace: 0xFF55,
  29595. underscore: 0x005F,
  29596. underscoredbl: 0x2017,
  29597. underscoremonospace: 0xFF3F,
  29598. underscorevertical: 0xFE33,
  29599. underscorewavy: 0xFE4F,
  29600. union: 0x222A,
  29601. universal: 0x2200,
  29602. uogonek: 0x0173,
  29603. uparen: 0x24B0,
  29604. upblock: 0x2580,
  29605. upperdothebrew: 0x05C4,
  29606. upsilon: 0x03C5,
  29607. upsilondieresis: 0x03CB,
  29608. upsilondieresistonos: 0x03B0,
  29609. upsilonlatin: 0x028A,
  29610. upsilontonos: 0x03CD,
  29611. uptackbelowcmb: 0x031D,
  29612. uptackmod: 0x02D4,
  29613. uragurmukhi: 0x0A73,
  29614. uring: 0x016F,
  29615. ushortcyrillic: 0x045E,
  29616. usmallhiragana: 0x3045,
  29617. usmallkatakana: 0x30A5,
  29618. usmallkatakanahalfwidth: 0xFF69,
  29619. ustraightcyrillic: 0x04AF,
  29620. ustraightstrokecyrillic: 0x04B1,
  29621. utilde: 0x0169,
  29622. utildeacute: 0x1E79,
  29623. utildebelow: 0x1E75,
  29624. uubengali: 0x098A,
  29625. uudeva: 0x090A,
  29626. uugujarati: 0x0A8A,
  29627. uugurmukhi: 0x0A0A,
  29628. uumatragurmukhi: 0x0A42,
  29629. uuvowelsignbengali: 0x09C2,
  29630. uuvowelsigndeva: 0x0942,
  29631. uuvowelsigngujarati: 0x0AC2,
  29632. uvowelsignbengali: 0x09C1,
  29633. uvowelsigndeva: 0x0941,
  29634. uvowelsigngujarati: 0x0AC1,
  29635. v: 0x0076,
  29636. vadeva: 0x0935,
  29637. vagujarati: 0x0AB5,
  29638. vagurmukhi: 0x0A35,
  29639. vakatakana: 0x30F7,
  29640. vav: 0x05D5,
  29641. vavdagesh: 0xFB35,
  29642. vavdagesh65: 0xFB35,
  29643. vavdageshhebrew: 0xFB35,
  29644. vavhebrew: 0x05D5,
  29645. vavholam: 0xFB4B,
  29646. vavholamhebrew: 0xFB4B,
  29647. vavvavhebrew: 0x05F0,
  29648. vavyodhebrew: 0x05F1,
  29649. vcircle: 0x24E5,
  29650. vdotbelow: 0x1E7F,
  29651. vecyrillic: 0x0432,
  29652. veharabic: 0x06A4,
  29653. vehfinalarabic: 0xFB6B,
  29654. vehinitialarabic: 0xFB6C,
  29655. vehmedialarabic: 0xFB6D,
  29656. vekatakana: 0x30F9,
  29657. venus: 0x2640,
  29658. verticalbar: 0x007C,
  29659. verticallineabovecmb: 0x030D,
  29660. verticallinebelowcmb: 0x0329,
  29661. verticallinelowmod: 0x02CC,
  29662. verticallinemod: 0x02C8,
  29663. vewarmenian: 0x057E,
  29664. vhook: 0x028B,
  29665. vikatakana: 0x30F8,
  29666. viramabengali: 0x09CD,
  29667. viramadeva: 0x094D,
  29668. viramagujarati: 0x0ACD,
  29669. visargabengali: 0x0983,
  29670. visargadeva: 0x0903,
  29671. visargagujarati: 0x0A83,
  29672. vmonospace: 0xFF56,
  29673. voarmenian: 0x0578,
  29674. voicediterationhiragana: 0x309E,
  29675. voicediterationkatakana: 0x30FE,
  29676. voicedmarkkana: 0x309B,
  29677. voicedmarkkanahalfwidth: 0xFF9E,
  29678. vokatakana: 0x30FA,
  29679. vparen: 0x24B1,
  29680. vtilde: 0x1E7D,
  29681. vturned: 0x028C,
  29682. vuhiragana: 0x3094,
  29683. vukatakana: 0x30F4,
  29684. w: 0x0077,
  29685. wacute: 0x1E83,
  29686. waekorean: 0x3159,
  29687. wahiragana: 0x308F,
  29688. wakatakana: 0x30EF,
  29689. wakatakanahalfwidth: 0xFF9C,
  29690. wakorean: 0x3158,
  29691. wasmallhiragana: 0x308E,
  29692. wasmallkatakana: 0x30EE,
  29693. wattosquare: 0x3357,
  29694. wavedash: 0x301C,
  29695. wavyunderscorevertical: 0xFE34,
  29696. wawarabic: 0x0648,
  29697. wawfinalarabic: 0xFEEE,
  29698. wawhamzaabovearabic: 0x0624,
  29699. wawhamzaabovefinalarabic: 0xFE86,
  29700. wbsquare: 0x33DD,
  29701. wcircle: 0x24E6,
  29702. wcircumflex: 0x0175,
  29703. wdieresis: 0x1E85,
  29704. wdotaccent: 0x1E87,
  29705. wdotbelow: 0x1E89,
  29706. wehiragana: 0x3091,
  29707. weierstrass: 0x2118,
  29708. wekatakana: 0x30F1,
  29709. wekorean: 0x315E,
  29710. weokorean: 0x315D,
  29711. wgrave: 0x1E81,
  29712. whitebullet: 0x25E6,
  29713. whitecircle: 0x25CB,
  29714. whitecircleinverse: 0x25D9,
  29715. whitecornerbracketleft: 0x300E,
  29716. whitecornerbracketleftvertical: 0xFE43,
  29717. whitecornerbracketright: 0x300F,
  29718. whitecornerbracketrightvertical: 0xFE44,
  29719. whitediamond: 0x25C7,
  29720. whitediamondcontainingblacksmalldiamond: 0x25C8,
  29721. whitedownpointingsmalltriangle: 0x25BF,
  29722. whitedownpointingtriangle: 0x25BD,
  29723. whiteleftpointingsmalltriangle: 0x25C3,
  29724. whiteleftpointingtriangle: 0x25C1,
  29725. whitelenticularbracketleft: 0x3016,
  29726. whitelenticularbracketright: 0x3017,
  29727. whiterightpointingsmalltriangle: 0x25B9,
  29728. whiterightpointingtriangle: 0x25B7,
  29729. whitesmallsquare: 0x25AB,
  29730. whitesmilingface: 0x263A,
  29731. whitesquare: 0x25A1,
  29732. whitestar: 0x2606,
  29733. whitetelephone: 0x260F,
  29734. whitetortoiseshellbracketleft: 0x3018,
  29735. whitetortoiseshellbracketright: 0x3019,
  29736. whiteuppointingsmalltriangle: 0x25B5,
  29737. whiteuppointingtriangle: 0x25B3,
  29738. wihiragana: 0x3090,
  29739. wikatakana: 0x30F0,
  29740. wikorean: 0x315F,
  29741. wmonospace: 0xFF57,
  29742. wohiragana: 0x3092,
  29743. wokatakana: 0x30F2,
  29744. wokatakanahalfwidth: 0xFF66,
  29745. won: 0x20A9,
  29746. wonmonospace: 0xFFE6,
  29747. wowaenthai: 0x0E27,
  29748. wparen: 0x24B2,
  29749. wring: 0x1E98,
  29750. wsuperior: 0x02B7,
  29751. wturned: 0x028D,
  29752. wynn: 0x01BF,
  29753. x: 0x0078,
  29754. xabovecmb: 0x033D,
  29755. xbopomofo: 0x3112,
  29756. xcircle: 0x24E7,
  29757. xdieresis: 0x1E8D,
  29758. xdotaccent: 0x1E8B,
  29759. xeharmenian: 0x056D,
  29760. xi: 0x03BE,
  29761. xmonospace: 0xFF58,
  29762. xparen: 0x24B3,
  29763. xsuperior: 0x02E3,
  29764. y: 0x0079,
  29765. yaadosquare: 0x334E,
  29766. yabengali: 0x09AF,
  29767. yacute: 0x00FD,
  29768. yadeva: 0x092F,
  29769. yaekorean: 0x3152,
  29770. yagujarati: 0x0AAF,
  29771. yagurmukhi: 0x0A2F,
  29772. yahiragana: 0x3084,
  29773. yakatakana: 0x30E4,
  29774. yakatakanahalfwidth: 0xFF94,
  29775. yakorean: 0x3151,
  29776. yamakkanthai: 0x0E4E,
  29777. yasmallhiragana: 0x3083,
  29778. yasmallkatakana: 0x30E3,
  29779. yasmallkatakanahalfwidth: 0xFF6C,
  29780. yatcyrillic: 0x0463,
  29781. ycircle: 0x24E8,
  29782. ycircumflex: 0x0177,
  29783. ydieresis: 0x00FF,
  29784. ydotaccent: 0x1E8F,
  29785. ydotbelow: 0x1EF5,
  29786. yeharabic: 0x064A,
  29787. yehbarreearabic: 0x06D2,
  29788. yehbarreefinalarabic: 0xFBAF,
  29789. yehfinalarabic: 0xFEF2,
  29790. yehhamzaabovearabic: 0x0626,
  29791. yehhamzaabovefinalarabic: 0xFE8A,
  29792. yehhamzaaboveinitialarabic: 0xFE8B,
  29793. yehhamzaabovemedialarabic: 0xFE8C,
  29794. yehinitialarabic: 0xFEF3,
  29795. yehmedialarabic: 0xFEF4,
  29796. yehmeeminitialarabic: 0xFCDD,
  29797. yehmeemisolatedarabic: 0xFC58,
  29798. yehnoonfinalarabic: 0xFC94,
  29799. yehthreedotsbelowarabic: 0x06D1,
  29800. yekorean: 0x3156,
  29801. yen: 0x00A5,
  29802. yenmonospace: 0xFFE5,
  29803. yeokorean: 0x3155,
  29804. yeorinhieuhkorean: 0x3186,
  29805. yerahbenyomohebrew: 0x05AA,
  29806. yerahbenyomolefthebrew: 0x05AA,
  29807. yericyrillic: 0x044B,
  29808. yerudieresiscyrillic: 0x04F9,
  29809. yesieungkorean: 0x3181,
  29810. yesieungpansioskorean: 0x3183,
  29811. yesieungsioskorean: 0x3182,
  29812. yetivhebrew: 0x059A,
  29813. ygrave: 0x1EF3,
  29814. yhook: 0x01B4,
  29815. yhookabove: 0x1EF7,
  29816. yiarmenian: 0x0575,
  29817. yicyrillic: 0x0457,
  29818. yikorean: 0x3162,
  29819. yinyang: 0x262F,
  29820. yiwnarmenian: 0x0582,
  29821. ymonospace: 0xFF59,
  29822. yod: 0x05D9,
  29823. yoddagesh: 0xFB39,
  29824. yoddageshhebrew: 0xFB39,
  29825. yodhebrew: 0x05D9,
  29826. yodyodhebrew: 0x05F2,
  29827. yodyodpatahhebrew: 0xFB1F,
  29828. yohiragana: 0x3088,
  29829. yoikorean: 0x3189,
  29830. yokatakana: 0x30E8,
  29831. yokatakanahalfwidth: 0xFF96,
  29832. yokorean: 0x315B,
  29833. yosmallhiragana: 0x3087,
  29834. yosmallkatakana: 0x30E7,
  29835. yosmallkatakanahalfwidth: 0xFF6E,
  29836. yotgreek: 0x03F3,
  29837. yoyaekorean: 0x3188,
  29838. yoyakorean: 0x3187,
  29839. yoyakthai: 0x0E22,
  29840. yoyingthai: 0x0E0D,
  29841. yparen: 0x24B4,
  29842. ypogegrammeni: 0x037A,
  29843. ypogegrammenigreekcmb: 0x0345,
  29844. yr: 0x01A6,
  29845. yring: 0x1E99,
  29846. ysuperior: 0x02B8,
  29847. ytilde: 0x1EF9,
  29848. yturned: 0x028E,
  29849. yuhiragana: 0x3086,
  29850. yuikorean: 0x318C,
  29851. yukatakana: 0x30E6,
  29852. yukatakanahalfwidth: 0xFF95,
  29853. yukorean: 0x3160,
  29854. yusbigcyrillic: 0x046B,
  29855. yusbigiotifiedcyrillic: 0x046D,
  29856. yuslittlecyrillic: 0x0467,
  29857. yuslittleiotifiedcyrillic: 0x0469,
  29858. yusmallhiragana: 0x3085,
  29859. yusmallkatakana: 0x30E5,
  29860. yusmallkatakanahalfwidth: 0xFF6D,
  29861. yuyekorean: 0x318B,
  29862. yuyeokorean: 0x318A,
  29863. yyabengali: 0x09DF,
  29864. yyadeva: 0x095F,
  29865. z: 0x007A,
  29866. zaarmenian: 0x0566,
  29867. zacute: 0x017A,
  29868. zadeva: 0x095B,
  29869. zagurmukhi: 0x0A5B,
  29870. zaharabic: 0x0638,
  29871. zahfinalarabic: 0xFEC6,
  29872. zahinitialarabic: 0xFEC7,
  29873. zahiragana: 0x3056,
  29874. zahmedialarabic: 0xFEC8,
  29875. zainarabic: 0x0632,
  29876. zainfinalarabic: 0xFEB0,
  29877. zakatakana: 0x30B6,
  29878. zaqefgadolhebrew: 0x0595,
  29879. zaqefqatanhebrew: 0x0594,
  29880. zarqahebrew: 0x0598,
  29881. zayin: 0x05D6,
  29882. zayindagesh: 0xFB36,
  29883. zayindageshhebrew: 0xFB36,
  29884. zayinhebrew: 0x05D6,
  29885. zbopomofo: 0x3117,
  29886. zcaron: 0x017E,
  29887. zcircle: 0x24E9,
  29888. zcircumflex: 0x1E91,
  29889. zcurl: 0x0291,
  29890. zdot: 0x017C,
  29891. zdotaccent: 0x017C,
  29892. zdotbelow: 0x1E93,
  29893. zecyrillic: 0x0437,
  29894. zedescendercyrillic: 0x0499,
  29895. zedieresiscyrillic: 0x04DF,
  29896. zehiragana: 0x305C,
  29897. zekatakana: 0x30BC,
  29898. zero: 0x0030,
  29899. zeroarabic: 0x0660,
  29900. zerobengali: 0x09E6,
  29901. zerodeva: 0x0966,
  29902. zerogujarati: 0x0AE6,
  29903. zerogurmukhi: 0x0A66,
  29904. zerohackarabic: 0x0660,
  29905. zeroinferior: 0x2080,
  29906. zeromonospace: 0xFF10,
  29907. zerooldstyle: 0xF730,
  29908. zeropersian: 0x06F0,
  29909. zerosuperior: 0x2070,
  29910. zerothai: 0x0E50,
  29911. zerowidthjoiner: 0xFEFF,
  29912. zerowidthnonjoiner: 0x200C,
  29913. zerowidthspace: 0x200B,
  29914. zeta: 0x03B6,
  29915. zhbopomofo: 0x3113,
  29916. zhearmenian: 0x056A,
  29917. zhebrevecyrillic: 0x04C2,
  29918. zhecyrillic: 0x0436,
  29919. zhedescendercyrillic: 0x0497,
  29920. zhedieresiscyrillic: 0x04DD,
  29921. zihiragana: 0x3058,
  29922. zikatakana: 0x30B8,
  29923. zinorhebrew: 0x05AE,
  29924. zlinebelow: 0x1E95,
  29925. zmonospace: 0xFF5A,
  29926. zohiragana: 0x305E,
  29927. zokatakana: 0x30BE,
  29928. zparen: 0x24B5,
  29929. zretroflexhook: 0x0290,
  29930. zstroke: 0x01B6,
  29931. zuhiragana: 0x305A,
  29932. zukatakana: 0x30BA,
  29933. '.notdef': 0x0000
  29934. };
  29935. var DingbatsGlyphsUnicode = {
  29936. space: 0x0020,
  29937. a1: 0x2701,
  29938. a2: 0x2702,
  29939. a202: 0x2703,
  29940. a3: 0x2704,
  29941. a4: 0x260E,
  29942. a5: 0x2706,
  29943. a119: 0x2707,
  29944. a118: 0x2708,
  29945. a117: 0x2709,
  29946. a11: 0x261B,
  29947. a12: 0x261E,
  29948. a13: 0x270C,
  29949. a14: 0x270D,
  29950. a15: 0x270E,
  29951. a16: 0x270F,
  29952. a105: 0x2710,
  29953. a17: 0x2711,
  29954. a18: 0x2712,
  29955. a19: 0x2713,
  29956. a20: 0x2714,
  29957. a21: 0x2715,
  29958. a22: 0x2716,
  29959. a23: 0x2717,
  29960. a24: 0x2718,
  29961. a25: 0x2719,
  29962. a26: 0x271A,
  29963. a27: 0x271B,
  29964. a28: 0x271C,
  29965. a6: 0x271D,
  29966. a7: 0x271E,
  29967. a8: 0x271F,
  29968. a9: 0x2720,
  29969. a10: 0x2721,
  29970. a29: 0x2722,
  29971. a30: 0x2723,
  29972. a31: 0x2724,
  29973. a32: 0x2725,
  29974. a33: 0x2726,
  29975. a34: 0x2727,
  29976. a35: 0x2605,
  29977. a36: 0x2729,
  29978. a37: 0x272A,
  29979. a38: 0x272B,
  29980. a39: 0x272C,
  29981. a40: 0x272D,
  29982. a41: 0x272E,
  29983. a42: 0x272F,
  29984. a43: 0x2730,
  29985. a44: 0x2731,
  29986. a45: 0x2732,
  29987. a46: 0x2733,
  29988. a47: 0x2734,
  29989. a48: 0x2735,
  29990. a49: 0x2736,
  29991. a50: 0x2737,
  29992. a51: 0x2738,
  29993. a52: 0x2739,
  29994. a53: 0x273A,
  29995. a54: 0x273B,
  29996. a55: 0x273C,
  29997. a56: 0x273D,
  29998. a57: 0x273E,
  29999. a58: 0x273F,
  30000. a59: 0x2740,
  30001. a60: 0x2741,
  30002. a61: 0x2742,
  30003. a62: 0x2743,
  30004. a63: 0x2744,
  30005. a64: 0x2745,
  30006. a65: 0x2746,
  30007. a66: 0x2747,
  30008. a67: 0x2748,
  30009. a68: 0x2749,
  30010. a69: 0x274A,
  30011. a70: 0x274B,
  30012. a71: 0x25CF,
  30013. a72: 0x274D,
  30014. a73: 0x25A0,
  30015. a74: 0x274F,
  30016. a203: 0x2750,
  30017. a75: 0x2751,
  30018. a204: 0x2752,
  30019. a76: 0x25B2,
  30020. a77: 0x25BC,
  30021. a78: 0x25C6,
  30022. a79: 0x2756,
  30023. a81: 0x25D7,
  30024. a82: 0x2758,
  30025. a83: 0x2759,
  30026. a84: 0x275A,
  30027. a97: 0x275B,
  30028. a98: 0x275C,
  30029. a99: 0x275D,
  30030. a100: 0x275E,
  30031. a101: 0x2761,
  30032. a102: 0x2762,
  30033. a103: 0x2763,
  30034. a104: 0x2764,
  30035. a106: 0x2765,
  30036. a107: 0x2766,
  30037. a108: 0x2767,
  30038. a112: 0x2663,
  30039. a111: 0x2666,
  30040. a110: 0x2665,
  30041. a109: 0x2660,
  30042. a120: 0x2460,
  30043. a121: 0x2461,
  30044. a122: 0x2462,
  30045. a123: 0x2463,
  30046. a124: 0x2464,
  30047. a125: 0x2465,
  30048. a126: 0x2466,
  30049. a127: 0x2467,
  30050. a128: 0x2468,
  30051. a129: 0x2469,
  30052. a130: 0x2776,
  30053. a131: 0x2777,
  30054. a132: 0x2778,
  30055. a133: 0x2779,
  30056. a134: 0x277A,
  30057. a135: 0x277B,
  30058. a136: 0x277C,
  30059. a137: 0x277D,
  30060. a138: 0x277E,
  30061. a139: 0x277F,
  30062. a140: 0x2780,
  30063. a141: 0x2781,
  30064. a142: 0x2782,
  30065. a143: 0x2783,
  30066. a144: 0x2784,
  30067. a145: 0x2785,
  30068. a146: 0x2786,
  30069. a147: 0x2787,
  30070. a148: 0x2788,
  30071. a149: 0x2789,
  30072. a150: 0x278A,
  30073. a151: 0x278B,
  30074. a152: 0x278C,
  30075. a153: 0x278D,
  30076. a154: 0x278E,
  30077. a155: 0x278F,
  30078. a156: 0x2790,
  30079. a157: 0x2791,
  30080. a158: 0x2792,
  30081. a159: 0x2793,
  30082. a160: 0x2794,
  30083. a161: 0x2192,
  30084. a163: 0x2194,
  30085. a164: 0x2195,
  30086. a196: 0x2798,
  30087. a165: 0x2799,
  30088. a192: 0x279A,
  30089. a166: 0x279B,
  30090. a167: 0x279C,
  30091. a168: 0x279D,
  30092. a169: 0x279E,
  30093. a170: 0x279F,
  30094. a171: 0x27A0,
  30095. a172: 0x27A1,
  30096. a173: 0x27A2,
  30097. a162: 0x27A3,
  30098. a174: 0x27A4,
  30099. a175: 0x27A5,
  30100. a176: 0x27A6,
  30101. a177: 0x27A7,
  30102. a178: 0x27A8,
  30103. a179: 0x27A9,
  30104. a193: 0x27AA,
  30105. a180: 0x27AB,
  30106. a199: 0x27AC,
  30107. a181: 0x27AD,
  30108. a200: 0x27AE,
  30109. a182: 0x27AF,
  30110. a201: 0x27B1,
  30111. a183: 0x27B2,
  30112. a184: 0x27B3,
  30113. a197: 0x27B4,
  30114. a185: 0x27B5,
  30115. a194: 0x27B6,
  30116. a198: 0x27B7,
  30117. a186: 0x27B8,
  30118. a195: 0x27B9,
  30119. a187: 0x27BA,
  30120. a188: 0x27BB,
  30121. a189: 0x27BC,
  30122. a190: 0x27BD,
  30123. a191: 0x27BE,
  30124. a89: 0x2768, // 0xF8D7
  30125. a90: 0x2769, // 0xF8D8
  30126. a93: 0x276A, // 0xF8D9
  30127. a94: 0x276B, // 0xF8DA
  30128. a91: 0x276C, // 0xF8DB
  30129. a92: 0x276D, // 0xF8DC
  30130. a205: 0x276E, // 0xF8DD
  30131. a85: 0x276F, // 0xF8DE
  30132. a206: 0x2770, // 0xF8DF
  30133. a86: 0x2771, // 0xF8E0
  30134. a87: 0x2772, // 0xF8E1
  30135. a88: 0x2773, // 0xF8E2
  30136. a95: 0x2774, // 0xF8E3
  30137. a96: 0x2775, // 0xF8E4
  30138. '.notdef': 0x0000
  30139. };
  30140. var PDFImage = (function PDFImageClosure() {
  30141. /**
  30142. * Decode the image in the main thread if it supported. Resovles the promise
  30143. * when the image data is ready.
  30144. */
  30145. function handleImageData(handler, xref, res, image) {
  30146. if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {
  30147. // For natively supported jpegs send them to the main thread for decoding.
  30148. var dict = image.dict;
  30149. var colorSpace = dict.get('ColorSpace', 'CS');
  30150. colorSpace = ColorSpace.parse(colorSpace, xref, res);
  30151. var numComps = colorSpace.numComps;
  30152. var decodePromise = handler.sendWithPromise('JpegDecode',
  30153. [image.getIR(), numComps]);
  30154. return decodePromise.then(function (message) {
  30155. var data = message.data;
  30156. return new Stream(data, 0, data.length, image.dict);
  30157. });
  30158. } else {
  30159. return Promise.resolve(image);
  30160. }
  30161. }
  30162. /**
  30163. * Decode and clamp a value. The formula is different from the spec because we
  30164. * don't decode to float range [0,1], we decode it in the [0,max] range.
  30165. */
  30166. function decodeAndClamp(value, addend, coefficient, max) {
  30167. value = addend + value * coefficient;
  30168. // Clamp the value to the range
  30169. return (value < 0 ? 0 : (value > max ? max : value));
  30170. }
  30171. function PDFImage(xref, res, image, inline, smask, mask, isMask) {
  30172. this.image = image;
  30173. var dict = image.dict;
  30174. if (dict.has('Filter')) {
  30175. var filter = dict.get('Filter').name;
  30176. if (filter === 'JPXDecode') {
  30177. var jpxImage = new JpxImage();
  30178. jpxImage.parseImageProperties(image.stream);
  30179. image.stream.reset();
  30180. image.bitsPerComponent = jpxImage.bitsPerComponent;
  30181. image.numComps = jpxImage.componentsCount;
  30182. } else if (filter === 'JBIG2Decode') {
  30183. image.bitsPerComponent = 1;
  30184. image.numComps = 1;
  30185. }
  30186. }
  30187. // TODO cache rendered images?
  30188. this.width = dict.get('Width', 'W');
  30189. this.height = dict.get('Height', 'H');
  30190. if (this.width < 1 || this.height < 1) {
  30191. error('Invalid image width: ' + this.width + ' or height: ' +
  30192. this.height);
  30193. }
  30194. this.interpolate = dict.get('Interpolate', 'I') || false;
  30195. this.imageMask = dict.get('ImageMask', 'IM') || false;
  30196. this.matte = dict.get('Matte') || false;
  30197. var bitsPerComponent = image.bitsPerComponent;
  30198. if (!bitsPerComponent) {
  30199. bitsPerComponent = dict.get('BitsPerComponent', 'BPC');
  30200. if (!bitsPerComponent) {
  30201. if (this.imageMask) {
  30202. bitsPerComponent = 1;
  30203. } else {
  30204. error('Bits per component missing in image: ' + this.imageMask);
  30205. }
  30206. }
  30207. }
  30208. this.bpc = bitsPerComponent;
  30209. if (!this.imageMask) {
  30210. var colorSpace = dict.get('ColorSpace', 'CS');
  30211. if (!colorSpace) {
  30212. info('JPX images (which do not require color spaces)');
  30213. switch (image.numComps) {
  30214. case 1:
  30215. colorSpace = Name.get('DeviceGray');
  30216. break;
  30217. case 3:
  30218. colorSpace = Name.get('DeviceRGB');
  30219. break;
  30220. case 4:
  30221. colorSpace = Name.get('DeviceCMYK');
  30222. break;
  30223. default:
  30224. error('JPX images with ' + this.numComps +
  30225. ' color components not supported.');
  30226. }
  30227. }
  30228. this.colorSpace = ColorSpace.parse(colorSpace, xref, res);
  30229. this.numComps = this.colorSpace.numComps;
  30230. }
  30231. this.decode = dict.get('Decode', 'D');
  30232. this.needsDecode = false;
  30233. if (this.decode &&
  30234. ((this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode)) ||
  30235. (isMask && !ColorSpace.isDefaultDecode(this.decode, 1)))) {
  30236. this.needsDecode = true;
  30237. // Do some preprocessing to avoid more math.
  30238. var max = (1 << bitsPerComponent) - 1;
  30239. this.decodeCoefficients = [];
  30240. this.decodeAddends = [];
  30241. for (var i = 0, j = 0; i < this.decode.length; i += 2, ++j) {
  30242. var dmin = this.decode[i];
  30243. var dmax = this.decode[i + 1];
  30244. this.decodeCoefficients[j] = dmax - dmin;
  30245. this.decodeAddends[j] = max * dmin;
  30246. }
  30247. }
  30248. if (smask) {
  30249. this.smask = new PDFImage(xref, res, smask, false);
  30250. } else if (mask) {
  30251. if (isStream(mask)) {
  30252. this.mask = new PDFImage(xref, res, mask, false, null, null, true);
  30253. } else {
  30254. // Color key mask (just an array).
  30255. this.mask = mask;
  30256. }
  30257. }
  30258. }
  30259. /**
  30260. * Handles processing of image data and returns the Promise that is resolved
  30261. * with a PDFImage when the image is ready to be used.
  30262. */
  30263. PDFImage.buildImage = function PDFImage_buildImage(handler, xref,
  30264. res, image, inline) {
  30265. var imagePromise = handleImageData(handler, xref, res, image);
  30266. var smaskPromise;
  30267. var maskPromise;
  30268. var smask = image.dict.get('SMask');
  30269. var mask = image.dict.get('Mask');
  30270. if (smask) {
  30271. smaskPromise = handleImageData(handler, xref, res, smask);
  30272. maskPromise = Promise.resolve(null);
  30273. } else {
  30274. smaskPromise = Promise.resolve(null);
  30275. if (mask) {
  30276. if (isStream(mask)) {
  30277. maskPromise = handleImageData(handler, xref, res, mask);
  30278. } else if (isArray(mask)) {
  30279. maskPromise = Promise.resolve(mask);
  30280. } else {
  30281. warn('Unsupported mask format.');
  30282. maskPromise = Promise.resolve(null);
  30283. }
  30284. } else {
  30285. maskPromise = Promise.resolve(null);
  30286. }
  30287. }
  30288. return Promise.all([imagePromise, smaskPromise, maskPromise]).then(
  30289. function(results) {
  30290. var imageData = results[0];
  30291. var smaskData = results[1];
  30292. var maskData = results[2];
  30293. return new PDFImage(xref, res, imageData, inline, smaskData, maskData);
  30294. });
  30295. };
  30296. /**
  30297. * Resize an image using the nearest neighbor algorithm. Currently only
  30298. * supports one and three component images.
  30299. * @param {TypedArray} pixels The original image with one component.
  30300. * @param {Number} bpc Number of bits per component.
  30301. * @param {Number} components Number of color components, 1 or 3 is supported.
  30302. * @param {Number} w1 Original width.
  30303. * @param {Number} h1 Original height.
  30304. * @param {Number} w2 New width.
  30305. * @param {Number} h2 New height.
  30306. * @param {TypedArray} dest (Optional) The destination buffer.
  30307. * @param {Number} alpha01 (Optional) Size reserved for the alpha channel.
  30308. * @return {TypedArray} Resized image data.
  30309. */
  30310. PDFImage.resize = function PDFImage_resize(pixels, bpc, components,
  30311. w1, h1, w2, h2, dest, alpha01) {
  30312. if (components !== 1 && components !== 3) {
  30313. error('Unsupported component count for resizing.');
  30314. }
  30315. var length = w2 * h2 * components;
  30316. var temp = dest ? dest : (bpc <= 8 ? new Uint8Array(length) :
  30317. (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));
  30318. var xRatio = w1 / w2;
  30319. var yRatio = h1 / h2;
  30320. var i, j, py, newIndex = 0, oldIndex;
  30321. var xScaled = new Uint16Array(w2);
  30322. var w1Scanline = w1 * components;
  30323. if (alpha01 !== 1) {
  30324. alpha01 = 0;
  30325. }
  30326. for (j = 0; j < w2; j++) {
  30327. xScaled[j] = Math.floor(j * xRatio) * components;
  30328. }
  30329. if (components === 1) {
  30330. for (i = 0; i < h2; i++) {
  30331. py = Math.floor(i * yRatio) * w1Scanline;
  30332. for (j = 0; j < w2; j++) {
  30333. oldIndex = py + xScaled[j];
  30334. temp[newIndex++] = pixels[oldIndex];
  30335. }
  30336. }
  30337. } else if (components === 3) {
  30338. for (i = 0; i < h2; i++) {
  30339. py = Math.floor(i * yRatio) * w1Scanline;
  30340. for (j = 0; j < w2; j++) {
  30341. oldIndex = py + xScaled[j];
  30342. temp[newIndex++] = pixels[oldIndex++];
  30343. temp[newIndex++] = pixels[oldIndex++];
  30344. temp[newIndex++] = pixels[oldIndex++];
  30345. newIndex += alpha01;
  30346. }
  30347. }
  30348. }
  30349. return temp;
  30350. };
  30351. PDFImage.createMask =
  30352. function PDFImage_createMask(imgArray, width, height,
  30353. imageIsFromDecodeStream, inverseDecode) {
  30354. // |imgArray| might not contain full data for every pixel of the mask, so
  30355. // we need to distinguish between |computedLength| and |actualLength|.
  30356. // In particular, if inverseDecode is true, then the array we return must
  30357. // have a length of |computedLength|.
  30358. var computedLength = ((width + 7) >> 3) * height;
  30359. var actualLength = imgArray.byteLength;
  30360. var haveFullData = computedLength === actualLength;
  30361. var data, i;
  30362. if (imageIsFromDecodeStream && (!inverseDecode || haveFullData)) {
  30363. // imgArray came from a DecodeStream and its data is in an appropriate
  30364. // form, so we can just transfer it.
  30365. data = imgArray;
  30366. } else if (!inverseDecode) {
  30367. data = new Uint8Array(actualLength);
  30368. data.set(imgArray);
  30369. } else {
  30370. data = new Uint8Array(computedLength);
  30371. data.set(imgArray);
  30372. for (i = actualLength; i < computedLength; i++) {
  30373. data[i] = 0xff;
  30374. }
  30375. }
  30376. // If necessary, invert the original mask data (but not any extra we might
  30377. // have added above). It's safe to modify the array -- whether it's the
  30378. // original or a copy, we're about to transfer it anyway, so nothing else
  30379. // in this thread can be relying on its contents.
  30380. if (inverseDecode) {
  30381. for (i = 0; i < actualLength; i++) {
  30382. data[i] = ~data[i];
  30383. }
  30384. }
  30385. return {data: data, width: width, height: height};
  30386. };
  30387. PDFImage.prototype = {
  30388. get drawWidth() {
  30389. return Math.max(this.width,
  30390. this.smask && this.smask.width || 0,
  30391. this.mask && this.mask.width || 0);
  30392. },
  30393. get drawHeight() {
  30394. return Math.max(this.height,
  30395. this.smask && this.smask.height || 0,
  30396. this.mask && this.mask.height || 0);
  30397. },
  30398. decodeBuffer: function PDFImage_decodeBuffer(buffer) {
  30399. var bpc = this.bpc;
  30400. var numComps = this.numComps;
  30401. var decodeAddends = this.decodeAddends;
  30402. var decodeCoefficients = this.decodeCoefficients;
  30403. var max = (1 << bpc) - 1;
  30404. var i, ii;
  30405. if (bpc === 1) {
  30406. // If the buffer needed decode that means it just needs to be inverted.
  30407. for (i = 0, ii = buffer.length; i < ii; i++) {
  30408. buffer[i] = +!(buffer[i]);
  30409. }
  30410. return;
  30411. }
  30412. var index = 0;
  30413. for (i = 0, ii = this.width * this.height; i < ii; i++) {
  30414. for (var j = 0; j < numComps; j++) {
  30415. buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j],
  30416. decodeCoefficients[j], max);
  30417. index++;
  30418. }
  30419. }
  30420. },
  30421. getComponents: function PDFImage_getComponents(buffer) {
  30422. var bpc = this.bpc;
  30423. // This image doesn't require any extra work.
  30424. if (bpc === 8) {
  30425. return buffer;
  30426. }
  30427. var width = this.width;
  30428. var height = this.height;
  30429. var numComps = this.numComps;
  30430. var length = width * height * numComps;
  30431. var bufferPos = 0;
  30432. var output = (bpc <= 8 ? new Uint8Array(length) :
  30433. (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));
  30434. var rowComps = width * numComps;
  30435. var max = (1 << bpc) - 1;
  30436. var i = 0, ii, buf;
  30437. if (bpc === 1) {
  30438. // Optimization for reading 1 bpc images.
  30439. var mask, loop1End, loop2End;
  30440. for (var j = 0; j < height; j++) {
  30441. loop1End = i + (rowComps & ~7);
  30442. loop2End = i + rowComps;
  30443. // unroll loop for all full bytes
  30444. while (i < loop1End) {
  30445. buf = buffer[bufferPos++];
  30446. output[i] = (buf >> 7) & 1;
  30447. output[i + 1] = (buf >> 6) & 1;
  30448. output[i + 2] = (buf >> 5) & 1;
  30449. output[i + 3] = (buf >> 4) & 1;
  30450. output[i + 4] = (buf >> 3) & 1;
  30451. output[i + 5] = (buf >> 2) & 1;
  30452. output[i + 6] = (buf >> 1) & 1;
  30453. output[i + 7] = buf & 1;
  30454. i += 8;
  30455. }
  30456. // handle remaing bits
  30457. if (i < loop2End) {
  30458. buf = buffer[bufferPos++];
  30459. mask = 128;
  30460. while (i < loop2End) {
  30461. output[i++] = +!!(buf & mask);
  30462. mask >>= 1;
  30463. }
  30464. }
  30465. }
  30466. } else {
  30467. // The general case that handles all other bpc values.
  30468. var bits = 0;
  30469. buf = 0;
  30470. for (i = 0, ii = length; i < ii; ++i) {
  30471. if (i % rowComps === 0) {
  30472. buf = 0;
  30473. bits = 0;
  30474. }
  30475. while (bits < bpc) {
  30476. buf = (buf << 8) | buffer[bufferPos++];
  30477. bits += 8;
  30478. }
  30479. var remainingBits = bits - bpc;
  30480. var value = buf >> remainingBits;
  30481. output[i] = (value < 0 ? 0 : (value > max ? max : value));
  30482. buf = buf & ((1 << remainingBits) - 1);
  30483. bits = remainingBits;
  30484. }
  30485. }
  30486. return output;
  30487. },
  30488. fillOpacity: function PDFImage_fillOpacity(rgbaBuf, width, height,
  30489. actualHeight, image) {
  30490. var smask = this.smask;
  30491. var mask = this.mask;
  30492. var alphaBuf, sw, sh, i, ii, j;
  30493. if (smask) {
  30494. sw = smask.width;
  30495. sh = smask.height;
  30496. alphaBuf = new Uint8Array(sw * sh);
  30497. smask.fillGrayBuffer(alphaBuf);
  30498. if (sw !== width || sh !== height) {
  30499. alphaBuf = PDFImage.resize(alphaBuf, smask.bpc, 1, sw, sh, width,
  30500. height);
  30501. }
  30502. } else if (mask) {
  30503. if (mask instanceof PDFImage) {
  30504. sw = mask.width;
  30505. sh = mask.height;
  30506. alphaBuf = new Uint8Array(sw * sh);
  30507. mask.numComps = 1;
  30508. mask.fillGrayBuffer(alphaBuf);
  30509. // Need to invert values in rgbaBuf
  30510. for (i = 0, ii = sw * sh; i < ii; ++i) {
  30511. alphaBuf[i] = 255 - alphaBuf[i];
  30512. }
  30513. if (sw !== width || sh !== height) {
  30514. alphaBuf = PDFImage.resize(alphaBuf, mask.bpc, 1, sw, sh, width,
  30515. height);
  30516. }
  30517. } else if (isArray(mask)) {
  30518. // Color key mask: if any of the compontents are outside the range
  30519. // then they should be painted.
  30520. alphaBuf = new Uint8Array(width * height);
  30521. var numComps = this.numComps;
  30522. for (i = 0, ii = width * height; i < ii; ++i) {
  30523. var opacity = 0;
  30524. var imageOffset = i * numComps;
  30525. for (j = 0; j < numComps; ++j) {
  30526. var color = image[imageOffset + j];
  30527. var maskOffset = j * 2;
  30528. if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
  30529. opacity = 255;
  30530. break;
  30531. }
  30532. }
  30533. alphaBuf[i] = opacity;
  30534. }
  30535. } else {
  30536. error('Unknown mask format.');
  30537. }
  30538. }
  30539. if (alphaBuf) {
  30540. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  30541. rgbaBuf[j] = alphaBuf[i];
  30542. }
  30543. } else {
  30544. // No mask.
  30545. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  30546. rgbaBuf[j] = 255;
  30547. }
  30548. }
  30549. },
  30550. undoPreblend: function PDFImage_undoPreblend(buffer, width, height) {
  30551. var matte = this.smask && this.smask.matte;
  30552. if (!matte) {
  30553. return;
  30554. }
  30555. var matteRgb = this.colorSpace.getRgb(matte, 0);
  30556. var matteR = matteRgb[0];
  30557. var matteG = matteRgb[1];
  30558. var matteB = matteRgb[2];
  30559. var length = width * height * 4;
  30560. var r, g, b;
  30561. for (var i = 0; i < length; i += 4) {
  30562. var alpha = buffer[i + 3];
  30563. if (alpha === 0) {
  30564. // according formula we have to get Infinity in all components
  30565. // making it white (typical paper color) should be okay
  30566. buffer[i] = 255;
  30567. buffer[i + 1] = 255;
  30568. buffer[i + 2] = 255;
  30569. continue;
  30570. }
  30571. var k = 255 / alpha;
  30572. r = (buffer[i] - matteR) * k + matteR;
  30573. g = (buffer[i + 1] - matteG) * k + matteG;
  30574. b = (buffer[i + 2] - matteB) * k + matteB;
  30575. buffer[i] = r <= 0 ? 0 : r >= 255 ? 255 : r | 0;
  30576. buffer[i + 1] = g <= 0 ? 0 : g >= 255 ? 255 : g | 0;
  30577. buffer[i + 2] = b <= 0 ? 0 : b >= 255 ? 255 : b | 0;
  30578. }
  30579. },
  30580. createImageData: function PDFImage_createImageData(forceRGBA) {
  30581. var drawWidth = this.drawWidth;
  30582. var drawHeight = this.drawHeight;
  30583. var imgData = { // other fields are filled in below
  30584. width: drawWidth,
  30585. height: drawHeight
  30586. };
  30587. var numComps = this.numComps;
  30588. var originalWidth = this.width;
  30589. var originalHeight = this.height;
  30590. var bpc = this.bpc;
  30591. // Rows start at byte boundary.
  30592. var rowBytes = (originalWidth * numComps * bpc + 7) >> 3;
  30593. var imgArray;
  30594. if (!forceRGBA) {
  30595. // If it is a 1-bit-per-pixel grayscale (i.e. black-and-white) image
  30596. // without any complications, we pass a same-sized copy to the main
  30597. // thread rather than expanding by 32x to RGBA form. This saves *lots*
  30598. // of memory for many scanned documents. It's also much faster.
  30599. //
  30600. // Similarly, if it is a 24-bit-per pixel RGB image without any
  30601. // complications, we avoid expanding by 1.333x to RGBA form.
  30602. var kind;
  30603. if (this.colorSpace.name === 'DeviceGray' && bpc === 1) {
  30604. kind = ImageKind.GRAYSCALE_1BPP;
  30605. } else if (this.colorSpace.name === 'DeviceRGB' && bpc === 8 &&
  30606. !this.needsDecode) {
  30607. kind = ImageKind.RGB_24BPP;
  30608. }
  30609. if (kind && !this.smask && !this.mask &&
  30610. drawWidth === originalWidth && drawHeight === originalHeight) {
  30611. imgData.kind = kind;
  30612. imgArray = this.getImageBytes(originalHeight * rowBytes);
  30613. // If imgArray came from a DecodeStream, we're safe to transfer it
  30614. // (and thus neuter it) because it will constitute the entire
  30615. // DecodeStream's data. But if it came from a Stream, we need to
  30616. // copy it because it'll only be a portion of the Stream's data, and
  30617. // the rest will be read later on.
  30618. if (this.image instanceof DecodeStream) {
  30619. imgData.data = imgArray;
  30620. } else {
  30621. var newArray = new Uint8Array(imgArray.length);
  30622. newArray.set(imgArray);
  30623. imgData.data = newArray;
  30624. }
  30625. if (this.needsDecode) {
  30626. // Invert the buffer (which must be grayscale if we reached here).
  30627. assert(kind === ImageKind.GRAYSCALE_1BPP);
  30628. var buffer = imgData.data;
  30629. for (var i = 0, ii = buffer.length; i < ii; i++) {
  30630. buffer[i] ^= 0xff;
  30631. }
  30632. }
  30633. return imgData;
  30634. }
  30635. if (this.image instanceof JpegStream && !this.smask && !this.mask) {
  30636. imgData.kind = ImageKind.RGB_24BPP;
  30637. imgData.data = this.getImageBytes(originalHeight * rowBytes,
  30638. drawWidth, drawHeight, true);
  30639. return imgData;
  30640. }
  30641. }
  30642. imgArray = this.getImageBytes(originalHeight * rowBytes);
  30643. // imgArray can be incomplete (e.g. after CCITT fax encoding).
  30644. var actualHeight = 0 | (imgArray.length / rowBytes *
  30645. drawHeight / originalHeight);
  30646. var comps = this.getComponents(imgArray);
  30647. // If opacity data is present, use RGBA_32BPP form. Otherwise, use the
  30648. // more compact RGB_24BPP form if allowable.
  30649. var alpha01, maybeUndoPreblend;
  30650. if (!forceRGBA && !this.smask && !this.mask) {
  30651. imgData.kind = ImageKind.RGB_24BPP;
  30652. imgData.data = new Uint8Array(drawWidth * drawHeight * 3);
  30653. alpha01 = 0;
  30654. maybeUndoPreblend = false;
  30655. } else {
  30656. imgData.kind = ImageKind.RGBA_32BPP;
  30657. imgData.data = new Uint8Array(drawWidth * drawHeight * 4);
  30658. alpha01 = 1;
  30659. maybeUndoPreblend = true;
  30660. // Color key masking (opacity) must be performed before decoding.
  30661. this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight,
  30662. comps);
  30663. }
  30664. if (this.needsDecode) {
  30665. this.decodeBuffer(comps);
  30666. }
  30667. this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight,
  30668. drawWidth, drawHeight, actualHeight, bpc, comps,
  30669. alpha01);
  30670. if (maybeUndoPreblend) {
  30671. this.undoPreblend(imgData.data, drawWidth, actualHeight);
  30672. }
  30673. return imgData;
  30674. },
  30675. fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) {
  30676. var numComps = this.numComps;
  30677. if (numComps !== 1) {
  30678. error('Reading gray scale from a color image: ' + numComps);
  30679. }
  30680. var width = this.width;
  30681. var height = this.height;
  30682. var bpc = this.bpc;
  30683. // rows start at byte boundary
  30684. var rowBytes = (width * numComps * bpc + 7) >> 3;
  30685. var imgArray = this.getImageBytes(height * rowBytes);
  30686. var comps = this.getComponents(imgArray);
  30687. var i, length;
  30688. if (bpc === 1) {
  30689. // inline decoding (= inversion) for 1 bpc images
  30690. length = width * height;
  30691. if (this.needsDecode) {
  30692. // invert and scale to {0, 255}
  30693. for (i = 0; i < length; ++i) {
  30694. buffer[i] = (comps[i] - 1) & 255;
  30695. }
  30696. } else {
  30697. // scale to {0, 255}
  30698. for (i = 0; i < length; ++i) {
  30699. buffer[i] = (-comps[i]) & 255;
  30700. }
  30701. }
  30702. return;
  30703. }
  30704. if (this.needsDecode) {
  30705. this.decodeBuffer(comps);
  30706. }
  30707. length = width * height;
  30708. // we aren't using a colorspace so we need to scale the value
  30709. var scale = 255 / ((1 << bpc) - 1);
  30710. for (i = 0; i < length; ++i) {
  30711. buffer[i] = (scale * comps[i]) | 0;
  30712. }
  30713. },
  30714. getImageBytes: function PDFImage_getImageBytes(length,
  30715. drawWidth, drawHeight,
  30716. forceRGB) {
  30717. this.image.reset();
  30718. this.image.drawWidth = drawWidth || this.width;
  30719. this.image.drawHeight = drawHeight || this.height;
  30720. this.image.forceRGB = !!forceRGB;
  30721. return this.image.getBytes(length);
  30722. }
  30723. };
  30724. return PDFImage;
  30725. })();
  30726. // The Metrics object contains glyph widths (in glyph space units).
  30727. // As per PDF spec, for most fonts (Type 3 being an exception) a glyph
  30728. // space unit corresponds to 1/1000th of text space unit.
  30729. var Metrics = {
  30730. 'Courier': 600,
  30731. 'Courier-Bold': 600,
  30732. 'Courier-BoldOblique': 600,
  30733. 'Courier-Oblique': 600,
  30734. 'Helvetica' : {
  30735. 'space': 278,
  30736. 'exclam': 278,
  30737. 'quotedbl': 355,
  30738. 'numbersign': 556,
  30739. 'dollar': 556,
  30740. 'percent': 889,
  30741. 'ampersand': 667,
  30742. 'quoteright': 222,
  30743. 'parenleft': 333,
  30744. 'parenright': 333,
  30745. 'asterisk': 389,
  30746. 'plus': 584,
  30747. 'comma': 278,
  30748. 'hyphen': 333,
  30749. 'period': 278,
  30750. 'slash': 278,
  30751. 'zero': 556,
  30752. 'one': 556,
  30753. 'two': 556,
  30754. 'three': 556,
  30755. 'four': 556,
  30756. 'five': 556,
  30757. 'six': 556,
  30758. 'seven': 556,
  30759. 'eight': 556,
  30760. 'nine': 556,
  30761. 'colon': 278,
  30762. 'semicolon': 278,
  30763. 'less': 584,
  30764. 'equal': 584,
  30765. 'greater': 584,
  30766. 'question': 556,
  30767. 'at': 1015,
  30768. 'A': 667,
  30769. 'B': 667,
  30770. 'C': 722,
  30771. 'D': 722,
  30772. 'E': 667,
  30773. 'F': 611,
  30774. 'G': 778,
  30775. 'H': 722,
  30776. 'I': 278,
  30777. 'J': 500,
  30778. 'K': 667,
  30779. 'L': 556,
  30780. 'M': 833,
  30781. 'N': 722,
  30782. 'O': 778,
  30783. 'P': 667,
  30784. 'Q': 778,
  30785. 'R': 722,
  30786. 'S': 667,
  30787. 'T': 611,
  30788. 'U': 722,
  30789. 'V': 667,
  30790. 'W': 944,
  30791. 'X': 667,
  30792. 'Y': 667,
  30793. 'Z': 611,
  30794. 'bracketleft': 278,
  30795. 'backslash': 278,
  30796. 'bracketright': 278,
  30797. 'asciicircum': 469,
  30798. 'underscore': 556,
  30799. 'quoteleft': 222,
  30800. 'a': 556,
  30801. 'b': 556,
  30802. 'c': 500,
  30803. 'd': 556,
  30804. 'e': 556,
  30805. 'f': 278,
  30806. 'g': 556,
  30807. 'h': 556,
  30808. 'i': 222,
  30809. 'j': 222,
  30810. 'k': 500,
  30811. 'l': 222,
  30812. 'm': 833,
  30813. 'n': 556,
  30814. 'o': 556,
  30815. 'p': 556,
  30816. 'q': 556,
  30817. 'r': 333,
  30818. 's': 500,
  30819. 't': 278,
  30820. 'u': 556,
  30821. 'v': 500,
  30822. 'w': 722,
  30823. 'x': 500,
  30824. 'y': 500,
  30825. 'z': 500,
  30826. 'braceleft': 334,
  30827. 'bar': 260,
  30828. 'braceright': 334,
  30829. 'asciitilde': 584,
  30830. 'exclamdown': 333,
  30831. 'cent': 556,
  30832. 'sterling': 556,
  30833. 'fraction': 167,
  30834. 'yen': 556,
  30835. 'florin': 556,
  30836. 'section': 556,
  30837. 'currency': 556,
  30838. 'quotesingle': 191,
  30839. 'quotedblleft': 333,
  30840. 'guillemotleft': 556,
  30841. 'guilsinglleft': 333,
  30842. 'guilsinglright': 333,
  30843. 'fi': 500,
  30844. 'fl': 500,
  30845. 'endash': 556,
  30846. 'dagger': 556,
  30847. 'daggerdbl': 556,
  30848. 'periodcentered': 278,
  30849. 'paragraph': 537,
  30850. 'bullet': 350,
  30851. 'quotesinglbase': 222,
  30852. 'quotedblbase': 333,
  30853. 'quotedblright': 333,
  30854. 'guillemotright': 556,
  30855. 'ellipsis': 1000,
  30856. 'perthousand': 1000,
  30857. 'questiondown': 611,
  30858. 'grave': 333,
  30859. 'acute': 333,
  30860. 'circumflex': 333,
  30861. 'tilde': 333,
  30862. 'macron': 333,
  30863. 'breve': 333,
  30864. 'dotaccent': 333,
  30865. 'dieresis': 333,
  30866. 'ring': 333,
  30867. 'cedilla': 333,
  30868. 'hungarumlaut': 333,
  30869. 'ogonek': 333,
  30870. 'caron': 333,
  30871. 'emdash': 1000,
  30872. 'AE': 1000,
  30873. 'ordfeminine': 370,
  30874. 'Lslash': 556,
  30875. 'Oslash': 778,
  30876. 'OE': 1000,
  30877. 'ordmasculine': 365,
  30878. 'ae': 889,
  30879. 'dotlessi': 278,
  30880. 'lslash': 222,
  30881. 'oslash': 611,
  30882. 'oe': 944,
  30883. 'germandbls': 611,
  30884. 'Idieresis': 278,
  30885. 'eacute': 556,
  30886. 'abreve': 556,
  30887. 'uhungarumlaut': 556,
  30888. 'ecaron': 556,
  30889. 'Ydieresis': 667,
  30890. 'divide': 584,
  30891. 'Yacute': 667,
  30892. 'Acircumflex': 667,
  30893. 'aacute': 556,
  30894. 'Ucircumflex': 722,
  30895. 'yacute': 500,
  30896. 'scommaaccent': 500,
  30897. 'ecircumflex': 556,
  30898. 'Uring': 722,
  30899. 'Udieresis': 722,
  30900. 'aogonek': 556,
  30901. 'Uacute': 722,
  30902. 'uogonek': 556,
  30903. 'Edieresis': 667,
  30904. 'Dcroat': 722,
  30905. 'commaaccent': 250,
  30906. 'copyright': 737,
  30907. 'Emacron': 667,
  30908. 'ccaron': 500,
  30909. 'aring': 556,
  30910. 'Ncommaaccent': 722,
  30911. 'lacute': 222,
  30912. 'agrave': 556,
  30913. 'Tcommaaccent': 611,
  30914. 'Cacute': 722,
  30915. 'atilde': 556,
  30916. 'Edotaccent': 667,
  30917. 'scaron': 500,
  30918. 'scedilla': 500,
  30919. 'iacute': 278,
  30920. 'lozenge': 471,
  30921. 'Rcaron': 722,
  30922. 'Gcommaaccent': 778,
  30923. 'ucircumflex': 556,
  30924. 'acircumflex': 556,
  30925. 'Amacron': 667,
  30926. 'rcaron': 333,
  30927. 'ccedilla': 500,
  30928. 'Zdotaccent': 611,
  30929. 'Thorn': 667,
  30930. 'Omacron': 778,
  30931. 'Racute': 722,
  30932. 'Sacute': 667,
  30933. 'dcaron': 643,
  30934. 'Umacron': 722,
  30935. 'uring': 556,
  30936. 'threesuperior': 333,
  30937. 'Ograve': 778,
  30938. 'Agrave': 667,
  30939. 'Abreve': 667,
  30940. 'multiply': 584,
  30941. 'uacute': 556,
  30942. 'Tcaron': 611,
  30943. 'partialdiff': 476,
  30944. 'ydieresis': 500,
  30945. 'Nacute': 722,
  30946. 'icircumflex': 278,
  30947. 'Ecircumflex': 667,
  30948. 'adieresis': 556,
  30949. 'edieresis': 556,
  30950. 'cacute': 500,
  30951. 'nacute': 556,
  30952. 'umacron': 556,
  30953. 'Ncaron': 722,
  30954. 'Iacute': 278,
  30955. 'plusminus': 584,
  30956. 'brokenbar': 260,
  30957. 'registered': 737,
  30958. 'Gbreve': 778,
  30959. 'Idotaccent': 278,
  30960. 'summation': 600,
  30961. 'Egrave': 667,
  30962. 'racute': 333,
  30963. 'omacron': 556,
  30964. 'Zacute': 611,
  30965. 'Zcaron': 611,
  30966. 'greaterequal': 549,
  30967. 'Eth': 722,
  30968. 'Ccedilla': 722,
  30969. 'lcommaaccent': 222,
  30970. 'tcaron': 317,
  30971. 'eogonek': 556,
  30972. 'Uogonek': 722,
  30973. 'Aacute': 667,
  30974. 'Adieresis': 667,
  30975. 'egrave': 556,
  30976. 'zacute': 500,
  30977. 'iogonek': 222,
  30978. 'Oacute': 778,
  30979. 'oacute': 556,
  30980. 'amacron': 556,
  30981. 'sacute': 500,
  30982. 'idieresis': 278,
  30983. 'Ocircumflex': 778,
  30984. 'Ugrave': 722,
  30985. 'Delta': 612,
  30986. 'thorn': 556,
  30987. 'twosuperior': 333,
  30988. 'Odieresis': 778,
  30989. 'mu': 556,
  30990. 'igrave': 278,
  30991. 'ohungarumlaut': 556,
  30992. 'Eogonek': 667,
  30993. 'dcroat': 556,
  30994. 'threequarters': 834,
  30995. 'Scedilla': 667,
  30996. 'lcaron': 299,
  30997. 'Kcommaaccent': 667,
  30998. 'Lacute': 556,
  30999. 'trademark': 1000,
  31000. 'edotaccent': 556,
  31001. 'Igrave': 278,
  31002. 'Imacron': 278,
  31003. 'Lcaron': 556,
  31004. 'onehalf': 834,
  31005. 'lessequal': 549,
  31006. 'ocircumflex': 556,
  31007. 'ntilde': 556,
  31008. 'Uhungarumlaut': 722,
  31009. 'Eacute': 667,
  31010. 'emacron': 556,
  31011. 'gbreve': 556,
  31012. 'onequarter': 834,
  31013. 'Scaron': 667,
  31014. 'Scommaaccent': 667,
  31015. 'Ohungarumlaut': 778,
  31016. 'degree': 400,
  31017. 'ograve': 556,
  31018. 'Ccaron': 722,
  31019. 'ugrave': 556,
  31020. 'radical': 453,
  31021. 'Dcaron': 722,
  31022. 'rcommaaccent': 333,
  31023. 'Ntilde': 722,
  31024. 'otilde': 556,
  31025. 'Rcommaaccent': 722,
  31026. 'Lcommaaccent': 556,
  31027. 'Atilde': 667,
  31028. 'Aogonek': 667,
  31029. 'Aring': 667,
  31030. 'Otilde': 778,
  31031. 'zdotaccent': 500,
  31032. 'Ecaron': 667,
  31033. 'Iogonek': 278,
  31034. 'kcommaaccent': 500,
  31035. 'minus': 584,
  31036. 'Icircumflex': 278,
  31037. 'ncaron': 556,
  31038. 'tcommaaccent': 278,
  31039. 'logicalnot': 584,
  31040. 'odieresis': 556,
  31041. 'udieresis': 556,
  31042. 'notequal': 549,
  31043. 'gcommaaccent': 556,
  31044. 'eth': 556,
  31045. 'zcaron': 500,
  31046. 'ncommaaccent': 556,
  31047. 'onesuperior': 333,
  31048. 'imacron': 278,
  31049. 'Euro': 556
  31050. },
  31051. 'Helvetica-Bold': {
  31052. 'space': 278,
  31053. 'exclam': 333,
  31054. 'quotedbl': 474,
  31055. 'numbersign': 556,
  31056. 'dollar': 556,
  31057. 'percent': 889,
  31058. 'ampersand': 722,
  31059. 'quoteright': 278,
  31060. 'parenleft': 333,
  31061. 'parenright': 333,
  31062. 'asterisk': 389,
  31063. 'plus': 584,
  31064. 'comma': 278,
  31065. 'hyphen': 333,
  31066. 'period': 278,
  31067. 'slash': 278,
  31068. 'zero': 556,
  31069. 'one': 556,
  31070. 'two': 556,
  31071. 'three': 556,
  31072. 'four': 556,
  31073. 'five': 556,
  31074. 'six': 556,
  31075. 'seven': 556,
  31076. 'eight': 556,
  31077. 'nine': 556,
  31078. 'colon': 333,
  31079. 'semicolon': 333,
  31080. 'less': 584,
  31081. 'equal': 584,
  31082. 'greater': 584,
  31083. 'question': 611,
  31084. 'at': 975,
  31085. 'A': 722,
  31086. 'B': 722,
  31087. 'C': 722,
  31088. 'D': 722,
  31089. 'E': 667,
  31090. 'F': 611,
  31091. 'G': 778,
  31092. 'H': 722,
  31093. 'I': 278,
  31094. 'J': 556,
  31095. 'K': 722,
  31096. 'L': 611,
  31097. 'M': 833,
  31098. 'N': 722,
  31099. 'O': 778,
  31100. 'P': 667,
  31101. 'Q': 778,
  31102. 'R': 722,
  31103. 'S': 667,
  31104. 'T': 611,
  31105. 'U': 722,
  31106. 'V': 667,
  31107. 'W': 944,
  31108. 'X': 667,
  31109. 'Y': 667,
  31110. 'Z': 611,
  31111. 'bracketleft': 333,
  31112. 'backslash': 278,
  31113. 'bracketright': 333,
  31114. 'asciicircum': 584,
  31115. 'underscore': 556,
  31116. 'quoteleft': 278,
  31117. 'a': 556,
  31118. 'b': 611,
  31119. 'c': 556,
  31120. 'd': 611,
  31121. 'e': 556,
  31122. 'f': 333,
  31123. 'g': 611,
  31124. 'h': 611,
  31125. 'i': 278,
  31126. 'j': 278,
  31127. 'k': 556,
  31128. 'l': 278,
  31129. 'm': 889,
  31130. 'n': 611,
  31131. 'o': 611,
  31132. 'p': 611,
  31133. 'q': 611,
  31134. 'r': 389,
  31135. 's': 556,
  31136. 't': 333,
  31137. 'u': 611,
  31138. 'v': 556,
  31139. 'w': 778,
  31140. 'x': 556,
  31141. 'y': 556,
  31142. 'z': 500,
  31143. 'braceleft': 389,
  31144. 'bar': 280,
  31145. 'braceright': 389,
  31146. 'asciitilde': 584,
  31147. 'exclamdown': 333,
  31148. 'cent': 556,
  31149. 'sterling': 556,
  31150. 'fraction': 167,
  31151. 'yen': 556,
  31152. 'florin': 556,
  31153. 'section': 556,
  31154. 'currency': 556,
  31155. 'quotesingle': 238,
  31156. 'quotedblleft': 500,
  31157. 'guillemotleft': 556,
  31158. 'guilsinglleft': 333,
  31159. 'guilsinglright': 333,
  31160. 'fi': 611,
  31161. 'fl': 611,
  31162. 'endash': 556,
  31163. 'dagger': 556,
  31164. 'daggerdbl': 556,
  31165. 'periodcentered': 278,
  31166. 'paragraph': 556,
  31167. 'bullet': 350,
  31168. 'quotesinglbase': 278,
  31169. 'quotedblbase': 500,
  31170. 'quotedblright': 500,
  31171. 'guillemotright': 556,
  31172. 'ellipsis': 1000,
  31173. 'perthousand': 1000,
  31174. 'questiondown': 611,
  31175. 'grave': 333,
  31176. 'acute': 333,
  31177. 'circumflex': 333,
  31178. 'tilde': 333,
  31179. 'macron': 333,
  31180. 'breve': 333,
  31181. 'dotaccent': 333,
  31182. 'dieresis': 333,
  31183. 'ring': 333,
  31184. 'cedilla': 333,
  31185. 'hungarumlaut': 333,
  31186. 'ogonek': 333,
  31187. 'caron': 333,
  31188. 'emdash': 1000,
  31189. 'AE': 1000,
  31190. 'ordfeminine': 370,
  31191. 'Lslash': 611,
  31192. 'Oslash': 778,
  31193. 'OE': 1000,
  31194. 'ordmasculine': 365,
  31195. 'ae': 889,
  31196. 'dotlessi': 278,
  31197. 'lslash': 278,
  31198. 'oslash': 611,
  31199. 'oe': 944,
  31200. 'germandbls': 611,
  31201. 'Idieresis': 278,
  31202. 'eacute': 556,
  31203. 'abreve': 556,
  31204. 'uhungarumlaut': 611,
  31205. 'ecaron': 556,
  31206. 'Ydieresis': 667,
  31207. 'divide': 584,
  31208. 'Yacute': 667,
  31209. 'Acircumflex': 722,
  31210. 'aacute': 556,
  31211. 'Ucircumflex': 722,
  31212. 'yacute': 556,
  31213. 'scommaaccent': 556,
  31214. 'ecircumflex': 556,
  31215. 'Uring': 722,
  31216. 'Udieresis': 722,
  31217. 'aogonek': 556,
  31218. 'Uacute': 722,
  31219. 'uogonek': 611,
  31220. 'Edieresis': 667,
  31221. 'Dcroat': 722,
  31222. 'commaaccent': 250,
  31223. 'copyright': 737,
  31224. 'Emacron': 667,
  31225. 'ccaron': 556,
  31226. 'aring': 556,
  31227. 'Ncommaaccent': 722,
  31228. 'lacute': 278,
  31229. 'agrave': 556,
  31230. 'Tcommaaccent': 611,
  31231. 'Cacute': 722,
  31232. 'atilde': 556,
  31233. 'Edotaccent': 667,
  31234. 'scaron': 556,
  31235. 'scedilla': 556,
  31236. 'iacute': 278,
  31237. 'lozenge': 494,
  31238. 'Rcaron': 722,
  31239. 'Gcommaaccent': 778,
  31240. 'ucircumflex': 611,
  31241. 'acircumflex': 556,
  31242. 'Amacron': 722,
  31243. 'rcaron': 389,
  31244. 'ccedilla': 556,
  31245. 'Zdotaccent': 611,
  31246. 'Thorn': 667,
  31247. 'Omacron': 778,
  31248. 'Racute': 722,
  31249. 'Sacute': 667,
  31250. 'dcaron': 743,
  31251. 'Umacron': 722,
  31252. 'uring': 611,
  31253. 'threesuperior': 333,
  31254. 'Ograve': 778,
  31255. 'Agrave': 722,
  31256. 'Abreve': 722,
  31257. 'multiply': 584,
  31258. 'uacute': 611,
  31259. 'Tcaron': 611,
  31260. 'partialdiff': 494,
  31261. 'ydieresis': 556,
  31262. 'Nacute': 722,
  31263. 'icircumflex': 278,
  31264. 'Ecircumflex': 667,
  31265. 'adieresis': 556,
  31266. 'edieresis': 556,
  31267. 'cacute': 556,
  31268. 'nacute': 611,
  31269. 'umacron': 611,
  31270. 'Ncaron': 722,
  31271. 'Iacute': 278,
  31272. 'plusminus': 584,
  31273. 'brokenbar': 280,
  31274. 'registered': 737,
  31275. 'Gbreve': 778,
  31276. 'Idotaccent': 278,
  31277. 'summation': 600,
  31278. 'Egrave': 667,
  31279. 'racute': 389,
  31280. 'omacron': 611,
  31281. 'Zacute': 611,
  31282. 'Zcaron': 611,
  31283. 'greaterequal': 549,
  31284. 'Eth': 722,
  31285. 'Ccedilla': 722,
  31286. 'lcommaaccent': 278,
  31287. 'tcaron': 389,
  31288. 'eogonek': 556,
  31289. 'Uogonek': 722,
  31290. 'Aacute': 722,
  31291. 'Adieresis': 722,
  31292. 'egrave': 556,
  31293. 'zacute': 500,
  31294. 'iogonek': 278,
  31295. 'Oacute': 778,
  31296. 'oacute': 611,
  31297. 'amacron': 556,
  31298. 'sacute': 556,
  31299. 'idieresis': 278,
  31300. 'Ocircumflex': 778,
  31301. 'Ugrave': 722,
  31302. 'Delta': 612,
  31303. 'thorn': 611,
  31304. 'twosuperior': 333,
  31305. 'Odieresis': 778,
  31306. 'mu': 611,
  31307. 'igrave': 278,
  31308. 'ohungarumlaut': 611,
  31309. 'Eogonek': 667,
  31310. 'dcroat': 611,
  31311. 'threequarters': 834,
  31312. 'Scedilla': 667,
  31313. 'lcaron': 400,
  31314. 'Kcommaaccent': 722,
  31315. 'Lacute': 611,
  31316. 'trademark': 1000,
  31317. 'edotaccent': 556,
  31318. 'Igrave': 278,
  31319. 'Imacron': 278,
  31320. 'Lcaron': 611,
  31321. 'onehalf': 834,
  31322. 'lessequal': 549,
  31323. 'ocircumflex': 611,
  31324. 'ntilde': 611,
  31325. 'Uhungarumlaut': 722,
  31326. 'Eacute': 667,
  31327. 'emacron': 556,
  31328. 'gbreve': 611,
  31329. 'onequarter': 834,
  31330. 'Scaron': 667,
  31331. 'Scommaaccent': 667,
  31332. 'Ohungarumlaut': 778,
  31333. 'degree': 400,
  31334. 'ograve': 611,
  31335. 'Ccaron': 722,
  31336. 'ugrave': 611,
  31337. 'radical': 549,
  31338. 'Dcaron': 722,
  31339. 'rcommaaccent': 389,
  31340. 'Ntilde': 722,
  31341. 'otilde': 611,
  31342. 'Rcommaaccent': 722,
  31343. 'Lcommaaccent': 611,
  31344. 'Atilde': 722,
  31345. 'Aogonek': 722,
  31346. 'Aring': 722,
  31347. 'Otilde': 778,
  31348. 'zdotaccent': 500,
  31349. 'Ecaron': 667,
  31350. 'Iogonek': 278,
  31351. 'kcommaaccent': 556,
  31352. 'minus': 584,
  31353. 'Icircumflex': 278,
  31354. 'ncaron': 611,
  31355. 'tcommaaccent': 333,
  31356. 'logicalnot': 584,
  31357. 'odieresis': 611,
  31358. 'udieresis': 611,
  31359. 'notequal': 549,
  31360. 'gcommaaccent': 611,
  31361. 'eth': 611,
  31362. 'zcaron': 500,
  31363. 'ncommaaccent': 611,
  31364. 'onesuperior': 333,
  31365. 'imacron': 278,
  31366. 'Euro': 556
  31367. },
  31368. 'Helvetica-BoldOblique': {
  31369. 'space': 278,
  31370. 'exclam': 333,
  31371. 'quotedbl': 474,
  31372. 'numbersign': 556,
  31373. 'dollar': 556,
  31374. 'percent': 889,
  31375. 'ampersand': 722,
  31376. 'quoteright': 278,
  31377. 'parenleft': 333,
  31378. 'parenright': 333,
  31379. 'asterisk': 389,
  31380. 'plus': 584,
  31381. 'comma': 278,
  31382. 'hyphen': 333,
  31383. 'period': 278,
  31384. 'slash': 278,
  31385. 'zero': 556,
  31386. 'one': 556,
  31387. 'two': 556,
  31388. 'three': 556,
  31389. 'four': 556,
  31390. 'five': 556,
  31391. 'six': 556,
  31392. 'seven': 556,
  31393. 'eight': 556,
  31394. 'nine': 556,
  31395. 'colon': 333,
  31396. 'semicolon': 333,
  31397. 'less': 584,
  31398. 'equal': 584,
  31399. 'greater': 584,
  31400. 'question': 611,
  31401. 'at': 975,
  31402. 'A': 722,
  31403. 'B': 722,
  31404. 'C': 722,
  31405. 'D': 722,
  31406. 'E': 667,
  31407. 'F': 611,
  31408. 'G': 778,
  31409. 'H': 722,
  31410. 'I': 278,
  31411. 'J': 556,
  31412. 'K': 722,
  31413. 'L': 611,
  31414. 'M': 833,
  31415. 'N': 722,
  31416. 'O': 778,
  31417. 'P': 667,
  31418. 'Q': 778,
  31419. 'R': 722,
  31420. 'S': 667,
  31421. 'T': 611,
  31422. 'U': 722,
  31423. 'V': 667,
  31424. 'W': 944,
  31425. 'X': 667,
  31426. 'Y': 667,
  31427. 'Z': 611,
  31428. 'bracketleft': 333,
  31429. 'backslash': 278,
  31430. 'bracketright': 333,
  31431. 'asciicircum': 584,
  31432. 'underscore': 556,
  31433. 'quoteleft': 278,
  31434. 'a': 556,
  31435. 'b': 611,
  31436. 'c': 556,
  31437. 'd': 611,
  31438. 'e': 556,
  31439. 'f': 333,
  31440. 'g': 611,
  31441. 'h': 611,
  31442. 'i': 278,
  31443. 'j': 278,
  31444. 'k': 556,
  31445. 'l': 278,
  31446. 'm': 889,
  31447. 'n': 611,
  31448. 'o': 611,
  31449. 'p': 611,
  31450. 'q': 611,
  31451. 'r': 389,
  31452. 's': 556,
  31453. 't': 333,
  31454. 'u': 611,
  31455. 'v': 556,
  31456. 'w': 778,
  31457. 'x': 556,
  31458. 'y': 556,
  31459. 'z': 500,
  31460. 'braceleft': 389,
  31461. 'bar': 280,
  31462. 'braceright': 389,
  31463. 'asciitilde': 584,
  31464. 'exclamdown': 333,
  31465. 'cent': 556,
  31466. 'sterling': 556,
  31467. 'fraction': 167,
  31468. 'yen': 556,
  31469. 'florin': 556,
  31470. 'section': 556,
  31471. 'currency': 556,
  31472. 'quotesingle': 238,
  31473. 'quotedblleft': 500,
  31474. 'guillemotleft': 556,
  31475. 'guilsinglleft': 333,
  31476. 'guilsinglright': 333,
  31477. 'fi': 611,
  31478. 'fl': 611,
  31479. 'endash': 556,
  31480. 'dagger': 556,
  31481. 'daggerdbl': 556,
  31482. 'periodcentered': 278,
  31483. 'paragraph': 556,
  31484. 'bullet': 350,
  31485. 'quotesinglbase': 278,
  31486. 'quotedblbase': 500,
  31487. 'quotedblright': 500,
  31488. 'guillemotright': 556,
  31489. 'ellipsis': 1000,
  31490. 'perthousand': 1000,
  31491. 'questiondown': 611,
  31492. 'grave': 333,
  31493. 'acute': 333,
  31494. 'circumflex': 333,
  31495. 'tilde': 333,
  31496. 'macron': 333,
  31497. 'breve': 333,
  31498. 'dotaccent': 333,
  31499. 'dieresis': 333,
  31500. 'ring': 333,
  31501. 'cedilla': 333,
  31502. 'hungarumlaut': 333,
  31503. 'ogonek': 333,
  31504. 'caron': 333,
  31505. 'emdash': 1000,
  31506. 'AE': 1000,
  31507. 'ordfeminine': 370,
  31508. 'Lslash': 611,
  31509. 'Oslash': 778,
  31510. 'OE': 1000,
  31511. 'ordmasculine': 365,
  31512. 'ae': 889,
  31513. 'dotlessi': 278,
  31514. 'lslash': 278,
  31515. 'oslash': 611,
  31516. 'oe': 944,
  31517. 'germandbls': 611,
  31518. 'Idieresis': 278,
  31519. 'eacute': 556,
  31520. 'abreve': 556,
  31521. 'uhungarumlaut': 611,
  31522. 'ecaron': 556,
  31523. 'Ydieresis': 667,
  31524. 'divide': 584,
  31525. 'Yacute': 667,
  31526. 'Acircumflex': 722,
  31527. 'aacute': 556,
  31528. 'Ucircumflex': 722,
  31529. 'yacute': 556,
  31530. 'scommaaccent': 556,
  31531. 'ecircumflex': 556,
  31532. 'Uring': 722,
  31533. 'Udieresis': 722,
  31534. 'aogonek': 556,
  31535. 'Uacute': 722,
  31536. 'uogonek': 611,
  31537. 'Edieresis': 667,
  31538. 'Dcroat': 722,
  31539. 'commaaccent': 250,
  31540. 'copyright': 737,
  31541. 'Emacron': 667,
  31542. 'ccaron': 556,
  31543. 'aring': 556,
  31544. 'Ncommaaccent': 722,
  31545. 'lacute': 278,
  31546. 'agrave': 556,
  31547. 'Tcommaaccent': 611,
  31548. 'Cacute': 722,
  31549. 'atilde': 556,
  31550. 'Edotaccent': 667,
  31551. 'scaron': 556,
  31552. 'scedilla': 556,
  31553. 'iacute': 278,
  31554. 'lozenge': 494,
  31555. 'Rcaron': 722,
  31556. 'Gcommaaccent': 778,
  31557. 'ucircumflex': 611,
  31558. 'acircumflex': 556,
  31559. 'Amacron': 722,
  31560. 'rcaron': 389,
  31561. 'ccedilla': 556,
  31562. 'Zdotaccent': 611,
  31563. 'Thorn': 667,
  31564. 'Omacron': 778,
  31565. 'Racute': 722,
  31566. 'Sacute': 667,
  31567. 'dcaron': 743,
  31568. 'Umacron': 722,
  31569. 'uring': 611,
  31570. 'threesuperior': 333,
  31571. 'Ograve': 778,
  31572. 'Agrave': 722,
  31573. 'Abreve': 722,
  31574. 'multiply': 584,
  31575. 'uacute': 611,
  31576. 'Tcaron': 611,
  31577. 'partialdiff': 494,
  31578. 'ydieresis': 556,
  31579. 'Nacute': 722,
  31580. 'icircumflex': 278,
  31581. 'Ecircumflex': 667,
  31582. 'adieresis': 556,
  31583. 'edieresis': 556,
  31584. 'cacute': 556,
  31585. 'nacute': 611,
  31586. 'umacron': 611,
  31587. 'Ncaron': 722,
  31588. 'Iacute': 278,
  31589. 'plusminus': 584,
  31590. 'brokenbar': 280,
  31591. 'registered': 737,
  31592. 'Gbreve': 778,
  31593. 'Idotaccent': 278,
  31594. 'summation': 600,
  31595. 'Egrave': 667,
  31596. 'racute': 389,
  31597. 'omacron': 611,
  31598. 'Zacute': 611,
  31599. 'Zcaron': 611,
  31600. 'greaterequal': 549,
  31601. 'Eth': 722,
  31602. 'Ccedilla': 722,
  31603. 'lcommaaccent': 278,
  31604. 'tcaron': 389,
  31605. 'eogonek': 556,
  31606. 'Uogonek': 722,
  31607. 'Aacute': 722,
  31608. 'Adieresis': 722,
  31609. 'egrave': 556,
  31610. 'zacute': 500,
  31611. 'iogonek': 278,
  31612. 'Oacute': 778,
  31613. 'oacute': 611,
  31614. 'amacron': 556,
  31615. 'sacute': 556,
  31616. 'idieresis': 278,
  31617. 'Ocircumflex': 778,
  31618. 'Ugrave': 722,
  31619. 'Delta': 612,
  31620. 'thorn': 611,
  31621. 'twosuperior': 333,
  31622. 'Odieresis': 778,
  31623. 'mu': 611,
  31624. 'igrave': 278,
  31625. 'ohungarumlaut': 611,
  31626. 'Eogonek': 667,
  31627. 'dcroat': 611,
  31628. 'threequarters': 834,
  31629. 'Scedilla': 667,
  31630. 'lcaron': 400,
  31631. 'Kcommaaccent': 722,
  31632. 'Lacute': 611,
  31633. 'trademark': 1000,
  31634. 'edotaccent': 556,
  31635. 'Igrave': 278,
  31636. 'Imacron': 278,
  31637. 'Lcaron': 611,
  31638. 'onehalf': 834,
  31639. 'lessequal': 549,
  31640. 'ocircumflex': 611,
  31641. 'ntilde': 611,
  31642. 'Uhungarumlaut': 722,
  31643. 'Eacute': 667,
  31644. 'emacron': 556,
  31645. 'gbreve': 611,
  31646. 'onequarter': 834,
  31647. 'Scaron': 667,
  31648. 'Scommaaccent': 667,
  31649. 'Ohungarumlaut': 778,
  31650. 'degree': 400,
  31651. 'ograve': 611,
  31652. 'Ccaron': 722,
  31653. 'ugrave': 611,
  31654. 'radical': 549,
  31655. 'Dcaron': 722,
  31656. 'rcommaaccent': 389,
  31657. 'Ntilde': 722,
  31658. 'otilde': 611,
  31659. 'Rcommaaccent': 722,
  31660. 'Lcommaaccent': 611,
  31661. 'Atilde': 722,
  31662. 'Aogonek': 722,
  31663. 'Aring': 722,
  31664. 'Otilde': 778,
  31665. 'zdotaccent': 500,
  31666. 'Ecaron': 667,
  31667. 'Iogonek': 278,
  31668. 'kcommaaccent': 556,
  31669. 'minus': 584,
  31670. 'Icircumflex': 278,
  31671. 'ncaron': 611,
  31672. 'tcommaaccent': 333,
  31673. 'logicalnot': 584,
  31674. 'odieresis': 611,
  31675. 'udieresis': 611,
  31676. 'notequal': 549,
  31677. 'gcommaaccent': 611,
  31678. 'eth': 611,
  31679. 'zcaron': 500,
  31680. 'ncommaaccent': 611,
  31681. 'onesuperior': 333,
  31682. 'imacron': 278,
  31683. 'Euro': 556
  31684. },
  31685. 'Helvetica-Oblique' : {
  31686. 'space': 278,
  31687. 'exclam': 278,
  31688. 'quotedbl': 355,
  31689. 'numbersign': 556,
  31690. 'dollar': 556,
  31691. 'percent': 889,
  31692. 'ampersand': 667,
  31693. 'quoteright': 222,
  31694. 'parenleft': 333,
  31695. 'parenright': 333,
  31696. 'asterisk': 389,
  31697. 'plus': 584,
  31698. 'comma': 278,
  31699. 'hyphen': 333,
  31700. 'period': 278,
  31701. 'slash': 278,
  31702. 'zero': 556,
  31703. 'one': 556,
  31704. 'two': 556,
  31705. 'three': 556,
  31706. 'four': 556,
  31707. 'five': 556,
  31708. 'six': 556,
  31709. 'seven': 556,
  31710. 'eight': 556,
  31711. 'nine': 556,
  31712. 'colon': 278,
  31713. 'semicolon': 278,
  31714. 'less': 584,
  31715. 'equal': 584,
  31716. 'greater': 584,
  31717. 'question': 556,
  31718. 'at': 1015,
  31719. 'A': 667,
  31720. 'B': 667,
  31721. 'C': 722,
  31722. 'D': 722,
  31723. 'E': 667,
  31724. 'F': 611,
  31725. 'G': 778,
  31726. 'H': 722,
  31727. 'I': 278,
  31728. 'J': 500,
  31729. 'K': 667,
  31730. 'L': 556,
  31731. 'M': 833,
  31732. 'N': 722,
  31733. 'O': 778,
  31734. 'P': 667,
  31735. 'Q': 778,
  31736. 'R': 722,
  31737. 'S': 667,
  31738. 'T': 611,
  31739. 'U': 722,
  31740. 'V': 667,
  31741. 'W': 944,
  31742. 'X': 667,
  31743. 'Y': 667,
  31744. 'Z': 611,
  31745. 'bracketleft': 278,
  31746. 'backslash': 278,
  31747. 'bracketright': 278,
  31748. 'asciicircum': 469,
  31749. 'underscore': 556,
  31750. 'quoteleft': 222,
  31751. 'a': 556,
  31752. 'b': 556,
  31753. 'c': 500,
  31754. 'd': 556,
  31755. 'e': 556,
  31756. 'f': 278,
  31757. 'g': 556,
  31758. 'h': 556,
  31759. 'i': 222,
  31760. 'j': 222,
  31761. 'k': 500,
  31762. 'l': 222,
  31763. 'm': 833,
  31764. 'n': 556,
  31765. 'o': 556,
  31766. 'p': 556,
  31767. 'q': 556,
  31768. 'r': 333,
  31769. 's': 500,
  31770. 't': 278,
  31771. 'u': 556,
  31772. 'v': 500,
  31773. 'w': 722,
  31774. 'x': 500,
  31775. 'y': 500,
  31776. 'z': 500,
  31777. 'braceleft': 334,
  31778. 'bar': 260,
  31779. 'braceright': 334,
  31780. 'asciitilde': 584,
  31781. 'exclamdown': 333,
  31782. 'cent': 556,
  31783. 'sterling': 556,
  31784. 'fraction': 167,
  31785. 'yen': 556,
  31786. 'florin': 556,
  31787. 'section': 556,
  31788. 'currency': 556,
  31789. 'quotesingle': 191,
  31790. 'quotedblleft': 333,
  31791. 'guillemotleft': 556,
  31792. 'guilsinglleft': 333,
  31793. 'guilsinglright': 333,
  31794. 'fi': 500,
  31795. 'fl': 500,
  31796. 'endash': 556,
  31797. 'dagger': 556,
  31798. 'daggerdbl': 556,
  31799. 'periodcentered': 278,
  31800. 'paragraph': 537,
  31801. 'bullet': 350,
  31802. 'quotesinglbase': 222,
  31803. 'quotedblbase': 333,
  31804. 'quotedblright': 333,
  31805. 'guillemotright': 556,
  31806. 'ellipsis': 1000,
  31807. 'perthousand': 1000,
  31808. 'questiondown': 611,
  31809. 'grave': 333,
  31810. 'acute': 333,
  31811. 'circumflex': 333,
  31812. 'tilde': 333,
  31813. 'macron': 333,
  31814. 'breve': 333,
  31815. 'dotaccent': 333,
  31816. 'dieresis': 333,
  31817. 'ring': 333,
  31818. 'cedilla': 333,
  31819. 'hungarumlaut': 333,
  31820. 'ogonek': 333,
  31821. 'caron': 333,
  31822. 'emdash': 1000,
  31823. 'AE': 1000,
  31824. 'ordfeminine': 370,
  31825. 'Lslash': 556,
  31826. 'Oslash': 778,
  31827. 'OE': 1000,
  31828. 'ordmasculine': 365,
  31829. 'ae': 889,
  31830. 'dotlessi': 278,
  31831. 'lslash': 222,
  31832. 'oslash': 611,
  31833. 'oe': 944,
  31834. 'germandbls': 611,
  31835. 'Idieresis': 278,
  31836. 'eacute': 556,
  31837. 'abreve': 556,
  31838. 'uhungarumlaut': 556,
  31839. 'ecaron': 556,
  31840. 'Ydieresis': 667,
  31841. 'divide': 584,
  31842. 'Yacute': 667,
  31843. 'Acircumflex': 667,
  31844. 'aacute': 556,
  31845. 'Ucircumflex': 722,
  31846. 'yacute': 500,
  31847. 'scommaaccent': 500,
  31848. 'ecircumflex': 556,
  31849. 'Uring': 722,
  31850. 'Udieresis': 722,
  31851. 'aogonek': 556,
  31852. 'Uacute': 722,
  31853. 'uogonek': 556,
  31854. 'Edieresis': 667,
  31855. 'Dcroat': 722,
  31856. 'commaaccent': 250,
  31857. 'copyright': 737,
  31858. 'Emacron': 667,
  31859. 'ccaron': 500,
  31860. 'aring': 556,
  31861. 'Ncommaaccent': 722,
  31862. 'lacute': 222,
  31863. 'agrave': 556,
  31864. 'Tcommaaccent': 611,
  31865. 'Cacute': 722,
  31866. 'atilde': 556,
  31867. 'Edotaccent': 667,
  31868. 'scaron': 500,
  31869. 'scedilla': 500,
  31870. 'iacute': 278,
  31871. 'lozenge': 471,
  31872. 'Rcaron': 722,
  31873. 'Gcommaaccent': 778,
  31874. 'ucircumflex': 556,
  31875. 'acircumflex': 556,
  31876. 'Amacron': 667,
  31877. 'rcaron': 333,
  31878. 'ccedilla': 500,
  31879. 'Zdotaccent': 611,
  31880. 'Thorn': 667,
  31881. 'Omacron': 778,
  31882. 'Racute': 722,
  31883. 'Sacute': 667,
  31884. 'dcaron': 643,
  31885. 'Umacron': 722,
  31886. 'uring': 556,
  31887. 'threesuperior': 333,
  31888. 'Ograve': 778,
  31889. 'Agrave': 667,
  31890. 'Abreve': 667,
  31891. 'multiply': 584,
  31892. 'uacute': 556,
  31893. 'Tcaron': 611,
  31894. 'partialdiff': 476,
  31895. 'ydieresis': 500,
  31896. 'Nacute': 722,
  31897. 'icircumflex': 278,
  31898. 'Ecircumflex': 667,
  31899. 'adieresis': 556,
  31900. 'edieresis': 556,
  31901. 'cacute': 500,
  31902. 'nacute': 556,
  31903. 'umacron': 556,
  31904. 'Ncaron': 722,
  31905. 'Iacute': 278,
  31906. 'plusminus': 584,
  31907. 'brokenbar': 260,
  31908. 'registered': 737,
  31909. 'Gbreve': 778,
  31910. 'Idotaccent': 278,
  31911. 'summation': 600,
  31912. 'Egrave': 667,
  31913. 'racute': 333,
  31914. 'omacron': 556,
  31915. 'Zacute': 611,
  31916. 'Zcaron': 611,
  31917. 'greaterequal': 549,
  31918. 'Eth': 722,
  31919. 'Ccedilla': 722,
  31920. 'lcommaaccent': 222,
  31921. 'tcaron': 317,
  31922. 'eogonek': 556,
  31923. 'Uogonek': 722,
  31924. 'Aacute': 667,
  31925. 'Adieresis': 667,
  31926. 'egrave': 556,
  31927. 'zacute': 500,
  31928. 'iogonek': 222,
  31929. 'Oacute': 778,
  31930. 'oacute': 556,
  31931. 'amacron': 556,
  31932. 'sacute': 500,
  31933. 'idieresis': 278,
  31934. 'Ocircumflex': 778,
  31935. 'Ugrave': 722,
  31936. 'Delta': 612,
  31937. 'thorn': 556,
  31938. 'twosuperior': 333,
  31939. 'Odieresis': 778,
  31940. 'mu': 556,
  31941. 'igrave': 278,
  31942. 'ohungarumlaut': 556,
  31943. 'Eogonek': 667,
  31944. 'dcroat': 556,
  31945. 'threequarters': 834,
  31946. 'Scedilla': 667,
  31947. 'lcaron': 299,
  31948. 'Kcommaaccent': 667,
  31949. 'Lacute': 556,
  31950. 'trademark': 1000,
  31951. 'edotaccent': 556,
  31952. 'Igrave': 278,
  31953. 'Imacron': 278,
  31954. 'Lcaron': 556,
  31955. 'onehalf': 834,
  31956. 'lessequal': 549,
  31957. 'ocircumflex': 556,
  31958. 'ntilde': 556,
  31959. 'Uhungarumlaut': 722,
  31960. 'Eacute': 667,
  31961. 'emacron': 556,
  31962. 'gbreve': 556,
  31963. 'onequarter': 834,
  31964. 'Scaron': 667,
  31965. 'Scommaaccent': 667,
  31966. 'Ohungarumlaut': 778,
  31967. 'degree': 400,
  31968. 'ograve': 556,
  31969. 'Ccaron': 722,
  31970. 'ugrave': 556,
  31971. 'radical': 453,
  31972. 'Dcaron': 722,
  31973. 'rcommaaccent': 333,
  31974. 'Ntilde': 722,
  31975. 'otilde': 556,
  31976. 'Rcommaaccent': 722,
  31977. 'Lcommaaccent': 556,
  31978. 'Atilde': 667,
  31979. 'Aogonek': 667,
  31980. 'Aring': 667,
  31981. 'Otilde': 778,
  31982. 'zdotaccent': 500,
  31983. 'Ecaron': 667,
  31984. 'Iogonek': 278,
  31985. 'kcommaaccent': 500,
  31986. 'minus': 584,
  31987. 'Icircumflex': 278,
  31988. 'ncaron': 556,
  31989. 'tcommaaccent': 278,
  31990. 'logicalnot': 584,
  31991. 'odieresis': 556,
  31992. 'udieresis': 556,
  31993. 'notequal': 549,
  31994. 'gcommaaccent': 556,
  31995. 'eth': 556,
  31996. 'zcaron': 500,
  31997. 'ncommaaccent': 556,
  31998. 'onesuperior': 333,
  31999. 'imacron': 278,
  32000. 'Euro': 556
  32001. },
  32002. 'Symbol': {
  32003. 'space': 250,
  32004. 'exclam': 333,
  32005. 'universal': 713,
  32006. 'numbersign': 500,
  32007. 'existential': 549,
  32008. 'percent': 833,
  32009. 'ampersand': 778,
  32010. 'suchthat': 439,
  32011. 'parenleft': 333,
  32012. 'parenright': 333,
  32013. 'asteriskmath': 500,
  32014. 'plus': 549,
  32015. 'comma': 250,
  32016. 'minus': 549,
  32017. 'period': 250,
  32018. 'slash': 278,
  32019. 'zero': 500,
  32020. 'one': 500,
  32021. 'two': 500,
  32022. 'three': 500,
  32023. 'four': 500,
  32024. 'five': 500,
  32025. 'six': 500,
  32026. 'seven': 500,
  32027. 'eight': 500,
  32028. 'nine': 500,
  32029. 'colon': 278,
  32030. 'semicolon': 278,
  32031. 'less': 549,
  32032. 'equal': 549,
  32033. 'greater': 549,
  32034. 'question': 444,
  32035. 'congruent': 549,
  32036. 'Alpha': 722,
  32037. 'Beta': 667,
  32038. 'Chi': 722,
  32039. 'Delta': 612,
  32040. 'Epsilon': 611,
  32041. 'Phi': 763,
  32042. 'Gamma': 603,
  32043. 'Eta': 722,
  32044. 'Iota': 333,
  32045. 'theta1': 631,
  32046. 'Kappa': 722,
  32047. 'Lambda': 686,
  32048. 'Mu': 889,
  32049. 'Nu': 722,
  32050. 'Omicron': 722,
  32051. 'Pi': 768,
  32052. 'Theta': 741,
  32053. 'Rho': 556,
  32054. 'Sigma': 592,
  32055. 'Tau': 611,
  32056. 'Upsilon': 690,
  32057. 'sigma1': 439,
  32058. 'Omega': 768,
  32059. 'Xi': 645,
  32060. 'Psi': 795,
  32061. 'Zeta': 611,
  32062. 'bracketleft': 333,
  32063. 'therefore': 863,
  32064. 'bracketright': 333,
  32065. 'perpendicular': 658,
  32066. 'underscore': 500,
  32067. 'radicalex': 500,
  32068. 'alpha': 631,
  32069. 'beta': 549,
  32070. 'chi': 549,
  32071. 'delta': 494,
  32072. 'epsilon': 439,
  32073. 'phi': 521,
  32074. 'gamma': 411,
  32075. 'eta': 603,
  32076. 'iota': 329,
  32077. 'phi1': 603,
  32078. 'kappa': 549,
  32079. 'lambda': 549,
  32080. 'mu': 576,
  32081. 'nu': 521,
  32082. 'omicron': 549,
  32083. 'pi': 549,
  32084. 'theta': 521,
  32085. 'rho': 549,
  32086. 'sigma': 603,
  32087. 'tau': 439,
  32088. 'upsilon': 576,
  32089. 'omega1': 713,
  32090. 'omega': 686,
  32091. 'xi': 493,
  32092. 'psi': 686,
  32093. 'zeta': 494,
  32094. 'braceleft': 480,
  32095. 'bar': 200,
  32096. 'braceright': 480,
  32097. 'similar': 549,
  32098. 'Euro': 750,
  32099. 'Upsilon1': 620,
  32100. 'minute': 247,
  32101. 'lessequal': 549,
  32102. 'fraction': 167,
  32103. 'infinity': 713,
  32104. 'florin': 500,
  32105. 'club': 753,
  32106. 'diamond': 753,
  32107. 'heart': 753,
  32108. 'spade': 753,
  32109. 'arrowboth': 1042,
  32110. 'arrowleft': 987,
  32111. 'arrowup': 603,
  32112. 'arrowright': 987,
  32113. 'arrowdown': 603,
  32114. 'degree': 400,
  32115. 'plusminus': 549,
  32116. 'second': 411,
  32117. 'greaterequal': 549,
  32118. 'multiply': 549,
  32119. 'proportional': 713,
  32120. 'partialdiff': 494,
  32121. 'bullet': 460,
  32122. 'divide': 549,
  32123. 'notequal': 549,
  32124. 'equivalence': 549,
  32125. 'approxequal': 549,
  32126. 'ellipsis': 1000,
  32127. 'arrowvertex': 603,
  32128. 'arrowhorizex': 1000,
  32129. 'carriagereturn': 658,
  32130. 'aleph': 823,
  32131. 'Ifraktur': 686,
  32132. 'Rfraktur': 795,
  32133. 'weierstrass': 987,
  32134. 'circlemultiply': 768,
  32135. 'circleplus': 768,
  32136. 'emptyset': 823,
  32137. 'intersection': 768,
  32138. 'union': 768,
  32139. 'propersuperset': 713,
  32140. 'reflexsuperset': 713,
  32141. 'notsubset': 713,
  32142. 'propersubset': 713,
  32143. 'reflexsubset': 713,
  32144. 'element': 713,
  32145. 'notelement': 713,
  32146. 'angle': 768,
  32147. 'gradient': 713,
  32148. 'registerserif': 790,
  32149. 'copyrightserif': 790,
  32150. 'trademarkserif': 890,
  32151. 'product': 823,
  32152. 'radical': 549,
  32153. 'dotmath': 250,
  32154. 'logicalnot': 713,
  32155. 'logicaland': 603,
  32156. 'logicalor': 603,
  32157. 'arrowdblboth': 1042,
  32158. 'arrowdblleft': 987,
  32159. 'arrowdblup': 603,
  32160. 'arrowdblright': 987,
  32161. 'arrowdbldown': 603,
  32162. 'lozenge': 494,
  32163. 'angleleft': 329,
  32164. 'registersans': 790,
  32165. 'copyrightsans': 790,
  32166. 'trademarksans': 786,
  32167. 'summation': 713,
  32168. 'parenlefttp': 384,
  32169. 'parenleftex': 384,
  32170. 'parenleftbt': 384,
  32171. 'bracketlefttp': 384,
  32172. 'bracketleftex': 384,
  32173. 'bracketleftbt': 384,
  32174. 'bracelefttp': 494,
  32175. 'braceleftmid': 494,
  32176. 'braceleftbt': 494,
  32177. 'braceex': 494,
  32178. 'angleright': 329,
  32179. 'integral': 274,
  32180. 'integraltp': 686,
  32181. 'integralex': 686,
  32182. 'integralbt': 686,
  32183. 'parenrighttp': 384,
  32184. 'parenrightex': 384,
  32185. 'parenrightbt': 384,
  32186. 'bracketrighttp': 384,
  32187. 'bracketrightex': 384,
  32188. 'bracketrightbt': 384,
  32189. 'bracerighttp': 494,
  32190. 'bracerightmid': 494,
  32191. 'bracerightbt': 494,
  32192. 'apple': 790
  32193. },
  32194. 'Times-Roman': {
  32195. 'space': 250,
  32196. 'exclam': 333,
  32197. 'quotedbl': 408,
  32198. 'numbersign': 500,
  32199. 'dollar': 500,
  32200. 'percent': 833,
  32201. 'ampersand': 778,
  32202. 'quoteright': 333,
  32203. 'parenleft': 333,
  32204. 'parenright': 333,
  32205. 'asterisk': 500,
  32206. 'plus': 564,
  32207. 'comma': 250,
  32208. 'hyphen': 333,
  32209. 'period': 250,
  32210. 'slash': 278,
  32211. 'zero': 500,
  32212. 'one': 500,
  32213. 'two': 500,
  32214. 'three': 500,
  32215. 'four': 500,
  32216. 'five': 500,
  32217. 'six': 500,
  32218. 'seven': 500,
  32219. 'eight': 500,
  32220. 'nine': 500,
  32221. 'colon': 278,
  32222. 'semicolon': 278,
  32223. 'less': 564,
  32224. 'equal': 564,
  32225. 'greater': 564,
  32226. 'question': 444,
  32227. 'at': 921,
  32228. 'A': 722,
  32229. 'B': 667,
  32230. 'C': 667,
  32231. 'D': 722,
  32232. 'E': 611,
  32233. 'F': 556,
  32234. 'G': 722,
  32235. 'H': 722,
  32236. 'I': 333,
  32237. 'J': 389,
  32238. 'K': 722,
  32239. 'L': 611,
  32240. 'M': 889,
  32241. 'N': 722,
  32242. 'O': 722,
  32243. 'P': 556,
  32244. 'Q': 722,
  32245. 'R': 667,
  32246. 'S': 556,
  32247. 'T': 611,
  32248. 'U': 722,
  32249. 'V': 722,
  32250. 'W': 944,
  32251. 'X': 722,
  32252. 'Y': 722,
  32253. 'Z': 611,
  32254. 'bracketleft': 333,
  32255. 'backslash': 278,
  32256. 'bracketright': 333,
  32257. 'asciicircum': 469,
  32258. 'underscore': 500,
  32259. 'quoteleft': 333,
  32260. 'a': 444,
  32261. 'b': 500,
  32262. 'c': 444,
  32263. 'd': 500,
  32264. 'e': 444,
  32265. 'f': 333,
  32266. 'g': 500,
  32267. 'h': 500,
  32268. 'i': 278,
  32269. 'j': 278,
  32270. 'k': 500,
  32271. 'l': 278,
  32272. 'm': 778,
  32273. 'n': 500,
  32274. 'o': 500,
  32275. 'p': 500,
  32276. 'q': 500,
  32277. 'r': 333,
  32278. 's': 389,
  32279. 't': 278,
  32280. 'u': 500,
  32281. 'v': 500,
  32282. 'w': 722,
  32283. 'x': 500,
  32284. 'y': 500,
  32285. 'z': 444,
  32286. 'braceleft': 480,
  32287. 'bar': 200,
  32288. 'braceright': 480,
  32289. 'asciitilde': 541,
  32290. 'exclamdown': 333,
  32291. 'cent': 500,
  32292. 'sterling': 500,
  32293. 'fraction': 167,
  32294. 'yen': 500,
  32295. 'florin': 500,
  32296. 'section': 500,
  32297. 'currency': 500,
  32298. 'quotesingle': 180,
  32299. 'quotedblleft': 444,
  32300. 'guillemotleft': 500,
  32301. 'guilsinglleft': 333,
  32302. 'guilsinglright': 333,
  32303. 'fi': 556,
  32304. 'fl': 556,
  32305. 'endash': 500,
  32306. 'dagger': 500,
  32307. 'daggerdbl': 500,
  32308. 'periodcentered': 250,
  32309. 'paragraph': 453,
  32310. 'bullet': 350,
  32311. 'quotesinglbase': 333,
  32312. 'quotedblbase': 444,
  32313. 'quotedblright': 444,
  32314. 'guillemotright': 500,
  32315. 'ellipsis': 1000,
  32316. 'perthousand': 1000,
  32317. 'questiondown': 444,
  32318. 'grave': 333,
  32319. 'acute': 333,
  32320. 'circumflex': 333,
  32321. 'tilde': 333,
  32322. 'macron': 333,
  32323. 'breve': 333,
  32324. 'dotaccent': 333,
  32325. 'dieresis': 333,
  32326. 'ring': 333,
  32327. 'cedilla': 333,
  32328. 'hungarumlaut': 333,
  32329. 'ogonek': 333,
  32330. 'caron': 333,
  32331. 'emdash': 1000,
  32332. 'AE': 889,
  32333. 'ordfeminine': 276,
  32334. 'Lslash': 611,
  32335. 'Oslash': 722,
  32336. 'OE': 889,
  32337. 'ordmasculine': 310,
  32338. 'ae': 667,
  32339. 'dotlessi': 278,
  32340. 'lslash': 278,
  32341. 'oslash': 500,
  32342. 'oe': 722,
  32343. 'germandbls': 500,
  32344. 'Idieresis': 333,
  32345. 'eacute': 444,
  32346. 'abreve': 444,
  32347. 'uhungarumlaut': 500,
  32348. 'ecaron': 444,
  32349. 'Ydieresis': 722,
  32350. 'divide': 564,
  32351. 'Yacute': 722,
  32352. 'Acircumflex': 722,
  32353. 'aacute': 444,
  32354. 'Ucircumflex': 722,
  32355. 'yacute': 500,
  32356. 'scommaaccent': 389,
  32357. 'ecircumflex': 444,
  32358. 'Uring': 722,
  32359. 'Udieresis': 722,
  32360. 'aogonek': 444,
  32361. 'Uacute': 722,
  32362. 'uogonek': 500,
  32363. 'Edieresis': 611,
  32364. 'Dcroat': 722,
  32365. 'commaaccent': 250,
  32366. 'copyright': 760,
  32367. 'Emacron': 611,
  32368. 'ccaron': 444,
  32369. 'aring': 444,
  32370. 'Ncommaaccent': 722,
  32371. 'lacute': 278,
  32372. 'agrave': 444,
  32373. 'Tcommaaccent': 611,
  32374. 'Cacute': 667,
  32375. 'atilde': 444,
  32376. 'Edotaccent': 611,
  32377. 'scaron': 389,
  32378. 'scedilla': 389,
  32379. 'iacute': 278,
  32380. 'lozenge': 471,
  32381. 'Rcaron': 667,
  32382. 'Gcommaaccent': 722,
  32383. 'ucircumflex': 500,
  32384. 'acircumflex': 444,
  32385. 'Amacron': 722,
  32386. 'rcaron': 333,
  32387. 'ccedilla': 444,
  32388. 'Zdotaccent': 611,
  32389. 'Thorn': 556,
  32390. 'Omacron': 722,
  32391. 'Racute': 667,
  32392. 'Sacute': 556,
  32393. 'dcaron': 588,
  32394. 'Umacron': 722,
  32395. 'uring': 500,
  32396. 'threesuperior': 300,
  32397. 'Ograve': 722,
  32398. 'Agrave': 722,
  32399. 'Abreve': 722,
  32400. 'multiply': 564,
  32401. 'uacute': 500,
  32402. 'Tcaron': 611,
  32403. 'partialdiff': 476,
  32404. 'ydieresis': 500,
  32405. 'Nacute': 722,
  32406. 'icircumflex': 278,
  32407. 'Ecircumflex': 611,
  32408. 'adieresis': 444,
  32409. 'edieresis': 444,
  32410. 'cacute': 444,
  32411. 'nacute': 500,
  32412. 'umacron': 500,
  32413. 'Ncaron': 722,
  32414. 'Iacute': 333,
  32415. 'plusminus': 564,
  32416. 'brokenbar': 200,
  32417. 'registered': 760,
  32418. 'Gbreve': 722,
  32419. 'Idotaccent': 333,
  32420. 'summation': 600,
  32421. 'Egrave': 611,
  32422. 'racute': 333,
  32423. 'omacron': 500,
  32424. 'Zacute': 611,
  32425. 'Zcaron': 611,
  32426. 'greaterequal': 549,
  32427. 'Eth': 722,
  32428. 'Ccedilla': 667,
  32429. 'lcommaaccent': 278,
  32430. 'tcaron': 326,
  32431. 'eogonek': 444,
  32432. 'Uogonek': 722,
  32433. 'Aacute': 722,
  32434. 'Adieresis': 722,
  32435. 'egrave': 444,
  32436. 'zacute': 444,
  32437. 'iogonek': 278,
  32438. 'Oacute': 722,
  32439. 'oacute': 500,
  32440. 'amacron': 444,
  32441. 'sacute': 389,
  32442. 'idieresis': 278,
  32443. 'Ocircumflex': 722,
  32444. 'Ugrave': 722,
  32445. 'Delta': 612,
  32446. 'thorn': 500,
  32447. 'twosuperior': 300,
  32448. 'Odieresis': 722,
  32449. 'mu': 500,
  32450. 'igrave': 278,
  32451. 'ohungarumlaut': 500,
  32452. 'Eogonek': 611,
  32453. 'dcroat': 500,
  32454. 'threequarters': 750,
  32455. 'Scedilla': 556,
  32456. 'lcaron': 344,
  32457. 'Kcommaaccent': 722,
  32458. 'Lacute': 611,
  32459. 'trademark': 980,
  32460. 'edotaccent': 444,
  32461. 'Igrave': 333,
  32462. 'Imacron': 333,
  32463. 'Lcaron': 611,
  32464. 'onehalf': 750,
  32465. 'lessequal': 549,
  32466. 'ocircumflex': 500,
  32467. 'ntilde': 500,
  32468. 'Uhungarumlaut': 722,
  32469. 'Eacute': 611,
  32470. 'emacron': 444,
  32471. 'gbreve': 500,
  32472. 'onequarter': 750,
  32473. 'Scaron': 556,
  32474. 'Scommaaccent': 556,
  32475. 'Ohungarumlaut': 722,
  32476. 'degree': 400,
  32477. 'ograve': 500,
  32478. 'Ccaron': 667,
  32479. 'ugrave': 500,
  32480. 'radical': 453,
  32481. 'Dcaron': 722,
  32482. 'rcommaaccent': 333,
  32483. 'Ntilde': 722,
  32484. 'otilde': 500,
  32485. 'Rcommaaccent': 667,
  32486. 'Lcommaaccent': 611,
  32487. 'Atilde': 722,
  32488. 'Aogonek': 722,
  32489. 'Aring': 722,
  32490. 'Otilde': 722,
  32491. 'zdotaccent': 444,
  32492. 'Ecaron': 611,
  32493. 'Iogonek': 333,
  32494. 'kcommaaccent': 500,
  32495. 'minus': 564,
  32496. 'Icircumflex': 333,
  32497. 'ncaron': 500,
  32498. 'tcommaaccent': 278,
  32499. 'logicalnot': 564,
  32500. 'odieresis': 500,
  32501. 'udieresis': 500,
  32502. 'notequal': 549,
  32503. 'gcommaaccent': 500,
  32504. 'eth': 500,
  32505. 'zcaron': 444,
  32506. 'ncommaaccent': 500,
  32507. 'onesuperior': 300,
  32508. 'imacron': 278,
  32509. 'Euro': 500
  32510. },
  32511. 'Times-Bold': {
  32512. 'space': 250,
  32513. 'exclam': 333,
  32514. 'quotedbl': 555,
  32515. 'numbersign': 500,
  32516. 'dollar': 500,
  32517. 'percent': 1000,
  32518. 'ampersand': 833,
  32519. 'quoteright': 333,
  32520. 'parenleft': 333,
  32521. 'parenright': 333,
  32522. 'asterisk': 500,
  32523. 'plus': 570,
  32524. 'comma': 250,
  32525. 'hyphen': 333,
  32526. 'period': 250,
  32527. 'slash': 278,
  32528. 'zero': 500,
  32529. 'one': 500,
  32530. 'two': 500,
  32531. 'three': 500,
  32532. 'four': 500,
  32533. 'five': 500,
  32534. 'six': 500,
  32535. 'seven': 500,
  32536. 'eight': 500,
  32537. 'nine': 500,
  32538. 'colon': 333,
  32539. 'semicolon': 333,
  32540. 'less': 570,
  32541. 'equal': 570,
  32542. 'greater': 570,
  32543. 'question': 500,
  32544. 'at': 930,
  32545. 'A': 722,
  32546. 'B': 667,
  32547. 'C': 722,
  32548. 'D': 722,
  32549. 'E': 667,
  32550. 'F': 611,
  32551. 'G': 778,
  32552. 'H': 778,
  32553. 'I': 389,
  32554. 'J': 500,
  32555. 'K': 778,
  32556. 'L': 667,
  32557. 'M': 944,
  32558. 'N': 722,
  32559. 'O': 778,
  32560. 'P': 611,
  32561. 'Q': 778,
  32562. 'R': 722,
  32563. 'S': 556,
  32564. 'T': 667,
  32565. 'U': 722,
  32566. 'V': 722,
  32567. 'W': 1000,
  32568. 'X': 722,
  32569. 'Y': 722,
  32570. 'Z': 667,
  32571. 'bracketleft': 333,
  32572. 'backslash': 278,
  32573. 'bracketright': 333,
  32574. 'asciicircum': 581,
  32575. 'underscore': 500,
  32576. 'quoteleft': 333,
  32577. 'a': 500,
  32578. 'b': 556,
  32579. 'c': 444,
  32580. 'd': 556,
  32581. 'e': 444,
  32582. 'f': 333,
  32583. 'g': 500,
  32584. 'h': 556,
  32585. 'i': 278,
  32586. 'j': 333,
  32587. 'k': 556,
  32588. 'l': 278,
  32589. 'm': 833,
  32590. 'n': 556,
  32591. 'o': 500,
  32592. 'p': 556,
  32593. 'q': 556,
  32594. 'r': 444,
  32595. 's': 389,
  32596. 't': 333,
  32597. 'u': 556,
  32598. 'v': 500,
  32599. 'w': 722,
  32600. 'x': 500,
  32601. 'y': 500,
  32602. 'z': 444,
  32603. 'braceleft': 394,
  32604. 'bar': 220,
  32605. 'braceright': 394,
  32606. 'asciitilde': 520,
  32607. 'exclamdown': 333,
  32608. 'cent': 500,
  32609. 'sterling': 500,
  32610. 'fraction': 167,
  32611. 'yen': 500,
  32612. 'florin': 500,
  32613. 'section': 500,
  32614. 'currency': 500,
  32615. 'quotesingle': 278,
  32616. 'quotedblleft': 500,
  32617. 'guillemotleft': 500,
  32618. 'guilsinglleft': 333,
  32619. 'guilsinglright': 333,
  32620. 'fi': 556,
  32621. 'fl': 556,
  32622. 'endash': 500,
  32623. 'dagger': 500,
  32624. 'daggerdbl': 500,
  32625. 'periodcentered': 250,
  32626. 'paragraph': 540,
  32627. 'bullet': 350,
  32628. 'quotesinglbase': 333,
  32629. 'quotedblbase': 500,
  32630. 'quotedblright': 500,
  32631. 'guillemotright': 500,
  32632. 'ellipsis': 1000,
  32633. 'perthousand': 1000,
  32634. 'questiondown': 500,
  32635. 'grave': 333,
  32636. 'acute': 333,
  32637. 'circumflex': 333,
  32638. 'tilde': 333,
  32639. 'macron': 333,
  32640. 'breve': 333,
  32641. 'dotaccent': 333,
  32642. 'dieresis': 333,
  32643. 'ring': 333,
  32644. 'cedilla': 333,
  32645. 'hungarumlaut': 333,
  32646. 'ogonek': 333,
  32647. 'caron': 333,
  32648. 'emdash': 1000,
  32649. 'AE': 1000,
  32650. 'ordfeminine': 300,
  32651. 'Lslash': 667,
  32652. 'Oslash': 778,
  32653. 'OE': 1000,
  32654. 'ordmasculine': 330,
  32655. 'ae': 722,
  32656. 'dotlessi': 278,
  32657. 'lslash': 278,
  32658. 'oslash': 500,
  32659. 'oe': 722,
  32660. 'germandbls': 556,
  32661. 'Idieresis': 389,
  32662. 'eacute': 444,
  32663. 'abreve': 500,
  32664. 'uhungarumlaut': 556,
  32665. 'ecaron': 444,
  32666. 'Ydieresis': 722,
  32667. 'divide': 570,
  32668. 'Yacute': 722,
  32669. 'Acircumflex': 722,
  32670. 'aacute': 500,
  32671. 'Ucircumflex': 722,
  32672. 'yacute': 500,
  32673. 'scommaaccent': 389,
  32674. 'ecircumflex': 444,
  32675. 'Uring': 722,
  32676. 'Udieresis': 722,
  32677. 'aogonek': 500,
  32678. 'Uacute': 722,
  32679. 'uogonek': 556,
  32680. 'Edieresis': 667,
  32681. 'Dcroat': 722,
  32682. 'commaaccent': 250,
  32683. 'copyright': 747,
  32684. 'Emacron': 667,
  32685. 'ccaron': 444,
  32686. 'aring': 500,
  32687. 'Ncommaaccent': 722,
  32688. 'lacute': 278,
  32689. 'agrave': 500,
  32690. 'Tcommaaccent': 667,
  32691. 'Cacute': 722,
  32692. 'atilde': 500,
  32693. 'Edotaccent': 667,
  32694. 'scaron': 389,
  32695. 'scedilla': 389,
  32696. 'iacute': 278,
  32697. 'lozenge': 494,
  32698. 'Rcaron': 722,
  32699. 'Gcommaaccent': 778,
  32700. 'ucircumflex': 556,
  32701. 'acircumflex': 500,
  32702. 'Amacron': 722,
  32703. 'rcaron': 444,
  32704. 'ccedilla': 444,
  32705. 'Zdotaccent': 667,
  32706. 'Thorn': 611,
  32707. 'Omacron': 778,
  32708. 'Racute': 722,
  32709. 'Sacute': 556,
  32710. 'dcaron': 672,
  32711. 'Umacron': 722,
  32712. 'uring': 556,
  32713. 'threesuperior': 300,
  32714. 'Ograve': 778,
  32715. 'Agrave': 722,
  32716. 'Abreve': 722,
  32717. 'multiply': 570,
  32718. 'uacute': 556,
  32719. 'Tcaron': 667,
  32720. 'partialdiff': 494,
  32721. 'ydieresis': 500,
  32722. 'Nacute': 722,
  32723. 'icircumflex': 278,
  32724. 'Ecircumflex': 667,
  32725. 'adieresis': 500,
  32726. 'edieresis': 444,
  32727. 'cacute': 444,
  32728. 'nacute': 556,
  32729. 'umacron': 556,
  32730. 'Ncaron': 722,
  32731. 'Iacute': 389,
  32732. 'plusminus': 570,
  32733. 'brokenbar': 220,
  32734. 'registered': 747,
  32735. 'Gbreve': 778,
  32736. 'Idotaccent': 389,
  32737. 'summation': 600,
  32738. 'Egrave': 667,
  32739. 'racute': 444,
  32740. 'omacron': 500,
  32741. 'Zacute': 667,
  32742. 'Zcaron': 667,
  32743. 'greaterequal': 549,
  32744. 'Eth': 722,
  32745. 'Ccedilla': 722,
  32746. 'lcommaaccent': 278,
  32747. 'tcaron': 416,
  32748. 'eogonek': 444,
  32749. 'Uogonek': 722,
  32750. 'Aacute': 722,
  32751. 'Adieresis': 722,
  32752. 'egrave': 444,
  32753. 'zacute': 444,
  32754. 'iogonek': 278,
  32755. 'Oacute': 778,
  32756. 'oacute': 500,
  32757. 'amacron': 500,
  32758. 'sacute': 389,
  32759. 'idieresis': 278,
  32760. 'Ocircumflex': 778,
  32761. 'Ugrave': 722,
  32762. 'Delta': 612,
  32763. 'thorn': 556,
  32764. 'twosuperior': 300,
  32765. 'Odieresis': 778,
  32766. 'mu': 556,
  32767. 'igrave': 278,
  32768. 'ohungarumlaut': 500,
  32769. 'Eogonek': 667,
  32770. 'dcroat': 556,
  32771. 'threequarters': 750,
  32772. 'Scedilla': 556,
  32773. 'lcaron': 394,
  32774. 'Kcommaaccent': 778,
  32775. 'Lacute': 667,
  32776. 'trademark': 1000,
  32777. 'edotaccent': 444,
  32778. 'Igrave': 389,
  32779. 'Imacron': 389,
  32780. 'Lcaron': 667,
  32781. 'onehalf': 750,
  32782. 'lessequal': 549,
  32783. 'ocircumflex': 500,
  32784. 'ntilde': 556,
  32785. 'Uhungarumlaut': 722,
  32786. 'Eacute': 667,
  32787. 'emacron': 444,
  32788. 'gbreve': 500,
  32789. 'onequarter': 750,
  32790. 'Scaron': 556,
  32791. 'Scommaaccent': 556,
  32792. 'Ohungarumlaut': 778,
  32793. 'degree': 400,
  32794. 'ograve': 500,
  32795. 'Ccaron': 722,
  32796. 'ugrave': 556,
  32797. 'radical': 549,
  32798. 'Dcaron': 722,
  32799. 'rcommaaccent': 444,
  32800. 'Ntilde': 722,
  32801. 'otilde': 500,
  32802. 'Rcommaaccent': 722,
  32803. 'Lcommaaccent': 667,
  32804. 'Atilde': 722,
  32805. 'Aogonek': 722,
  32806. 'Aring': 722,
  32807. 'Otilde': 778,
  32808. 'zdotaccent': 444,
  32809. 'Ecaron': 667,
  32810. 'Iogonek': 389,
  32811. 'kcommaaccent': 556,
  32812. 'minus': 570,
  32813. 'Icircumflex': 389,
  32814. 'ncaron': 556,
  32815. 'tcommaaccent': 333,
  32816. 'logicalnot': 570,
  32817. 'odieresis': 500,
  32818. 'udieresis': 556,
  32819. 'notequal': 549,
  32820. 'gcommaaccent': 500,
  32821. 'eth': 500,
  32822. 'zcaron': 444,
  32823. 'ncommaaccent': 556,
  32824. 'onesuperior': 300,
  32825. 'imacron': 278,
  32826. 'Euro': 500
  32827. },
  32828. 'Times-BoldItalic': {
  32829. 'space': 250,
  32830. 'exclam': 389,
  32831. 'quotedbl': 555,
  32832. 'numbersign': 500,
  32833. 'dollar': 500,
  32834. 'percent': 833,
  32835. 'ampersand': 778,
  32836. 'quoteright': 333,
  32837. 'parenleft': 333,
  32838. 'parenright': 333,
  32839. 'asterisk': 500,
  32840. 'plus': 570,
  32841. 'comma': 250,
  32842. 'hyphen': 333,
  32843. 'period': 250,
  32844. 'slash': 278,
  32845. 'zero': 500,
  32846. 'one': 500,
  32847. 'two': 500,
  32848. 'three': 500,
  32849. 'four': 500,
  32850. 'five': 500,
  32851. 'six': 500,
  32852. 'seven': 500,
  32853. 'eight': 500,
  32854. 'nine': 500,
  32855. 'colon': 333,
  32856. 'semicolon': 333,
  32857. 'less': 570,
  32858. 'equal': 570,
  32859. 'greater': 570,
  32860. 'question': 500,
  32861. 'at': 832,
  32862. 'A': 667,
  32863. 'B': 667,
  32864. 'C': 667,
  32865. 'D': 722,
  32866. 'E': 667,
  32867. 'F': 667,
  32868. 'G': 722,
  32869. 'H': 778,
  32870. 'I': 389,
  32871. 'J': 500,
  32872. 'K': 667,
  32873. 'L': 611,
  32874. 'M': 889,
  32875. 'N': 722,
  32876. 'O': 722,
  32877. 'P': 611,
  32878. 'Q': 722,
  32879. 'R': 667,
  32880. 'S': 556,
  32881. 'T': 611,
  32882. 'U': 722,
  32883. 'V': 667,
  32884. 'W': 889,
  32885. 'X': 667,
  32886. 'Y': 611,
  32887. 'Z': 611,
  32888. 'bracketleft': 333,
  32889. 'backslash': 278,
  32890. 'bracketright': 333,
  32891. 'asciicircum': 570,
  32892. 'underscore': 500,
  32893. 'quoteleft': 333,
  32894. 'a': 500,
  32895. 'b': 500,
  32896. 'c': 444,
  32897. 'd': 500,
  32898. 'e': 444,
  32899. 'f': 333,
  32900. 'g': 500,
  32901. 'h': 556,
  32902. 'i': 278,
  32903. 'j': 278,
  32904. 'k': 500,
  32905. 'l': 278,
  32906. 'm': 778,
  32907. 'n': 556,
  32908. 'o': 500,
  32909. 'p': 500,
  32910. 'q': 500,
  32911. 'r': 389,
  32912. 's': 389,
  32913. 't': 278,
  32914. 'u': 556,
  32915. 'v': 444,
  32916. 'w': 667,
  32917. 'x': 500,
  32918. 'y': 444,
  32919. 'z': 389,
  32920. 'braceleft': 348,
  32921. 'bar': 220,
  32922. 'braceright': 348,
  32923. 'asciitilde': 570,
  32924. 'exclamdown': 389,
  32925. 'cent': 500,
  32926. 'sterling': 500,
  32927. 'fraction': 167,
  32928. 'yen': 500,
  32929. 'florin': 500,
  32930. 'section': 500,
  32931. 'currency': 500,
  32932. 'quotesingle': 278,
  32933. 'quotedblleft': 500,
  32934. 'guillemotleft': 500,
  32935. 'guilsinglleft': 333,
  32936. 'guilsinglright': 333,
  32937. 'fi': 556,
  32938. 'fl': 556,
  32939. 'endash': 500,
  32940. 'dagger': 500,
  32941. 'daggerdbl': 500,
  32942. 'periodcentered': 250,
  32943. 'paragraph': 500,
  32944. 'bullet': 350,
  32945. 'quotesinglbase': 333,
  32946. 'quotedblbase': 500,
  32947. 'quotedblright': 500,
  32948. 'guillemotright': 500,
  32949. 'ellipsis': 1000,
  32950. 'perthousand': 1000,
  32951. 'questiondown': 500,
  32952. 'grave': 333,
  32953. 'acute': 333,
  32954. 'circumflex': 333,
  32955. 'tilde': 333,
  32956. 'macron': 333,
  32957. 'breve': 333,
  32958. 'dotaccent': 333,
  32959. 'dieresis': 333,
  32960. 'ring': 333,
  32961. 'cedilla': 333,
  32962. 'hungarumlaut': 333,
  32963. 'ogonek': 333,
  32964. 'caron': 333,
  32965. 'emdash': 1000,
  32966. 'AE': 944,
  32967. 'ordfeminine': 266,
  32968. 'Lslash': 611,
  32969. 'Oslash': 722,
  32970. 'OE': 944,
  32971. 'ordmasculine': 300,
  32972. 'ae': 722,
  32973. 'dotlessi': 278,
  32974. 'lslash': 278,
  32975. 'oslash': 500,
  32976. 'oe': 722,
  32977. 'germandbls': 500,
  32978. 'Idieresis': 389,
  32979. 'eacute': 444,
  32980. 'abreve': 500,
  32981. 'uhungarumlaut': 556,
  32982. 'ecaron': 444,
  32983. 'Ydieresis': 611,
  32984. 'divide': 570,
  32985. 'Yacute': 611,
  32986. 'Acircumflex': 667,
  32987. 'aacute': 500,
  32988. 'Ucircumflex': 722,
  32989. 'yacute': 444,
  32990. 'scommaaccent': 389,
  32991. 'ecircumflex': 444,
  32992. 'Uring': 722,
  32993. 'Udieresis': 722,
  32994. 'aogonek': 500,
  32995. 'Uacute': 722,
  32996. 'uogonek': 556,
  32997. 'Edieresis': 667,
  32998. 'Dcroat': 722,
  32999. 'commaaccent': 250,
  33000. 'copyright': 747,
  33001. 'Emacron': 667,
  33002. 'ccaron': 444,
  33003. 'aring': 500,
  33004. 'Ncommaaccent': 722,
  33005. 'lacute': 278,
  33006. 'agrave': 500,
  33007. 'Tcommaaccent': 611,
  33008. 'Cacute': 667,
  33009. 'atilde': 500,
  33010. 'Edotaccent': 667,
  33011. 'scaron': 389,
  33012. 'scedilla': 389,
  33013. 'iacute': 278,
  33014. 'lozenge': 494,
  33015. 'Rcaron': 667,
  33016. 'Gcommaaccent': 722,
  33017. 'ucircumflex': 556,
  33018. 'acircumflex': 500,
  33019. 'Amacron': 667,
  33020. 'rcaron': 389,
  33021. 'ccedilla': 444,
  33022. 'Zdotaccent': 611,
  33023. 'Thorn': 611,
  33024. 'Omacron': 722,
  33025. 'Racute': 667,
  33026. 'Sacute': 556,
  33027. 'dcaron': 608,
  33028. 'Umacron': 722,
  33029. 'uring': 556,
  33030. 'threesuperior': 300,
  33031. 'Ograve': 722,
  33032. 'Agrave': 667,
  33033. 'Abreve': 667,
  33034. 'multiply': 570,
  33035. 'uacute': 556,
  33036. 'Tcaron': 611,
  33037. 'partialdiff': 494,
  33038. 'ydieresis': 444,
  33039. 'Nacute': 722,
  33040. 'icircumflex': 278,
  33041. 'Ecircumflex': 667,
  33042. 'adieresis': 500,
  33043. 'edieresis': 444,
  33044. 'cacute': 444,
  33045. 'nacute': 556,
  33046. 'umacron': 556,
  33047. 'Ncaron': 722,
  33048. 'Iacute': 389,
  33049. 'plusminus': 570,
  33050. 'brokenbar': 220,
  33051. 'registered': 747,
  33052. 'Gbreve': 722,
  33053. 'Idotaccent': 389,
  33054. 'summation': 600,
  33055. 'Egrave': 667,
  33056. 'racute': 389,
  33057. 'omacron': 500,
  33058. 'Zacute': 611,
  33059. 'Zcaron': 611,
  33060. 'greaterequal': 549,
  33061. 'Eth': 722,
  33062. 'Ccedilla': 667,
  33063. 'lcommaaccent': 278,
  33064. 'tcaron': 366,
  33065. 'eogonek': 444,
  33066. 'Uogonek': 722,
  33067. 'Aacute': 667,
  33068. 'Adieresis': 667,
  33069. 'egrave': 444,
  33070. 'zacute': 389,
  33071. 'iogonek': 278,
  33072. 'Oacute': 722,
  33073. 'oacute': 500,
  33074. 'amacron': 500,
  33075. 'sacute': 389,
  33076. 'idieresis': 278,
  33077. 'Ocircumflex': 722,
  33078. 'Ugrave': 722,
  33079. 'Delta': 612,
  33080. 'thorn': 500,
  33081. 'twosuperior': 300,
  33082. 'Odieresis': 722,
  33083. 'mu': 576,
  33084. 'igrave': 278,
  33085. 'ohungarumlaut': 500,
  33086. 'Eogonek': 667,
  33087. 'dcroat': 500,
  33088. 'threequarters': 750,
  33089. 'Scedilla': 556,
  33090. 'lcaron': 382,
  33091. 'Kcommaaccent': 667,
  33092. 'Lacute': 611,
  33093. 'trademark': 1000,
  33094. 'edotaccent': 444,
  33095. 'Igrave': 389,
  33096. 'Imacron': 389,
  33097. 'Lcaron': 611,
  33098. 'onehalf': 750,
  33099. 'lessequal': 549,
  33100. 'ocircumflex': 500,
  33101. 'ntilde': 556,
  33102. 'Uhungarumlaut': 722,
  33103. 'Eacute': 667,
  33104. 'emacron': 444,
  33105. 'gbreve': 500,
  33106. 'onequarter': 750,
  33107. 'Scaron': 556,
  33108. 'Scommaaccent': 556,
  33109. 'Ohungarumlaut': 722,
  33110. 'degree': 400,
  33111. 'ograve': 500,
  33112. 'Ccaron': 667,
  33113. 'ugrave': 556,
  33114. 'radical': 549,
  33115. 'Dcaron': 722,
  33116. 'rcommaaccent': 389,
  33117. 'Ntilde': 722,
  33118. 'otilde': 500,
  33119. 'Rcommaaccent': 667,
  33120. 'Lcommaaccent': 611,
  33121. 'Atilde': 667,
  33122. 'Aogonek': 667,
  33123. 'Aring': 667,
  33124. 'Otilde': 722,
  33125. 'zdotaccent': 389,
  33126. 'Ecaron': 667,
  33127. 'Iogonek': 389,
  33128. 'kcommaaccent': 500,
  33129. 'minus': 606,
  33130. 'Icircumflex': 389,
  33131. 'ncaron': 556,
  33132. 'tcommaaccent': 278,
  33133. 'logicalnot': 606,
  33134. 'odieresis': 500,
  33135. 'udieresis': 556,
  33136. 'notequal': 549,
  33137. 'gcommaaccent': 500,
  33138. 'eth': 500,
  33139. 'zcaron': 389,
  33140. 'ncommaaccent': 556,
  33141. 'onesuperior': 300,
  33142. 'imacron': 278,
  33143. 'Euro': 500
  33144. },
  33145. 'Times-Italic': {
  33146. 'space': 250,
  33147. 'exclam': 333,
  33148. 'quotedbl': 420,
  33149. 'numbersign': 500,
  33150. 'dollar': 500,
  33151. 'percent': 833,
  33152. 'ampersand': 778,
  33153. 'quoteright': 333,
  33154. 'parenleft': 333,
  33155. 'parenright': 333,
  33156. 'asterisk': 500,
  33157. 'plus': 675,
  33158. 'comma': 250,
  33159. 'hyphen': 333,
  33160. 'period': 250,
  33161. 'slash': 278,
  33162. 'zero': 500,
  33163. 'one': 500,
  33164. 'two': 500,
  33165. 'three': 500,
  33166. 'four': 500,
  33167. 'five': 500,
  33168. 'six': 500,
  33169. 'seven': 500,
  33170. 'eight': 500,
  33171. 'nine': 500,
  33172. 'colon': 333,
  33173. 'semicolon': 333,
  33174. 'less': 675,
  33175. 'equal': 675,
  33176. 'greater': 675,
  33177. 'question': 500,
  33178. 'at': 920,
  33179. 'A': 611,
  33180. 'B': 611,
  33181. 'C': 667,
  33182. 'D': 722,
  33183. 'E': 611,
  33184. 'F': 611,
  33185. 'G': 722,
  33186. 'H': 722,
  33187. 'I': 333,
  33188. 'J': 444,
  33189. 'K': 667,
  33190. 'L': 556,
  33191. 'M': 833,
  33192. 'N': 667,
  33193. 'O': 722,
  33194. 'P': 611,
  33195. 'Q': 722,
  33196. 'R': 611,
  33197. 'S': 500,
  33198. 'T': 556,
  33199. 'U': 722,
  33200. 'V': 611,
  33201. 'W': 833,
  33202. 'X': 611,
  33203. 'Y': 556,
  33204. 'Z': 556,
  33205. 'bracketleft': 389,
  33206. 'backslash': 278,
  33207. 'bracketright': 389,
  33208. 'asciicircum': 422,
  33209. 'underscore': 500,
  33210. 'quoteleft': 333,
  33211. 'a': 500,
  33212. 'b': 500,
  33213. 'c': 444,
  33214. 'd': 500,
  33215. 'e': 444,
  33216. 'f': 278,
  33217. 'g': 500,
  33218. 'h': 500,
  33219. 'i': 278,
  33220. 'j': 278,
  33221. 'k': 444,
  33222. 'l': 278,
  33223. 'm': 722,
  33224. 'n': 500,
  33225. 'o': 500,
  33226. 'p': 500,
  33227. 'q': 500,
  33228. 'r': 389,
  33229. 's': 389,
  33230. 't': 278,
  33231. 'u': 500,
  33232. 'v': 444,
  33233. 'w': 667,
  33234. 'x': 444,
  33235. 'y': 444,
  33236. 'z': 389,
  33237. 'braceleft': 400,
  33238. 'bar': 275,
  33239. 'braceright': 400,
  33240. 'asciitilde': 541,
  33241. 'exclamdown': 389,
  33242. 'cent': 500,
  33243. 'sterling': 500,
  33244. 'fraction': 167,
  33245. 'yen': 500,
  33246. 'florin': 500,
  33247. 'section': 500,
  33248. 'currency': 500,
  33249. 'quotesingle': 214,
  33250. 'quotedblleft': 556,
  33251. 'guillemotleft': 500,
  33252. 'guilsinglleft': 333,
  33253. 'guilsinglright': 333,
  33254. 'fi': 500,
  33255. 'fl': 500,
  33256. 'endash': 500,
  33257. 'dagger': 500,
  33258. 'daggerdbl': 500,
  33259. 'periodcentered': 250,
  33260. 'paragraph': 523,
  33261. 'bullet': 350,
  33262. 'quotesinglbase': 333,
  33263. 'quotedblbase': 556,
  33264. 'quotedblright': 556,
  33265. 'guillemotright': 500,
  33266. 'ellipsis': 889,
  33267. 'perthousand': 1000,
  33268. 'questiondown': 500,
  33269. 'grave': 333,
  33270. 'acute': 333,
  33271. 'circumflex': 333,
  33272. 'tilde': 333,
  33273. 'macron': 333,
  33274. 'breve': 333,
  33275. 'dotaccent': 333,
  33276. 'dieresis': 333,
  33277. 'ring': 333,
  33278. 'cedilla': 333,
  33279. 'hungarumlaut': 333,
  33280. 'ogonek': 333,
  33281. 'caron': 333,
  33282. 'emdash': 889,
  33283. 'AE': 889,
  33284. 'ordfeminine': 276,
  33285. 'Lslash': 556,
  33286. 'Oslash': 722,
  33287. 'OE': 944,
  33288. 'ordmasculine': 310,
  33289. 'ae': 667,
  33290. 'dotlessi': 278,
  33291. 'lslash': 278,
  33292. 'oslash': 500,
  33293. 'oe': 667,
  33294. 'germandbls': 500,
  33295. 'Idieresis': 333,
  33296. 'eacute': 444,
  33297. 'abreve': 500,
  33298. 'uhungarumlaut': 500,
  33299. 'ecaron': 444,
  33300. 'Ydieresis': 556,
  33301. 'divide': 675,
  33302. 'Yacute': 556,
  33303. 'Acircumflex': 611,
  33304. 'aacute': 500,
  33305. 'Ucircumflex': 722,
  33306. 'yacute': 444,
  33307. 'scommaaccent': 389,
  33308. 'ecircumflex': 444,
  33309. 'Uring': 722,
  33310. 'Udieresis': 722,
  33311. 'aogonek': 500,
  33312. 'Uacute': 722,
  33313. 'uogonek': 500,
  33314. 'Edieresis': 611,
  33315. 'Dcroat': 722,
  33316. 'commaaccent': 250,
  33317. 'copyright': 760,
  33318. 'Emacron': 611,
  33319. 'ccaron': 444,
  33320. 'aring': 500,
  33321. 'Ncommaaccent': 667,
  33322. 'lacute': 278,
  33323. 'agrave': 500,
  33324. 'Tcommaaccent': 556,
  33325. 'Cacute': 667,
  33326. 'atilde': 500,
  33327. 'Edotaccent': 611,
  33328. 'scaron': 389,
  33329. 'scedilla': 389,
  33330. 'iacute': 278,
  33331. 'lozenge': 471,
  33332. 'Rcaron': 611,
  33333. 'Gcommaaccent': 722,
  33334. 'ucircumflex': 500,
  33335. 'acircumflex': 500,
  33336. 'Amacron': 611,
  33337. 'rcaron': 389,
  33338. 'ccedilla': 444,
  33339. 'Zdotaccent': 556,
  33340. 'Thorn': 611,
  33341. 'Omacron': 722,
  33342. 'Racute': 611,
  33343. 'Sacute': 500,
  33344. 'dcaron': 544,
  33345. 'Umacron': 722,
  33346. 'uring': 500,
  33347. 'threesuperior': 300,
  33348. 'Ograve': 722,
  33349. 'Agrave': 611,
  33350. 'Abreve': 611,
  33351. 'multiply': 675,
  33352. 'uacute': 500,
  33353. 'Tcaron': 556,
  33354. 'partialdiff': 476,
  33355. 'ydieresis': 444,
  33356. 'Nacute': 667,
  33357. 'icircumflex': 278,
  33358. 'Ecircumflex': 611,
  33359. 'adieresis': 500,
  33360. 'edieresis': 444,
  33361. 'cacute': 444,
  33362. 'nacute': 500,
  33363. 'umacron': 500,
  33364. 'Ncaron': 667,
  33365. 'Iacute': 333,
  33366. 'plusminus': 675,
  33367. 'brokenbar': 275,
  33368. 'registered': 760,
  33369. 'Gbreve': 722,
  33370. 'Idotaccent': 333,
  33371. 'summation': 600,
  33372. 'Egrave': 611,
  33373. 'racute': 389,
  33374. 'omacron': 500,
  33375. 'Zacute': 556,
  33376. 'Zcaron': 556,
  33377. 'greaterequal': 549,
  33378. 'Eth': 722,
  33379. 'Ccedilla': 667,
  33380. 'lcommaaccent': 278,
  33381. 'tcaron': 300,
  33382. 'eogonek': 444,
  33383. 'Uogonek': 722,
  33384. 'Aacute': 611,
  33385. 'Adieresis': 611,
  33386. 'egrave': 444,
  33387. 'zacute': 389,
  33388. 'iogonek': 278,
  33389. 'Oacute': 722,
  33390. 'oacute': 500,
  33391. 'amacron': 500,
  33392. 'sacute': 389,
  33393. 'idieresis': 278,
  33394. 'Ocircumflex': 722,
  33395. 'Ugrave': 722,
  33396. 'Delta': 612,
  33397. 'thorn': 500,
  33398. 'twosuperior': 300,
  33399. 'Odieresis': 722,
  33400. 'mu': 500,
  33401. 'igrave': 278,
  33402. 'ohungarumlaut': 500,
  33403. 'Eogonek': 611,
  33404. 'dcroat': 500,
  33405. 'threequarters': 750,
  33406. 'Scedilla': 500,
  33407. 'lcaron': 300,
  33408. 'Kcommaaccent': 667,
  33409. 'Lacute': 556,
  33410. 'trademark': 980,
  33411. 'edotaccent': 444,
  33412. 'Igrave': 333,
  33413. 'Imacron': 333,
  33414. 'Lcaron': 611,
  33415. 'onehalf': 750,
  33416. 'lessequal': 549,
  33417. 'ocircumflex': 500,
  33418. 'ntilde': 500,
  33419. 'Uhungarumlaut': 722,
  33420. 'Eacute': 611,
  33421. 'emacron': 444,
  33422. 'gbreve': 500,
  33423. 'onequarter': 750,
  33424. 'Scaron': 500,
  33425. 'Scommaaccent': 500,
  33426. 'Ohungarumlaut': 722,
  33427. 'degree': 400,
  33428. 'ograve': 500,
  33429. 'Ccaron': 667,
  33430. 'ugrave': 500,
  33431. 'radical': 453,
  33432. 'Dcaron': 722,
  33433. 'rcommaaccent': 389,
  33434. 'Ntilde': 667,
  33435. 'otilde': 500,
  33436. 'Rcommaaccent': 611,
  33437. 'Lcommaaccent': 556,
  33438. 'Atilde': 611,
  33439. 'Aogonek': 611,
  33440. 'Aring': 611,
  33441. 'Otilde': 722,
  33442. 'zdotaccent': 389,
  33443. 'Ecaron': 611,
  33444. 'Iogonek': 333,
  33445. 'kcommaaccent': 444,
  33446. 'minus': 675,
  33447. 'Icircumflex': 333,
  33448. 'ncaron': 500,
  33449. 'tcommaaccent': 278,
  33450. 'logicalnot': 675,
  33451. 'odieresis': 500,
  33452. 'udieresis': 500,
  33453. 'notequal': 549,
  33454. 'gcommaaccent': 500,
  33455. 'eth': 500,
  33456. 'zcaron': 389,
  33457. 'ncommaaccent': 500,
  33458. 'onesuperior': 300,
  33459. 'imacron': 278,
  33460. 'Euro': 500
  33461. },
  33462. 'ZapfDingbats': {
  33463. 'space': 278,
  33464. 'a1': 974,
  33465. 'a2': 961,
  33466. 'a202': 974,
  33467. 'a3': 980,
  33468. 'a4': 719,
  33469. 'a5': 789,
  33470. 'a119': 790,
  33471. 'a118': 791,
  33472. 'a117': 690,
  33473. 'a11': 960,
  33474. 'a12': 939,
  33475. 'a13': 549,
  33476. 'a14': 855,
  33477. 'a15': 911,
  33478. 'a16': 933,
  33479. 'a105': 911,
  33480. 'a17': 945,
  33481. 'a18': 974,
  33482. 'a19': 755,
  33483. 'a20': 846,
  33484. 'a21': 762,
  33485. 'a22': 761,
  33486. 'a23': 571,
  33487. 'a24': 677,
  33488. 'a25': 763,
  33489. 'a26': 760,
  33490. 'a27': 759,
  33491. 'a28': 754,
  33492. 'a6': 494,
  33493. 'a7': 552,
  33494. 'a8': 537,
  33495. 'a9': 577,
  33496. 'a10': 692,
  33497. 'a29': 786,
  33498. 'a30': 788,
  33499. 'a31': 788,
  33500. 'a32': 790,
  33501. 'a33': 793,
  33502. 'a34': 794,
  33503. 'a35': 816,
  33504. 'a36': 823,
  33505. 'a37': 789,
  33506. 'a38': 841,
  33507. 'a39': 823,
  33508. 'a40': 833,
  33509. 'a41': 816,
  33510. 'a42': 831,
  33511. 'a43': 923,
  33512. 'a44': 744,
  33513. 'a45': 723,
  33514. 'a46': 749,
  33515. 'a47': 790,
  33516. 'a48': 792,
  33517. 'a49': 695,
  33518. 'a50': 776,
  33519. 'a51': 768,
  33520. 'a52': 792,
  33521. 'a53': 759,
  33522. 'a54': 707,
  33523. 'a55': 708,
  33524. 'a56': 682,
  33525. 'a57': 701,
  33526. 'a58': 826,
  33527. 'a59': 815,
  33528. 'a60': 789,
  33529. 'a61': 789,
  33530. 'a62': 707,
  33531. 'a63': 687,
  33532. 'a64': 696,
  33533. 'a65': 689,
  33534. 'a66': 786,
  33535. 'a67': 787,
  33536. 'a68': 713,
  33537. 'a69': 791,
  33538. 'a70': 785,
  33539. 'a71': 791,
  33540. 'a72': 873,
  33541. 'a73': 761,
  33542. 'a74': 762,
  33543. 'a203': 762,
  33544. 'a75': 759,
  33545. 'a204': 759,
  33546. 'a76': 892,
  33547. 'a77': 892,
  33548. 'a78': 788,
  33549. 'a79': 784,
  33550. 'a81': 438,
  33551. 'a82': 138,
  33552. 'a83': 277,
  33553. 'a84': 415,
  33554. 'a97': 392,
  33555. 'a98': 392,
  33556. 'a99': 668,
  33557. 'a100': 668,
  33558. 'a89': 390,
  33559. 'a90': 390,
  33560. 'a93': 317,
  33561. 'a94': 317,
  33562. 'a91': 276,
  33563. 'a92': 276,
  33564. 'a205': 509,
  33565. 'a85': 509,
  33566. 'a206': 410,
  33567. 'a86': 410,
  33568. 'a87': 234,
  33569. 'a88': 234,
  33570. 'a95': 334,
  33571. 'a96': 334,
  33572. 'a101': 732,
  33573. 'a102': 544,
  33574. 'a103': 544,
  33575. 'a104': 910,
  33576. 'a106': 667,
  33577. 'a107': 760,
  33578. 'a108': 760,
  33579. 'a112': 776,
  33580. 'a111': 595,
  33581. 'a110': 694,
  33582. 'a109': 626,
  33583. 'a120': 788,
  33584. 'a121': 788,
  33585. 'a122': 788,
  33586. 'a123': 788,
  33587. 'a124': 788,
  33588. 'a125': 788,
  33589. 'a126': 788,
  33590. 'a127': 788,
  33591. 'a128': 788,
  33592. 'a129': 788,
  33593. 'a130': 788,
  33594. 'a131': 788,
  33595. 'a132': 788,
  33596. 'a133': 788,
  33597. 'a134': 788,
  33598. 'a135': 788,
  33599. 'a136': 788,
  33600. 'a137': 788,
  33601. 'a138': 788,
  33602. 'a139': 788,
  33603. 'a140': 788,
  33604. 'a141': 788,
  33605. 'a142': 788,
  33606. 'a143': 788,
  33607. 'a144': 788,
  33608. 'a145': 788,
  33609. 'a146': 788,
  33610. 'a147': 788,
  33611. 'a148': 788,
  33612. 'a149': 788,
  33613. 'a150': 788,
  33614. 'a151': 788,
  33615. 'a152': 788,
  33616. 'a153': 788,
  33617. 'a154': 788,
  33618. 'a155': 788,
  33619. 'a156': 788,
  33620. 'a157': 788,
  33621. 'a158': 788,
  33622. 'a159': 788,
  33623. 'a160': 894,
  33624. 'a161': 838,
  33625. 'a163': 1016,
  33626. 'a164': 458,
  33627. 'a196': 748,
  33628. 'a165': 924,
  33629. 'a192': 748,
  33630. 'a166': 918,
  33631. 'a167': 927,
  33632. 'a168': 928,
  33633. 'a169': 928,
  33634. 'a170': 834,
  33635. 'a171': 873,
  33636. 'a172': 828,
  33637. 'a173': 924,
  33638. 'a162': 924,
  33639. 'a174': 917,
  33640. 'a175': 930,
  33641. 'a176': 931,
  33642. 'a177': 463,
  33643. 'a178': 883,
  33644. 'a179': 836,
  33645. 'a193': 836,
  33646. 'a180': 867,
  33647. 'a199': 867,
  33648. 'a181': 696,
  33649. 'a200': 696,
  33650. 'a182': 874,
  33651. 'a201': 874,
  33652. 'a183': 760,
  33653. 'a184': 946,
  33654. 'a197': 771,
  33655. 'a185': 865,
  33656. 'a194': 771,
  33657. 'a198': 888,
  33658. 'a186': 967,
  33659. 'a195': 888,
  33660. 'a187': 831,
  33661. 'a188': 873,
  33662. 'a189': 927,
  33663. 'a190': 970,
  33664. 'a191': 918
  33665. }
  33666. };
  33667. var EOF = {};
  33668. function isEOF(v) {
  33669. return (v === EOF);
  33670. }
  33671. var MAX_LENGTH_TO_CACHE = 1000;
  33672. var Parser = (function ParserClosure() {
  33673. function Parser(lexer, allowStreams, xref) {
  33674. this.lexer = lexer;
  33675. this.allowStreams = allowStreams;
  33676. this.xref = xref;
  33677. this.imageCache = {};
  33678. this.refill();
  33679. }
  33680. Parser.prototype = {
  33681. refill: function Parser_refill() {
  33682. this.buf1 = this.lexer.getObj();
  33683. this.buf2 = this.lexer.getObj();
  33684. },
  33685. shift: function Parser_shift() {
  33686. if (isCmd(this.buf2, 'ID')) {
  33687. this.buf1 = this.buf2;
  33688. this.buf2 = null;
  33689. } else {
  33690. this.buf1 = this.buf2;
  33691. this.buf2 = this.lexer.getObj();
  33692. }
  33693. },
  33694. getObj: function Parser_getObj(cipherTransform) {
  33695. var buf1 = this.buf1;
  33696. this.shift();
  33697. if (buf1 instanceof Cmd) {
  33698. switch (buf1.cmd) {
  33699. case 'BI': // inline image
  33700. return this.makeInlineImage(cipherTransform);
  33701. case '[': // array
  33702. var array = [];
  33703. while (!isCmd(this.buf1, ']') && !isEOF(this.buf1)) {
  33704. array.push(this.getObj(cipherTransform));
  33705. }
  33706. if (isEOF(this.buf1)) {
  33707. error('End of file inside array');
  33708. }
  33709. this.shift();
  33710. return array;
  33711. case '<<': // dictionary or stream
  33712. var dict = new Dict(this.xref);
  33713. while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) {
  33714. if (!isName(this.buf1)) {
  33715. info('Malformed dictionary: key must be a name object');
  33716. this.shift();
  33717. continue;
  33718. }
  33719. var key = this.buf1.name;
  33720. this.shift();
  33721. if (isEOF(this.buf1)) {
  33722. break;
  33723. }
  33724. dict.set(key, this.getObj(cipherTransform));
  33725. }
  33726. if (isEOF(this.buf1)) {
  33727. error('End of file inside dictionary');
  33728. }
  33729. // Stream objects are not allowed inside content streams or
  33730. // object streams.
  33731. if (isCmd(this.buf2, 'stream')) {
  33732. return (this.allowStreams ?
  33733. this.makeStream(dict, cipherTransform) : dict);
  33734. }
  33735. this.shift();
  33736. return dict;
  33737. default: // simple object
  33738. return buf1;
  33739. }
  33740. }
  33741. if (isInt(buf1)) { // indirect reference or integer
  33742. var num = buf1;
  33743. if (isInt(this.buf1) && isCmd(this.buf2, 'R')) {
  33744. var ref = new Ref(num, this.buf1);
  33745. this.shift();
  33746. this.shift();
  33747. return ref;
  33748. }
  33749. return num;
  33750. }
  33751. if (isString(buf1)) { // string
  33752. var str = buf1;
  33753. if (cipherTransform) {
  33754. str = cipherTransform.decryptString(str);
  33755. }
  33756. return str;
  33757. }
  33758. // simple object
  33759. return buf1;
  33760. },
  33761. /**
  33762. * Find the end of the stream by searching for the /EI\s/.
  33763. * @returns {number} The inline stream length.
  33764. */
  33765. findDefaultInlineStreamEnd:
  33766. function Parser_findDefaultInlineStreamEnd(stream) {
  33767. var E = 0x45, I = 0x49, SPACE = 0x20, LF = 0xA, CR = 0xD;
  33768. var startPos = stream.pos, state = 0, ch, i, n, followingBytes;
  33769. while ((ch = stream.getByte()) !== -1) {
  33770. if (state === 0) {
  33771. state = (ch === E) ? 1 : 0;
  33772. } else if (state === 1) {
  33773. state = (ch === I) ? 2 : 0;
  33774. } else {
  33775. assert(state === 2);
  33776. if (ch === SPACE || ch === LF || ch === CR) {
  33777. // Let's check the next five bytes are ASCII... just be sure.
  33778. n = 5;
  33779. followingBytes = stream.peekBytes(n);
  33780. for (i = 0; i < n; i++) {
  33781. ch = followingBytes[i];
  33782. if (ch !== LF && ch !== CR && (ch < SPACE || ch > 0x7F)) {
  33783. // Not a LF, CR, SPACE or any visible ASCII character, i.e.
  33784. // it's binary stuff. Resetting the state.
  33785. state = 0;
  33786. break;
  33787. }
  33788. }
  33789. if (state === 2) {
  33790. break; // Finished!
  33791. }
  33792. } else {
  33793. state = 0;
  33794. }
  33795. }
  33796. }
  33797. return ((stream.pos - 4) - startPos);
  33798. },
  33799. /**
  33800. * Find the EOD (end-of-data) marker '~>' (i.e. TILDE + GT) of the stream.
  33801. * @returns {number} The inline stream length.
  33802. */
  33803. findASCII85DecodeInlineStreamEnd:
  33804. function Parser_findASCII85DecodeInlineStreamEnd(stream) {
  33805. var TILDE = 0x7E, GT = 0x3E;
  33806. var startPos = stream.pos, ch, length;
  33807. while ((ch = stream.getByte()) !== -1) {
  33808. if (ch === TILDE && stream.peekByte() === GT) {
  33809. stream.skip();
  33810. break;
  33811. }
  33812. }
  33813. length = stream.pos - startPos;
  33814. if (ch === -1) {
  33815. warn('Inline ASCII85Decode image stream: ' +
  33816. 'EOD marker not found, searching for /EI/ instead.');
  33817. stream.skip(-length); // Reset the stream position.
  33818. return this.findDefaultInlineStreamEnd(stream);
  33819. }
  33820. this.inlineStreamSkipEI(stream);
  33821. return length;
  33822. },
  33823. /**
  33824. * Find the EOD (end-of-data) marker '>' (i.e. GT) of the stream.
  33825. * @returns {number} The inline stream length.
  33826. */
  33827. findASCIIHexDecodeInlineStreamEnd:
  33828. function Parser_findASCIIHexDecodeInlineStreamEnd(stream) {
  33829. var GT = 0x3E;
  33830. var startPos = stream.pos, ch, length;
  33831. while ((ch = stream.getByte()) !== -1) {
  33832. if (ch === GT) {
  33833. break;
  33834. }
  33835. }
  33836. length = stream.pos - startPos;
  33837. if (ch === -1) {
  33838. warn('Inline ASCIIHexDecode image stream: ' +
  33839. 'EOD marker not found, searching for /EI/ instead.');
  33840. stream.skip(-length); // Reset the stream position.
  33841. return this.findDefaultInlineStreamEnd(stream);
  33842. }
  33843. this.inlineStreamSkipEI(stream);
  33844. return length;
  33845. },
  33846. /**
  33847. * Skip over the /EI/ for streams where we search for an EOD marker.
  33848. */
  33849. inlineStreamSkipEI: function Parser_inlineStreamSkipEI(stream) {
  33850. var E = 0x45, I = 0x49;
  33851. var state = 0, ch;
  33852. while ((ch = stream.getByte()) !== -1) {
  33853. if (state === 0) {
  33854. state = (ch === E) ? 1 : 0;
  33855. } else if (state === 1) {
  33856. state = (ch === I) ? 2 : 0;
  33857. } else if (state === 2) {
  33858. break;
  33859. }
  33860. }
  33861. },
  33862. makeInlineImage: function Parser_makeInlineImage(cipherTransform) {
  33863. var lexer = this.lexer;
  33864. var stream = lexer.stream;
  33865. // Parse dictionary.
  33866. var dict = new Dict(null);
  33867. while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) {
  33868. if (!isName(this.buf1)) {
  33869. error('Dictionary key must be a name object');
  33870. }
  33871. var key = this.buf1.name;
  33872. this.shift();
  33873. if (isEOF(this.buf1)) {
  33874. break;
  33875. }
  33876. dict.set(key, this.getObj(cipherTransform));
  33877. }
  33878. // Extract the name of the first (i.e. the current) image filter.
  33879. var filter = this.fetchIfRef(dict.get('Filter', 'F')), filterName;
  33880. if (isName(filter)) {
  33881. filterName = filter.name;
  33882. } else if (isArray(filter) && isName(filter[0])) {
  33883. filterName = filter[0].name;
  33884. }
  33885. // Parse image stream.
  33886. var startPos = stream.pos, length, i, ii;
  33887. if (filterName === 'ASCII85Decide' || filterName === 'A85') {
  33888. length = this.findASCII85DecodeInlineStreamEnd(stream);
  33889. } else if (filterName === 'ASCIIHexDecode' || filterName === 'AHx') {
  33890. length = this.findASCIIHexDecodeInlineStreamEnd(stream);
  33891. } else {
  33892. length = this.findDefaultInlineStreamEnd(stream);
  33893. }
  33894. var imageStream = stream.makeSubStream(startPos, length, dict);
  33895. // Cache all images below the MAX_LENGTH_TO_CACHE threshold by their
  33896. // adler32 checksum.
  33897. var adler32;
  33898. if (length < MAX_LENGTH_TO_CACHE) {
  33899. var imageBytes = imageStream.getBytes();
  33900. imageStream.reset();
  33901. var a = 1;
  33902. var b = 0;
  33903. for (i = 0, ii = imageBytes.length; i < ii; ++i) {
  33904. // No modulo required in the loop if imageBytes.length < 5552.
  33905. a += imageBytes[i] & 0xff;
  33906. b += a;
  33907. }
  33908. adler32 = ((b % 65521) << 16) | (a % 65521);
  33909. if (this.imageCache.adler32 === adler32) {
  33910. this.buf2 = Cmd.get('EI');
  33911. this.shift();
  33912. this.imageCache[adler32].reset();
  33913. return this.imageCache[adler32];
  33914. }
  33915. }
  33916. if (cipherTransform) {
  33917. imageStream = cipherTransform.createStream(imageStream, length);
  33918. }
  33919. imageStream = this.filter(imageStream, dict, length);
  33920. imageStream.dict = dict;
  33921. if (adler32 !== undefined) {
  33922. imageStream.cacheKey = 'inline_' + length + '_' + adler32;
  33923. this.imageCache[adler32] = imageStream;
  33924. }
  33925. this.buf2 = Cmd.get('EI');
  33926. this.shift();
  33927. return imageStream;
  33928. },
  33929. fetchIfRef: function Parser_fetchIfRef(obj) {
  33930. // not relying on the xref.fetchIfRef -- xref might not be set
  33931. return (isRef(obj) ? this.xref.fetch(obj) : obj);
  33932. },
  33933. makeStream: function Parser_makeStream(dict, cipherTransform) {
  33934. var lexer = this.lexer;
  33935. var stream = lexer.stream;
  33936. // get stream start position
  33937. lexer.skipToNextLine();
  33938. var pos = stream.pos - 1;
  33939. // get length
  33940. var length = this.fetchIfRef(dict.get('Length'));
  33941. if (!isInt(length)) {
  33942. info('Bad ' + length + ' attribute in stream');
  33943. length = 0;
  33944. }
  33945. // skip over the stream data
  33946. stream.pos = pos + length;
  33947. lexer.nextChar();
  33948. this.shift(); // '>>'
  33949. this.shift(); // 'stream'
  33950. if (!isCmd(this.buf1, 'endstream')) {
  33951. // bad stream length, scanning for endstream
  33952. stream.pos = pos;
  33953. var SCAN_BLOCK_SIZE = 2048;
  33954. var ENDSTREAM_SIGNATURE_LENGTH = 9;
  33955. var ENDSTREAM_SIGNATURE = [0x65, 0x6E, 0x64, 0x73, 0x74, 0x72, 0x65,
  33956. 0x61, 0x6D];
  33957. var skipped = 0, found = false, i, j;
  33958. while (stream.pos < stream.end) {
  33959. var scanBytes = stream.peekBytes(SCAN_BLOCK_SIZE);
  33960. var scanLength = scanBytes.length - ENDSTREAM_SIGNATURE_LENGTH;
  33961. if (scanLength <= 0) {
  33962. break;
  33963. }
  33964. found = false;
  33965. for (i = 0, j = 0; i < scanLength; i++) {
  33966. var b = scanBytes[i];
  33967. if (b !== ENDSTREAM_SIGNATURE[j]) {
  33968. i -= j;
  33969. j = 0;
  33970. } else {
  33971. j++;
  33972. if (j >= ENDSTREAM_SIGNATURE_LENGTH) {
  33973. i++;
  33974. found = true;
  33975. break;
  33976. }
  33977. }
  33978. }
  33979. if (found) {
  33980. skipped += i - ENDSTREAM_SIGNATURE_LENGTH;
  33981. stream.pos += i - ENDSTREAM_SIGNATURE_LENGTH;
  33982. break;
  33983. }
  33984. skipped += scanLength;
  33985. stream.pos += scanLength;
  33986. }
  33987. if (!found) {
  33988. error('Missing endstream');
  33989. }
  33990. length = skipped;
  33991. lexer.nextChar();
  33992. this.shift();
  33993. this.shift();
  33994. }
  33995. this.shift(); // 'endstream'
  33996. stream = stream.makeSubStream(pos, length, dict);
  33997. if (cipherTransform) {
  33998. stream = cipherTransform.createStream(stream, length);
  33999. }
  34000. stream = this.filter(stream, dict, length);
  34001. stream.dict = dict;
  34002. return stream;
  34003. },
  34004. filter: function Parser_filter(stream, dict, length) {
  34005. var filter = this.fetchIfRef(dict.get('Filter', 'F'));
  34006. var params = this.fetchIfRef(dict.get('DecodeParms', 'DP'));
  34007. if (isName(filter)) {
  34008. return this.makeFilter(stream, filter.name, length, params);
  34009. }
  34010. var maybeLength = length;
  34011. if (isArray(filter)) {
  34012. var filterArray = filter;
  34013. var paramsArray = params;
  34014. for (var i = 0, ii = filterArray.length; i < ii; ++i) {
  34015. filter = filterArray[i];
  34016. if (!isName(filter)) {
  34017. error('Bad filter name: ' + filter);
  34018. }
  34019. params = null;
  34020. if (isArray(paramsArray) && (i in paramsArray)) {
  34021. params = paramsArray[i];
  34022. }
  34023. stream = this.makeFilter(stream, filter.name, maybeLength, params);
  34024. // after the first stream the length variable is invalid
  34025. maybeLength = null;
  34026. }
  34027. }
  34028. return stream;
  34029. },
  34030. makeFilter: function Parser_makeFilter(stream, name, maybeLength, params) {
  34031. if (stream.dict.get('Length') === 0) {
  34032. return new NullStream(stream);
  34033. }
  34034. try {
  34035. if (params) {
  34036. params = this.fetchIfRef(params);
  34037. }
  34038. var xrefStreamStats = this.xref.stats.streamTypes;
  34039. if (name === 'FlateDecode' || name === 'Fl') {
  34040. xrefStreamStats[StreamType.FLATE] = true;
  34041. if (params) {
  34042. return new PredictorStream(new FlateStream(stream, maybeLength),
  34043. maybeLength, params);
  34044. }
  34045. return new FlateStream(stream, maybeLength);
  34046. }
  34047. if (name === 'LZWDecode' || name === 'LZW') {
  34048. xrefStreamStats[StreamType.LZW] = true;
  34049. var earlyChange = 1;
  34050. if (params) {
  34051. if (params.has('EarlyChange')) {
  34052. earlyChange = params.get('EarlyChange');
  34053. }
  34054. return new PredictorStream(
  34055. new LZWStream(stream, maybeLength, earlyChange),
  34056. maybeLength, params);
  34057. }
  34058. return new LZWStream(stream, maybeLength, earlyChange);
  34059. }
  34060. if (name === 'DCTDecode' || name === 'DCT') {
  34061. xrefStreamStats[StreamType.DCT] = true;
  34062. return new JpegStream(stream, maybeLength, stream.dict, this.xref);
  34063. }
  34064. if (name === 'JPXDecode' || name === 'JPX') {
  34065. xrefStreamStats[StreamType.JPX] = true;
  34066. return new JpxStream(stream, maybeLength, stream.dict);
  34067. }
  34068. if (name === 'ASCII85Decode' || name === 'A85') {
  34069. xrefStreamStats[StreamType.A85] = true;
  34070. return new Ascii85Stream(stream, maybeLength);
  34071. }
  34072. if (name === 'ASCIIHexDecode' || name === 'AHx') {
  34073. xrefStreamStats[StreamType.AHX] = true;
  34074. return new AsciiHexStream(stream, maybeLength);
  34075. }
  34076. if (name === 'CCITTFaxDecode' || name === 'CCF') {
  34077. xrefStreamStats[StreamType.CCF] = true;
  34078. return new CCITTFaxStream(stream, maybeLength, params);
  34079. }
  34080. if (name === 'RunLengthDecode' || name === 'RL') {
  34081. xrefStreamStats[StreamType.RL] = true;
  34082. return new RunLengthStream(stream, maybeLength);
  34083. }
  34084. if (name === 'JBIG2Decode') {
  34085. xrefStreamStats[StreamType.JBIG] = true;
  34086. return new Jbig2Stream(stream, maybeLength, stream.dict);
  34087. }
  34088. warn('filter "' + name + '" not supported yet');
  34089. return stream;
  34090. } catch (ex) {
  34091. if (ex instanceof MissingDataException) {
  34092. throw ex;
  34093. }
  34094. warn('Invalid stream: \"' + ex + '\"');
  34095. return new NullStream(stream);
  34096. }
  34097. }
  34098. };
  34099. return Parser;
  34100. })();
  34101. var Lexer = (function LexerClosure() {
  34102. function Lexer(stream, knownCommands) {
  34103. this.stream = stream;
  34104. this.nextChar();
  34105. // While lexing, we build up many strings one char at a time. Using += for
  34106. // this can result in lots of garbage strings. It's better to build an
  34107. // array of single-char strings and then join() them together at the end.
  34108. // And reusing a single array (i.e. |this.strBuf|) over and over for this
  34109. // purpose uses less memory than using a new array for each string.
  34110. this.strBuf = [];
  34111. // The PDFs might have "glued" commands with other commands, operands or
  34112. // literals, e.g. "q1". The knownCommands is a dictionary of the valid
  34113. // commands and their prefixes. The prefixes are built the following way:
  34114. // if there a command that is a prefix of the other valid command or
  34115. // literal (e.g. 'f' and 'false') the following prefixes must be included,
  34116. // 'fa', 'fal', 'fals'. The prefixes are not needed, if the command has no
  34117. // other commands or literals as a prefix. The knowCommands is optional.
  34118. this.knownCommands = knownCommands;
  34119. }
  34120. Lexer.isSpace = function Lexer_isSpace(ch) {
  34121. // Space is one of the following characters: SPACE, TAB, CR or LF.
  34122. return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
  34123. };
  34124. // A '1' in this array means the character is white space. A '1' or
  34125. // '2' means the character ends a name or command.
  34126. var specialChars = [
  34127. 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x
  34128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
  34129. 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x
  34130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x
  34131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x
  34132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x
  34133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x
  34134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x
  34135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x
  34136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x
  34137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax
  34138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx
  34139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx
  34140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx
  34141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex
  34142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx
  34143. ];
  34144. function toHexDigit(ch) {
  34145. if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
  34146. return ch & 0x0F;
  34147. }
  34148. if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
  34149. // 'A'-'F', 'a'-'f'
  34150. return (ch & 0x0F) + 9;
  34151. }
  34152. return -1;
  34153. }
  34154. Lexer.prototype = {
  34155. nextChar: function Lexer_nextChar() {
  34156. return (this.currentChar = this.stream.getByte());
  34157. },
  34158. peekChar: function Lexer_peekChar() {
  34159. return this.stream.peekByte();
  34160. },
  34161. getNumber: function Lexer_getNumber() {
  34162. var ch = this.currentChar;
  34163. var eNotation = false;
  34164. var divideBy = 0; // different from 0 if it's a floating point value
  34165. var sign = 1;
  34166. if (ch === 0x2D) { // '-'
  34167. sign = -1;
  34168. ch = this.nextChar();
  34169. } else if (ch === 0x2B) { // '+'
  34170. ch = this.nextChar();
  34171. }
  34172. if (ch === 0x2E) { // '.'
  34173. divideBy = 10;
  34174. ch = this.nextChar();
  34175. }
  34176. if (ch < 0x30 || ch > 0x39) { // '0' - '9'
  34177. error('Invalid number: ' + String.fromCharCode(ch));
  34178. return 0;
  34179. }
  34180. var baseValue = ch - 0x30; // '0'
  34181. var powerValue = 0;
  34182. var powerValueSign = 1;
  34183. while ((ch = this.nextChar()) >= 0) {
  34184. if (0x30 <= ch && ch <= 0x39) { // '0' - '9'
  34185. var currentDigit = ch - 0x30; // '0'
  34186. if (eNotation) { // We are after an 'e' or 'E'
  34187. powerValue = powerValue * 10 + currentDigit;
  34188. } else {
  34189. if (divideBy !== 0) { // We are after a point
  34190. divideBy *= 10;
  34191. }
  34192. baseValue = baseValue * 10 + currentDigit;
  34193. }
  34194. } else if (ch === 0x2E) { // '.'
  34195. if (divideBy === 0) {
  34196. divideBy = 1;
  34197. } else {
  34198. // A number can have only one '.'
  34199. break;
  34200. }
  34201. } else if (ch === 0x2D) { // '-'
  34202. // ignore minus signs in the middle of numbers to match
  34203. // Adobe's behavior
  34204. warn('Badly formated number');
  34205. } else if (ch === 0x45 || ch === 0x65) { // 'E', 'e'
  34206. // 'E' can be either a scientific notation or the beginning of a new
  34207. // operator
  34208. ch = this.peekChar();
  34209. if (ch === 0x2B || ch === 0x2D) { // '+', '-'
  34210. powerValueSign = (ch === 0x2D) ? -1 : 1;
  34211. this.nextChar(); // Consume the sign character
  34212. } else if (ch < 0x30 || ch > 0x39) { // '0' - '9'
  34213. // The 'E' must be the beginning of a new operator
  34214. break;
  34215. }
  34216. eNotation = true;
  34217. } else {
  34218. // the last character doesn't belong to us
  34219. break;
  34220. }
  34221. }
  34222. if (divideBy !== 0) {
  34223. baseValue /= divideBy;
  34224. }
  34225. if (eNotation) {
  34226. baseValue *= Math.pow(10, powerValueSign * powerValue);
  34227. }
  34228. return sign * baseValue;
  34229. },
  34230. getString: function Lexer_getString() {
  34231. var numParen = 1;
  34232. var done = false;
  34233. var strBuf = this.strBuf;
  34234. strBuf.length = 0;
  34235. var ch = this.nextChar();
  34236. while (true) {
  34237. var charBuffered = false;
  34238. switch (ch | 0) {
  34239. case -1:
  34240. warn('Unterminated string');
  34241. done = true;
  34242. break;
  34243. case 0x28: // '('
  34244. ++numParen;
  34245. strBuf.push('(');
  34246. break;
  34247. case 0x29: // ')'
  34248. if (--numParen === 0) {
  34249. this.nextChar(); // consume strings ')'
  34250. done = true;
  34251. } else {
  34252. strBuf.push(')');
  34253. }
  34254. break;
  34255. case 0x5C: // '\\'
  34256. ch = this.nextChar();
  34257. switch (ch) {
  34258. case -1:
  34259. warn('Unterminated string');
  34260. done = true;
  34261. break;
  34262. case 0x6E: // 'n'
  34263. strBuf.push('\n');
  34264. break;
  34265. case 0x72: // 'r'
  34266. strBuf.push('\r');
  34267. break;
  34268. case 0x74: // 't'
  34269. strBuf.push('\t');
  34270. break;
  34271. case 0x62: // 'b'
  34272. strBuf.push('\b');
  34273. break;
  34274. case 0x66: // 'f'
  34275. strBuf.push('\f');
  34276. break;
  34277. case 0x5C: // '\'
  34278. case 0x28: // '('
  34279. case 0x29: // ')'
  34280. strBuf.push(String.fromCharCode(ch));
  34281. break;
  34282. case 0x30: case 0x31: case 0x32: case 0x33: // '0'-'3'
  34283. case 0x34: case 0x35: case 0x36: case 0x37: // '4'-'7'
  34284. var x = ch & 0x0F;
  34285. ch = this.nextChar();
  34286. charBuffered = true;
  34287. if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'
  34288. x = (x << 3) + (ch & 0x0F);
  34289. ch = this.nextChar();
  34290. if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'
  34291. charBuffered = false;
  34292. x = (x << 3) + (ch & 0x0F);
  34293. }
  34294. }
  34295. strBuf.push(String.fromCharCode(x));
  34296. break;
  34297. case 0x0D: // CR
  34298. if (this.peekChar() === 0x0A) { // LF
  34299. this.nextChar();
  34300. }
  34301. break;
  34302. case 0x0A: // LF
  34303. break;
  34304. default:
  34305. strBuf.push(String.fromCharCode(ch));
  34306. break;
  34307. }
  34308. break;
  34309. default:
  34310. strBuf.push(String.fromCharCode(ch));
  34311. break;
  34312. }
  34313. if (done) {
  34314. break;
  34315. }
  34316. if (!charBuffered) {
  34317. ch = this.nextChar();
  34318. }
  34319. }
  34320. return strBuf.join('');
  34321. },
  34322. getName: function Lexer_getName() {
  34323. var ch;
  34324. var strBuf = this.strBuf;
  34325. strBuf.length = 0;
  34326. while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
  34327. if (ch === 0x23) { // '#'
  34328. ch = this.nextChar();
  34329. var x = toHexDigit(ch);
  34330. if (x !== -1) {
  34331. var x2 = toHexDigit(this.nextChar());
  34332. if (x2 === -1) {
  34333. error('Illegal digit in hex char in name: ' + x2);
  34334. }
  34335. strBuf.push(String.fromCharCode((x << 4) | x2));
  34336. } else {
  34337. strBuf.push('#', String.fromCharCode(ch));
  34338. }
  34339. } else {
  34340. strBuf.push(String.fromCharCode(ch));
  34341. }
  34342. }
  34343. if (strBuf.length > 128) {
  34344. error('Warning: name token is longer than allowed by the spec: ' +
  34345. strBuf.length);
  34346. }
  34347. return Name.get(strBuf.join(''));
  34348. },
  34349. getHexString: function Lexer_getHexString() {
  34350. var strBuf = this.strBuf;
  34351. strBuf.length = 0;
  34352. var ch = this.currentChar;
  34353. var isFirstHex = true;
  34354. var firstDigit;
  34355. var secondDigit;
  34356. while (true) {
  34357. if (ch < 0) {
  34358. warn('Unterminated hex string');
  34359. break;
  34360. } else if (ch === 0x3E) { // '>'
  34361. this.nextChar();
  34362. break;
  34363. } else if (specialChars[ch] === 1) {
  34364. ch = this.nextChar();
  34365. continue;
  34366. } else {
  34367. if (isFirstHex) {
  34368. firstDigit = toHexDigit(ch);
  34369. if (firstDigit === -1) {
  34370. warn('Ignoring invalid character "' + ch + '" in hex string');
  34371. ch = this.nextChar();
  34372. continue;
  34373. }
  34374. } else {
  34375. secondDigit = toHexDigit(ch);
  34376. if (secondDigit === -1) {
  34377. warn('Ignoring invalid character "' + ch + '" in hex string');
  34378. ch = this.nextChar();
  34379. continue;
  34380. }
  34381. strBuf.push(String.fromCharCode((firstDigit << 4) | secondDigit));
  34382. }
  34383. isFirstHex = !isFirstHex;
  34384. ch = this.nextChar();
  34385. }
  34386. }
  34387. return strBuf.join('');
  34388. },
  34389. getObj: function Lexer_getObj() {
  34390. // skip whitespace and comments
  34391. var comment = false;
  34392. var ch = this.currentChar;
  34393. while (true) {
  34394. if (ch < 0) {
  34395. return EOF;
  34396. }
  34397. if (comment) {
  34398. if (ch === 0x0A || ch === 0x0D) { // LF, CR
  34399. comment = false;
  34400. }
  34401. } else if (ch === 0x25) { // '%'
  34402. comment = true;
  34403. } else if (specialChars[ch] !== 1) {
  34404. break;
  34405. }
  34406. ch = this.nextChar();
  34407. }
  34408. // start reading token
  34409. switch (ch | 0) {
  34410. case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'
  34411. case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'
  34412. case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'
  34413. return this.getNumber();
  34414. case 0x28: // '('
  34415. return this.getString();
  34416. case 0x2F: // '/'
  34417. return this.getName();
  34418. // array punctuation
  34419. case 0x5B: // '['
  34420. this.nextChar();
  34421. return Cmd.get('[');
  34422. case 0x5D: // ']'
  34423. this.nextChar();
  34424. return Cmd.get(']');
  34425. // hex string or dict punctuation
  34426. case 0x3C: // '<'
  34427. ch = this.nextChar();
  34428. if (ch === 0x3C) {
  34429. // dict punctuation
  34430. this.nextChar();
  34431. return Cmd.get('<<');
  34432. }
  34433. return this.getHexString();
  34434. // dict punctuation
  34435. case 0x3E: // '>'
  34436. ch = this.nextChar();
  34437. if (ch === 0x3E) {
  34438. this.nextChar();
  34439. return Cmd.get('>>');
  34440. }
  34441. return Cmd.get('>');
  34442. case 0x7B: // '{'
  34443. this.nextChar();
  34444. return Cmd.get('{');
  34445. case 0x7D: // '}'
  34446. this.nextChar();
  34447. return Cmd.get('}');
  34448. case 0x29: // ')'
  34449. error('Illegal character: ' + ch);
  34450. break;
  34451. }
  34452. // command
  34453. var str = String.fromCharCode(ch);
  34454. var knownCommands = this.knownCommands;
  34455. var knownCommandFound = knownCommands && knownCommands[str] !== undefined;
  34456. while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
  34457. // stop if known command is found and next character does not make
  34458. // the str a command
  34459. var possibleCommand = str + String.fromCharCode(ch);
  34460. if (knownCommandFound && knownCommands[possibleCommand] === undefined) {
  34461. break;
  34462. }
  34463. if (str.length === 128) {
  34464. error('Command token too long: ' + str.length);
  34465. }
  34466. str = possibleCommand;
  34467. knownCommandFound = knownCommands && knownCommands[str] !== undefined;
  34468. }
  34469. if (str === 'true') {
  34470. return true;
  34471. }
  34472. if (str === 'false') {
  34473. return false;
  34474. }
  34475. if (str === 'null') {
  34476. return null;
  34477. }
  34478. return Cmd.get(str);
  34479. },
  34480. skipToNextLine: function Lexer_skipToNextLine() {
  34481. var ch = this.currentChar;
  34482. while (ch >= 0) {
  34483. if (ch === 0x0D) { // CR
  34484. ch = this.nextChar();
  34485. if (ch === 0x0A) { // LF
  34486. this.nextChar();
  34487. }
  34488. break;
  34489. } else if (ch === 0x0A) { // LF
  34490. this.nextChar();
  34491. break;
  34492. }
  34493. ch = this.nextChar();
  34494. }
  34495. }
  34496. };
  34497. return Lexer;
  34498. })();
  34499. var Linearization = {
  34500. create: function LinearizationCreate(stream) {
  34501. function getInt(name, allowZeroValue) {
  34502. var obj = linDict.get(name);
  34503. if (isInt(obj) && (allowZeroValue ? obj >= 0 : obj > 0)) {
  34504. return obj;
  34505. }
  34506. throw new Error('The "' + name + '" parameter in the linearization ' +
  34507. 'dictionary is invalid.');
  34508. }
  34509. function getHints() {
  34510. var hints = linDict.get('H'), hintsLength, item;
  34511. if (isArray(hints) &&
  34512. ((hintsLength = hints.length) === 2 || hintsLength === 4)) {
  34513. for (var index = 0; index < hintsLength; index++) {
  34514. if (!(isInt(item = hints[index]) && item > 0)) {
  34515. throw new Error('Hint (' + index +
  34516. ') in the linearization dictionary is invalid.');
  34517. }
  34518. }
  34519. return hints;
  34520. }
  34521. throw new Error('Hint array in the linearization dictionary is invalid.');
  34522. }
  34523. var parser = new Parser(new Lexer(stream), false, null);
  34524. var obj1 = parser.getObj();
  34525. var obj2 = parser.getObj();
  34526. var obj3 = parser.getObj();
  34527. var linDict = parser.getObj();
  34528. var obj, length;
  34529. if (!(isInt(obj1) && isInt(obj2) && isCmd(obj3, 'obj') && isDict(linDict) &&
  34530. isNum(obj = linDict.get('Linearized')) && obj > 0)) {
  34531. return null; // No valid linearization dictionary found.
  34532. } else if ((length = getInt('L')) !== stream.length) {
  34533. throw new Error('The "L" parameter in the linearization dictionary ' +
  34534. 'does not equal the stream length.');
  34535. }
  34536. return {
  34537. length: length,
  34538. hints: getHints(),
  34539. objectNumberFirst: getInt('O'),
  34540. endFirst: getInt('E'),
  34541. numPages: getInt('N'),
  34542. mainXRefEntriesOffset: getInt('T'),
  34543. pageFirst: (linDict.has('P') ? getInt('P', true) : 0)
  34544. };
  34545. }
  34546. };
  34547. var PostScriptParser = (function PostScriptParserClosure() {
  34548. function PostScriptParser(lexer) {
  34549. this.lexer = lexer;
  34550. this.operators = [];
  34551. this.token = null;
  34552. this.prev = null;
  34553. }
  34554. PostScriptParser.prototype = {
  34555. nextToken: function PostScriptParser_nextToken() {
  34556. this.prev = this.token;
  34557. this.token = this.lexer.getToken();
  34558. },
  34559. accept: function PostScriptParser_accept(type) {
  34560. if (this.token.type === type) {
  34561. this.nextToken();
  34562. return true;
  34563. }
  34564. return false;
  34565. },
  34566. expect: function PostScriptParser_expect(type) {
  34567. if (this.accept(type)) {
  34568. return true;
  34569. }
  34570. error('Unexpected symbol: found ' + this.token.type + ' expected ' +
  34571. type + '.');
  34572. },
  34573. parse: function PostScriptParser_parse() {
  34574. this.nextToken();
  34575. this.expect(PostScriptTokenTypes.LBRACE);
  34576. this.parseBlock();
  34577. this.expect(PostScriptTokenTypes.RBRACE);
  34578. return this.operators;
  34579. },
  34580. parseBlock: function PostScriptParser_parseBlock() {
  34581. while (true) {
  34582. if (this.accept(PostScriptTokenTypes.NUMBER)) {
  34583. this.operators.push(this.prev.value);
  34584. } else if (this.accept(PostScriptTokenTypes.OPERATOR)) {
  34585. this.operators.push(this.prev.value);
  34586. } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
  34587. this.parseCondition();
  34588. } else {
  34589. return;
  34590. }
  34591. }
  34592. },
  34593. parseCondition: function PostScriptParser_parseCondition() {
  34594. // Add two place holders that will be updated later
  34595. var conditionLocation = this.operators.length;
  34596. this.operators.push(null, null);
  34597. this.parseBlock();
  34598. this.expect(PostScriptTokenTypes.RBRACE);
  34599. if (this.accept(PostScriptTokenTypes.IF)) {
  34600. // The true block is right after the 'if' so it just falls through on
  34601. // true else it jumps and skips the true block.
  34602. this.operators[conditionLocation] = this.operators.length;
  34603. this.operators[conditionLocation + 1] = 'jz';
  34604. } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
  34605. var jumpLocation = this.operators.length;
  34606. this.operators.push(null, null);
  34607. var endOfTrue = this.operators.length;
  34608. this.parseBlock();
  34609. this.expect(PostScriptTokenTypes.RBRACE);
  34610. this.expect(PostScriptTokenTypes.IFELSE);
  34611. // The jump is added at the end of the true block to skip the false
  34612. // block.
  34613. this.operators[jumpLocation] = this.operators.length;
  34614. this.operators[jumpLocation + 1] = 'j';
  34615. this.operators[conditionLocation] = endOfTrue;
  34616. this.operators[conditionLocation + 1] = 'jz';
  34617. } else {
  34618. error('PS Function: error parsing conditional.');
  34619. }
  34620. }
  34621. };
  34622. return PostScriptParser;
  34623. })();
  34624. var PostScriptTokenTypes = {
  34625. LBRACE: 0,
  34626. RBRACE: 1,
  34627. NUMBER: 2,
  34628. OPERATOR: 3,
  34629. IF: 4,
  34630. IFELSE: 5
  34631. };
  34632. var PostScriptToken = (function PostScriptTokenClosure() {
  34633. function PostScriptToken(type, value) {
  34634. this.type = type;
  34635. this.value = value;
  34636. }
  34637. var opCache = {};
  34638. PostScriptToken.getOperator = function PostScriptToken_getOperator(op) {
  34639. var opValue = opCache[op];
  34640. if (opValue) {
  34641. return opValue;
  34642. }
  34643. return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);
  34644. };
  34645. PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE,
  34646. '{');
  34647. PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE,
  34648. '}');
  34649. PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF');
  34650. PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE,
  34651. 'IFELSE');
  34652. return PostScriptToken;
  34653. })();
  34654. var PostScriptLexer = (function PostScriptLexerClosure() {
  34655. function PostScriptLexer(stream) {
  34656. this.stream = stream;
  34657. this.nextChar();
  34658. this.strBuf = [];
  34659. }
  34660. PostScriptLexer.prototype = {
  34661. nextChar: function PostScriptLexer_nextChar() {
  34662. return (this.currentChar = this.stream.getByte());
  34663. },
  34664. getToken: function PostScriptLexer_getToken() {
  34665. var comment = false;
  34666. var ch = this.currentChar;
  34667. // skip comments
  34668. while (true) {
  34669. if (ch < 0) {
  34670. return EOF;
  34671. }
  34672. if (comment) {
  34673. if (ch === 0x0A || ch === 0x0D) {
  34674. comment = false;
  34675. }
  34676. } else if (ch === 0x25) { // '%'
  34677. comment = true;
  34678. } else if (!Lexer.isSpace(ch)) {
  34679. break;
  34680. }
  34681. ch = this.nextChar();
  34682. }
  34683. switch (ch | 0) {
  34684. case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'
  34685. case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'
  34686. case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'
  34687. return new PostScriptToken(PostScriptTokenTypes.NUMBER,
  34688. this.getNumber());
  34689. case 0x7B: // '{'
  34690. this.nextChar();
  34691. return PostScriptToken.LBRACE;
  34692. case 0x7D: // '}'
  34693. this.nextChar();
  34694. return PostScriptToken.RBRACE;
  34695. }
  34696. // operator
  34697. var strBuf = this.strBuf;
  34698. strBuf.length = 0;
  34699. strBuf[0] = String.fromCharCode(ch);
  34700. while ((ch = this.nextChar()) >= 0 && // and 'A'-'Z', 'a'-'z'
  34701. ((ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A))) {
  34702. strBuf.push(String.fromCharCode(ch));
  34703. }
  34704. var str = strBuf.join('');
  34705. switch (str.toLowerCase()) {
  34706. case 'if':
  34707. return PostScriptToken.IF;
  34708. case 'ifelse':
  34709. return PostScriptToken.IFELSE;
  34710. default:
  34711. return PostScriptToken.getOperator(str);
  34712. }
  34713. },
  34714. getNumber: function PostScriptLexer_getNumber() {
  34715. var ch = this.currentChar;
  34716. var strBuf = this.strBuf;
  34717. strBuf.length = 0;
  34718. strBuf[0] = String.fromCharCode(ch);
  34719. while ((ch = this.nextChar()) >= 0) {
  34720. if ((ch >= 0x30 && ch <= 0x39) || // '0'-'9'
  34721. ch === 0x2D || ch === 0x2E) { // '-', '.'
  34722. strBuf.push(String.fromCharCode(ch));
  34723. } else {
  34724. break;
  34725. }
  34726. }
  34727. var value = parseFloat(strBuf.join(''));
  34728. if (isNaN(value)) {
  34729. error('Invalid floating point number: ' + value);
  34730. }
  34731. return value;
  34732. }
  34733. };
  34734. return PostScriptLexer;
  34735. })();
  34736. var Stream = (function StreamClosure() {
  34737. function Stream(arrayBuffer, start, length, dict) {
  34738. this.bytes = (arrayBuffer instanceof Uint8Array ?
  34739. arrayBuffer : new Uint8Array(arrayBuffer));
  34740. this.start = start || 0;
  34741. this.pos = this.start;
  34742. this.end = (start + length) || this.bytes.length;
  34743. this.dict = dict;
  34744. }
  34745. // required methods for a stream. if a particular stream does not
  34746. // implement these, an error should be thrown
  34747. Stream.prototype = {
  34748. get length() {
  34749. return this.end - this.start;
  34750. },
  34751. get isEmpty() {
  34752. return this.length === 0;
  34753. },
  34754. getByte: function Stream_getByte() {
  34755. if (this.pos >= this.end) {
  34756. return -1;
  34757. }
  34758. return this.bytes[this.pos++];
  34759. },
  34760. getUint16: function Stream_getUint16() {
  34761. var b0 = this.getByte();
  34762. var b1 = this.getByte();
  34763. return (b0 << 8) + b1;
  34764. },
  34765. getInt32: function Stream_getInt32() {
  34766. var b0 = this.getByte();
  34767. var b1 = this.getByte();
  34768. var b2 = this.getByte();
  34769. var b3 = this.getByte();
  34770. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  34771. },
  34772. // returns subarray of original buffer
  34773. // should only be read
  34774. getBytes: function Stream_getBytes(length) {
  34775. var bytes = this.bytes;
  34776. var pos = this.pos;
  34777. var strEnd = this.end;
  34778. if (!length) {
  34779. return bytes.subarray(pos, strEnd);
  34780. }
  34781. var end = pos + length;
  34782. if (end > strEnd) {
  34783. end = strEnd;
  34784. }
  34785. this.pos = end;
  34786. return bytes.subarray(pos, end);
  34787. },
  34788. peekByte: function Stream_peekByte() {
  34789. var peekedByte = this.getByte();
  34790. this.pos--;
  34791. return peekedByte;
  34792. },
  34793. peekBytes: function Stream_peekBytes(length) {
  34794. var bytes = this.getBytes(length);
  34795. this.pos -= bytes.length;
  34796. return bytes;
  34797. },
  34798. skip: function Stream_skip(n) {
  34799. if (!n) {
  34800. n = 1;
  34801. }
  34802. this.pos += n;
  34803. },
  34804. reset: function Stream_reset() {
  34805. this.pos = this.start;
  34806. },
  34807. moveStart: function Stream_moveStart() {
  34808. this.start = this.pos;
  34809. },
  34810. makeSubStream: function Stream_makeSubStream(start, length, dict) {
  34811. return new Stream(this.bytes.buffer, start, length, dict);
  34812. },
  34813. isStream: true
  34814. };
  34815. return Stream;
  34816. })();
  34817. var StringStream = (function StringStreamClosure() {
  34818. function StringStream(str) {
  34819. var length = str.length;
  34820. var bytes = new Uint8Array(length);
  34821. for (var n = 0; n < length; ++n) {
  34822. bytes[n] = str.charCodeAt(n);
  34823. }
  34824. Stream.call(this, bytes);
  34825. }
  34826. StringStream.prototype = Stream.prototype;
  34827. return StringStream;
  34828. })();
  34829. // super class for the decoding streams
  34830. var DecodeStream = (function DecodeStreamClosure() {
  34831. // Lots of DecodeStreams are created whose buffers are never used. For these
  34832. // we share a single empty buffer. This is (a) space-efficient and (b) avoids
  34833. // having special cases that would be required if we used |null| for an empty
  34834. // buffer.
  34835. var emptyBuffer = new Uint8Array(0);
  34836. function DecodeStream(maybeMinBufferLength) {
  34837. this.pos = 0;
  34838. this.bufferLength = 0;
  34839. this.eof = false;
  34840. this.buffer = emptyBuffer;
  34841. this.minBufferLength = 512;
  34842. if (maybeMinBufferLength) {
  34843. // Compute the first power of two that is as big as maybeMinBufferLength.
  34844. while (this.minBufferLength < maybeMinBufferLength) {
  34845. this.minBufferLength *= 2;
  34846. }
  34847. }
  34848. }
  34849. DecodeStream.prototype = {
  34850. get isEmpty() {
  34851. while (!this.eof && this.bufferLength === 0) {
  34852. this.readBlock();
  34853. }
  34854. return this.bufferLength === 0;
  34855. },
  34856. ensureBuffer: function DecodeStream_ensureBuffer(requested) {
  34857. var buffer = this.buffer;
  34858. if (requested <= buffer.byteLength) {
  34859. return buffer;
  34860. }
  34861. var size = this.minBufferLength;
  34862. while (size < requested) {
  34863. size *= 2;
  34864. }
  34865. var buffer2 = new Uint8Array(size);
  34866. buffer2.set(buffer);
  34867. return (this.buffer = buffer2);
  34868. },
  34869. getByte: function DecodeStream_getByte() {
  34870. var pos = this.pos;
  34871. while (this.bufferLength <= pos) {
  34872. if (this.eof) {
  34873. return -1;
  34874. }
  34875. this.readBlock();
  34876. }
  34877. return this.buffer[this.pos++];
  34878. },
  34879. getUint16: function DecodeStream_getUint16() {
  34880. var b0 = this.getByte();
  34881. var b1 = this.getByte();
  34882. return (b0 << 8) + b1;
  34883. },
  34884. getInt32: function DecodeStream_getInt32() {
  34885. var b0 = this.getByte();
  34886. var b1 = this.getByte();
  34887. var b2 = this.getByte();
  34888. var b3 = this.getByte();
  34889. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  34890. },
  34891. getBytes: function DecodeStream_getBytes(length) {
  34892. var end, pos = this.pos;
  34893. if (length) {
  34894. this.ensureBuffer(pos + length);
  34895. end = pos + length;
  34896. while (!this.eof && this.bufferLength < end) {
  34897. this.readBlock();
  34898. }
  34899. var bufEnd = this.bufferLength;
  34900. if (end > bufEnd) {
  34901. end = bufEnd;
  34902. }
  34903. } else {
  34904. while (!this.eof) {
  34905. this.readBlock();
  34906. }
  34907. end = this.bufferLength;
  34908. }
  34909. this.pos = end;
  34910. return this.buffer.subarray(pos, end);
  34911. },
  34912. peekByte: function DecodeStream_peekByte() {
  34913. var peekedByte = this.getByte();
  34914. this.pos--;
  34915. return peekedByte;
  34916. },
  34917. peekBytes: function DecodeStream_peekBytes(length) {
  34918. var bytes = this.getBytes(length);
  34919. this.pos -= bytes.length;
  34920. return bytes;
  34921. },
  34922. makeSubStream: function DecodeStream_makeSubStream(start, length, dict) {
  34923. var end = start + length;
  34924. while (this.bufferLength <= end && !this.eof) {
  34925. this.readBlock();
  34926. }
  34927. return new Stream(this.buffer, start, length, dict);
  34928. },
  34929. skip: function DecodeStream_skip(n) {
  34930. if (!n) {
  34931. n = 1;
  34932. }
  34933. this.pos += n;
  34934. },
  34935. reset: function DecodeStream_reset() {
  34936. this.pos = 0;
  34937. },
  34938. getBaseStreams: function DecodeStream_getBaseStreams() {
  34939. if (this.str && this.str.getBaseStreams) {
  34940. return this.str.getBaseStreams();
  34941. }
  34942. return [];
  34943. }
  34944. };
  34945. return DecodeStream;
  34946. })();
  34947. var StreamsSequenceStream = (function StreamsSequenceStreamClosure() {
  34948. function StreamsSequenceStream(streams) {
  34949. this.streams = streams;
  34950. DecodeStream.call(this, /* maybeLength = */ null);
  34951. }
  34952. StreamsSequenceStream.prototype = Object.create(DecodeStream.prototype);
  34953. StreamsSequenceStream.prototype.readBlock =
  34954. function streamSequenceStreamReadBlock() {
  34955. var streams = this.streams;
  34956. if (streams.length === 0) {
  34957. this.eof = true;
  34958. return;
  34959. }
  34960. var stream = streams.shift();
  34961. var chunk = stream.getBytes();
  34962. var bufferLength = this.bufferLength;
  34963. var newLength = bufferLength + chunk.length;
  34964. var buffer = this.ensureBuffer(newLength);
  34965. buffer.set(chunk, bufferLength);
  34966. this.bufferLength = newLength;
  34967. };
  34968. StreamsSequenceStream.prototype.getBaseStreams =
  34969. function StreamsSequenceStream_getBaseStreams() {
  34970. var baseStreams = [];
  34971. for (var i = 0, ii = this.streams.length; i < ii; i++) {
  34972. var stream = this.streams[i];
  34973. if (stream.getBaseStreams) {
  34974. Util.appendToArray(baseStreams, stream.getBaseStreams());
  34975. }
  34976. }
  34977. return baseStreams;
  34978. };
  34979. return StreamsSequenceStream;
  34980. })();
  34981. var FlateStream = (function FlateStreamClosure() {
  34982. var codeLenCodeMap = new Uint32Array([
  34983. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  34984. ]);
  34985. var lengthDecode = new Uint32Array([
  34986. 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
  34987. 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
  34988. 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
  34989. 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
  34990. ]);
  34991. var distDecode = new Uint32Array([
  34992. 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
  34993. 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
  34994. 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
  34995. 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
  34996. ]);
  34997. var fixedLitCodeTab = [new Uint32Array([
  34998. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
  34999. 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
  35000. 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
  35001. 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
  35002. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
  35003. 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
  35004. 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
  35005. 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
  35006. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
  35007. 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
  35008. 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
  35009. 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
  35010. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
  35011. 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
  35012. 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
  35013. 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
  35014. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
  35015. 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
  35016. 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
  35017. 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
  35018. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
  35019. 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
  35020. 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
  35021. 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
  35022. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
  35023. 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
  35024. 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
  35025. 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
  35026. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
  35027. 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
  35028. 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
  35029. 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
  35030. 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
  35031. 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
  35032. 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
  35033. 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
  35034. 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
  35035. 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
  35036. 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
  35037. 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
  35038. 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
  35039. 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
  35040. 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
  35041. 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
  35042. 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
  35043. 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
  35044. 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
  35045. 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
  35046. 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
  35047. 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
  35048. 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
  35049. 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
  35050. 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
  35051. 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
  35052. 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
  35053. 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
  35054. 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
  35055. 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
  35056. 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
  35057. 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
  35058. 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
  35059. 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
  35060. 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
  35061. 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
  35062. ]), 9];
  35063. var fixedDistCodeTab = [new Uint32Array([
  35064. 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
  35065. 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
  35066. 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
  35067. 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
  35068. ]), 5];
  35069. function FlateStream(str, maybeLength) {
  35070. this.str = str;
  35071. this.dict = str.dict;
  35072. var cmf = str.getByte();
  35073. var flg = str.getByte();
  35074. if (cmf === -1 || flg === -1) {
  35075. error('Invalid header in flate stream: ' + cmf + ', ' + flg);
  35076. }
  35077. if ((cmf & 0x0f) !== 0x08) {
  35078. error('Unknown compression method in flate stream: ' + cmf + ', ' + flg);
  35079. }
  35080. if ((((cmf << 8) + flg) % 31) !== 0) {
  35081. error('Bad FCHECK in flate stream: ' + cmf + ', ' + flg);
  35082. }
  35083. if (flg & 0x20) {
  35084. error('FDICT bit set in flate stream: ' + cmf + ', ' + flg);
  35085. }
  35086. this.codeSize = 0;
  35087. this.codeBuf = 0;
  35088. DecodeStream.call(this, maybeLength);
  35089. }
  35090. FlateStream.prototype = Object.create(DecodeStream.prototype);
  35091. FlateStream.prototype.getBits = function FlateStream_getBits(bits) {
  35092. var str = this.str;
  35093. var codeSize = this.codeSize;
  35094. var codeBuf = this.codeBuf;
  35095. var b;
  35096. while (codeSize < bits) {
  35097. if ((b = str.getByte()) === -1) {
  35098. error('Bad encoding in flate stream');
  35099. }
  35100. codeBuf |= b << codeSize;
  35101. codeSize += 8;
  35102. }
  35103. b = codeBuf & ((1 << bits) - 1);
  35104. this.codeBuf = codeBuf >> bits;
  35105. this.codeSize = codeSize -= bits;
  35106. return b;
  35107. };
  35108. FlateStream.prototype.getCode = function FlateStream_getCode(table) {
  35109. var str = this.str;
  35110. var codes = table[0];
  35111. var maxLen = table[1];
  35112. var codeSize = this.codeSize;
  35113. var codeBuf = this.codeBuf;
  35114. var b;
  35115. while (codeSize < maxLen) {
  35116. if ((b = str.getByte()) === -1) {
  35117. // premature end of stream. code might however still be valid.
  35118. // codeSize < codeLen check below guards against incomplete codeVal.
  35119. break;
  35120. }
  35121. codeBuf |= (b << codeSize);
  35122. codeSize += 8;
  35123. }
  35124. var code = codes[codeBuf & ((1 << maxLen) - 1)];
  35125. var codeLen = code >> 16;
  35126. var codeVal = code & 0xffff;
  35127. if (codeLen < 1 || codeSize < codeLen) {
  35128. error('Bad encoding in flate stream');
  35129. }
  35130. this.codeBuf = (codeBuf >> codeLen);
  35131. this.codeSize = (codeSize - codeLen);
  35132. return codeVal;
  35133. };
  35134. FlateStream.prototype.generateHuffmanTable =
  35135. function flateStreamGenerateHuffmanTable(lengths) {
  35136. var n = lengths.length;
  35137. // find max code length
  35138. var maxLen = 0;
  35139. var i;
  35140. for (i = 0; i < n; ++i) {
  35141. if (lengths[i] > maxLen) {
  35142. maxLen = lengths[i];
  35143. }
  35144. }
  35145. // build the table
  35146. var size = 1 << maxLen;
  35147. var codes = new Uint32Array(size);
  35148. for (var len = 1, code = 0, skip = 2;
  35149. len <= maxLen;
  35150. ++len, code <<= 1, skip <<= 1) {
  35151. for (var val = 0; val < n; ++val) {
  35152. if (lengths[val] === len) {
  35153. // bit-reverse the code
  35154. var code2 = 0;
  35155. var t = code;
  35156. for (i = 0; i < len; ++i) {
  35157. code2 = (code2 << 1) | (t & 1);
  35158. t >>= 1;
  35159. }
  35160. // fill the table entries
  35161. for (i = code2; i < size; i += skip) {
  35162. codes[i] = (len << 16) | val;
  35163. }
  35164. ++code;
  35165. }
  35166. }
  35167. }
  35168. return [codes, maxLen];
  35169. };
  35170. FlateStream.prototype.readBlock = function FlateStream_readBlock() {
  35171. var buffer, len;
  35172. var str = this.str;
  35173. // read block header
  35174. var hdr = this.getBits(3);
  35175. if (hdr & 1) {
  35176. this.eof = true;
  35177. }
  35178. hdr >>= 1;
  35179. if (hdr === 0) { // uncompressed block
  35180. var b;
  35181. if ((b = str.getByte()) === -1) {
  35182. error('Bad block header in flate stream');
  35183. }
  35184. var blockLen = b;
  35185. if ((b = str.getByte()) === -1) {
  35186. error('Bad block header in flate stream');
  35187. }
  35188. blockLen |= (b << 8);
  35189. if ((b = str.getByte()) === -1) {
  35190. error('Bad block header in flate stream');
  35191. }
  35192. var check = b;
  35193. if ((b = str.getByte()) === -1) {
  35194. error('Bad block header in flate stream');
  35195. }
  35196. check |= (b << 8);
  35197. if (check !== (~blockLen & 0xffff) &&
  35198. (blockLen !== 0 || check !== 0)) {
  35199. // Ignoring error for bad "empty" block (see issue 1277)
  35200. error('Bad uncompressed block length in flate stream');
  35201. }
  35202. this.codeBuf = 0;
  35203. this.codeSize = 0;
  35204. var bufferLength = this.bufferLength;
  35205. buffer = this.ensureBuffer(bufferLength + blockLen);
  35206. var end = bufferLength + blockLen;
  35207. this.bufferLength = end;
  35208. if (blockLen === 0) {
  35209. if (str.peekByte() === -1) {
  35210. this.eof = true;
  35211. }
  35212. } else {
  35213. for (var n = bufferLength; n < end; ++n) {
  35214. if ((b = str.getByte()) === -1) {
  35215. this.eof = true;
  35216. break;
  35217. }
  35218. buffer[n] = b;
  35219. }
  35220. }
  35221. return;
  35222. }
  35223. var litCodeTable;
  35224. var distCodeTable;
  35225. if (hdr === 1) { // compressed block, fixed codes
  35226. litCodeTable = fixedLitCodeTab;
  35227. distCodeTable = fixedDistCodeTab;
  35228. } else if (hdr === 2) { // compressed block, dynamic codes
  35229. var numLitCodes = this.getBits(5) + 257;
  35230. var numDistCodes = this.getBits(5) + 1;
  35231. var numCodeLenCodes = this.getBits(4) + 4;
  35232. // build the code lengths code table
  35233. var codeLenCodeLengths = new Uint8Array(codeLenCodeMap.length);
  35234. var i;
  35235. for (i = 0; i < numCodeLenCodes; ++i) {
  35236. codeLenCodeLengths[codeLenCodeMap[i]] = this.getBits(3);
  35237. }
  35238. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
  35239. // build the literal and distance code tables
  35240. len = 0;
  35241. i = 0;
  35242. var codes = numLitCodes + numDistCodes;
  35243. var codeLengths = new Uint8Array(codes);
  35244. var bitsLength, bitsOffset, what;
  35245. while (i < codes) {
  35246. var code = this.getCode(codeLenCodeTab);
  35247. if (code === 16) {
  35248. bitsLength = 2; bitsOffset = 3; what = len;
  35249. } else if (code === 17) {
  35250. bitsLength = 3; bitsOffset = 3; what = (len = 0);
  35251. } else if (code === 18) {
  35252. bitsLength = 7; bitsOffset = 11; what = (len = 0);
  35253. } else {
  35254. codeLengths[i++] = len = code;
  35255. continue;
  35256. }
  35257. var repeatLength = this.getBits(bitsLength) + bitsOffset;
  35258. while (repeatLength-- > 0) {
  35259. codeLengths[i++] = what;
  35260. }
  35261. }
  35262. litCodeTable =
  35263. this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes));
  35264. distCodeTable =
  35265. this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes));
  35266. } else {
  35267. error('Unknown block type in flate stream');
  35268. }
  35269. buffer = this.buffer;
  35270. var limit = buffer ? buffer.length : 0;
  35271. var pos = this.bufferLength;
  35272. while (true) {
  35273. var code1 = this.getCode(litCodeTable);
  35274. if (code1 < 256) {
  35275. if (pos + 1 >= limit) {
  35276. buffer = this.ensureBuffer(pos + 1);
  35277. limit = buffer.length;
  35278. }
  35279. buffer[pos++] = code1;
  35280. continue;
  35281. }
  35282. if (code1 === 256) {
  35283. this.bufferLength = pos;
  35284. return;
  35285. }
  35286. code1 -= 257;
  35287. code1 = lengthDecode[code1];
  35288. var code2 = code1 >> 16;
  35289. if (code2 > 0) {
  35290. code2 = this.getBits(code2);
  35291. }
  35292. len = (code1 & 0xffff) + code2;
  35293. code1 = this.getCode(distCodeTable);
  35294. code1 = distDecode[code1];
  35295. code2 = code1 >> 16;
  35296. if (code2 > 0) {
  35297. code2 = this.getBits(code2);
  35298. }
  35299. var dist = (code1 & 0xffff) + code2;
  35300. if (pos + len >= limit) {
  35301. buffer = this.ensureBuffer(pos + len);
  35302. limit = buffer.length;
  35303. }
  35304. for (var k = 0; k < len; ++k, ++pos) {
  35305. buffer[pos] = buffer[pos - dist];
  35306. }
  35307. }
  35308. };
  35309. return FlateStream;
  35310. })();
  35311. var PredictorStream = (function PredictorStreamClosure() {
  35312. function PredictorStream(str, maybeLength, params) {
  35313. var predictor = this.predictor = params.get('Predictor') || 1;
  35314. if (predictor <= 1) {
  35315. return str; // no prediction
  35316. }
  35317. if (predictor !== 2 && (predictor < 10 || predictor > 15)) {
  35318. error('Unsupported predictor: ' + predictor);
  35319. }
  35320. if (predictor === 2) {
  35321. this.readBlock = this.readBlockTiff;
  35322. } else {
  35323. this.readBlock = this.readBlockPng;
  35324. }
  35325. this.str = str;
  35326. this.dict = str.dict;
  35327. var colors = this.colors = params.get('Colors') || 1;
  35328. var bits = this.bits = params.get('BitsPerComponent') || 8;
  35329. var columns = this.columns = params.get('Columns') || 1;
  35330. this.pixBytes = (colors * bits + 7) >> 3;
  35331. this.rowBytes = (columns * colors * bits + 7) >> 3;
  35332. DecodeStream.call(this, maybeLength);
  35333. return this;
  35334. }
  35335. PredictorStream.prototype = Object.create(DecodeStream.prototype);
  35336. PredictorStream.prototype.readBlockTiff =
  35337. function predictorStreamReadBlockTiff() {
  35338. var rowBytes = this.rowBytes;
  35339. var bufferLength = this.bufferLength;
  35340. var buffer = this.ensureBuffer(bufferLength + rowBytes);
  35341. var bits = this.bits;
  35342. var colors = this.colors;
  35343. var rawBytes = this.str.getBytes(rowBytes);
  35344. this.eof = !rawBytes.length;
  35345. if (this.eof) {
  35346. return;
  35347. }
  35348. var inbuf = 0, outbuf = 0;
  35349. var inbits = 0, outbits = 0;
  35350. var pos = bufferLength;
  35351. var i;
  35352. if (bits === 1) {
  35353. for (i = 0; i < rowBytes; ++i) {
  35354. var c = rawBytes[i];
  35355. inbuf = (inbuf << 8) | c;
  35356. // bitwise addition is exclusive or
  35357. // first shift inbuf and then add
  35358. buffer[pos++] = (c ^ (inbuf >> colors)) & 0xFF;
  35359. // truncate inbuf (assumes colors < 16)
  35360. inbuf &= 0xFFFF;
  35361. }
  35362. } else if (bits === 8) {
  35363. for (i = 0; i < colors; ++i) {
  35364. buffer[pos++] = rawBytes[i];
  35365. }
  35366. for (; i < rowBytes; ++i) {
  35367. buffer[pos] = buffer[pos - colors] + rawBytes[i];
  35368. pos++;
  35369. }
  35370. } else {
  35371. var compArray = new Uint8Array(colors + 1);
  35372. var bitMask = (1 << bits) - 1;
  35373. var j = 0, k = bufferLength;
  35374. var columns = this.columns;
  35375. for (i = 0; i < columns; ++i) {
  35376. for (var kk = 0; kk < colors; ++kk) {
  35377. if (inbits < bits) {
  35378. inbuf = (inbuf << 8) | (rawBytes[j++] & 0xFF);
  35379. inbits += 8;
  35380. }
  35381. compArray[kk] = (compArray[kk] +
  35382. (inbuf >> (inbits - bits))) & bitMask;
  35383. inbits -= bits;
  35384. outbuf = (outbuf << bits) | compArray[kk];
  35385. outbits += bits;
  35386. if (outbits >= 8) {
  35387. buffer[k++] = (outbuf >> (outbits - 8)) & 0xFF;
  35388. outbits -= 8;
  35389. }
  35390. }
  35391. }
  35392. if (outbits > 0) {
  35393. buffer[k++] = (outbuf << (8 - outbits)) +
  35394. (inbuf & ((1 << (8 - outbits)) - 1));
  35395. }
  35396. }
  35397. this.bufferLength += rowBytes;
  35398. };
  35399. PredictorStream.prototype.readBlockPng =
  35400. function predictorStreamReadBlockPng() {
  35401. var rowBytes = this.rowBytes;
  35402. var pixBytes = this.pixBytes;
  35403. var predictor = this.str.getByte();
  35404. var rawBytes = this.str.getBytes(rowBytes);
  35405. this.eof = !rawBytes.length;
  35406. if (this.eof) {
  35407. return;
  35408. }
  35409. var bufferLength = this.bufferLength;
  35410. var buffer = this.ensureBuffer(bufferLength + rowBytes);
  35411. var prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength);
  35412. if (prevRow.length === 0) {
  35413. prevRow = new Uint8Array(rowBytes);
  35414. }
  35415. var i, j = bufferLength, up, c;
  35416. switch (predictor) {
  35417. case 0:
  35418. for (i = 0; i < rowBytes; ++i) {
  35419. buffer[j++] = rawBytes[i];
  35420. }
  35421. break;
  35422. case 1:
  35423. for (i = 0; i < pixBytes; ++i) {
  35424. buffer[j++] = rawBytes[i];
  35425. }
  35426. for (; i < rowBytes; ++i) {
  35427. buffer[j] = (buffer[j - pixBytes] + rawBytes[i]) & 0xFF;
  35428. j++;
  35429. }
  35430. break;
  35431. case 2:
  35432. for (i = 0; i < rowBytes; ++i) {
  35433. buffer[j++] = (prevRow[i] + rawBytes[i]) & 0xFF;
  35434. }
  35435. break;
  35436. case 3:
  35437. for (i = 0; i < pixBytes; ++i) {
  35438. buffer[j++] = (prevRow[i] >> 1) + rawBytes[i];
  35439. }
  35440. for (; i < rowBytes; ++i) {
  35441. buffer[j] = (((prevRow[i] + buffer[j - pixBytes]) >> 1) +
  35442. rawBytes[i]) & 0xFF;
  35443. j++;
  35444. }
  35445. break;
  35446. case 4:
  35447. // we need to save the up left pixels values. the simplest way
  35448. // is to create a new buffer
  35449. for (i = 0; i < pixBytes; ++i) {
  35450. up = prevRow[i];
  35451. c = rawBytes[i];
  35452. buffer[j++] = up + c;
  35453. }
  35454. for (; i < rowBytes; ++i) {
  35455. up = prevRow[i];
  35456. var upLeft = prevRow[i - pixBytes];
  35457. var left = buffer[j - pixBytes];
  35458. var p = left + up - upLeft;
  35459. var pa = p - left;
  35460. if (pa < 0) {
  35461. pa = -pa;
  35462. }
  35463. var pb = p - up;
  35464. if (pb < 0) {
  35465. pb = -pb;
  35466. }
  35467. var pc = p - upLeft;
  35468. if (pc < 0) {
  35469. pc = -pc;
  35470. }
  35471. c = rawBytes[i];
  35472. if (pa <= pb && pa <= pc) {
  35473. buffer[j++] = left + c;
  35474. } else if (pb <= pc) {
  35475. buffer[j++] = up + c;
  35476. } else {
  35477. buffer[j++] = upLeft + c;
  35478. }
  35479. }
  35480. break;
  35481. default:
  35482. error('Unsupported predictor: ' + predictor);
  35483. }
  35484. this.bufferLength += rowBytes;
  35485. };
  35486. return PredictorStream;
  35487. })();
  35488. /**
  35489. * Depending on the type of JPEG a JpegStream is handled in different ways. For
  35490. * JPEG's that are supported natively such as DeviceGray and DeviceRGB the image
  35491. * data is stored and then loaded by the browser. For unsupported JPEG's we use
  35492. * a library to decode these images and the stream behaves like all the other
  35493. * DecodeStreams.
  35494. */
  35495. var JpegStream = (function JpegStreamClosure() {
  35496. function JpegStream(stream, maybeLength, dict, xref) {
  35497. // Some images may contain 'junk' before the SOI (start-of-image) marker.
  35498. // Note: this seems to mainly affect inline images.
  35499. var ch;
  35500. while ((ch = stream.getByte()) !== -1) {
  35501. if (ch === 0xFF) { // Find the first byte of the SOI marker (0xFFD8).
  35502. stream.skip(-1); // Reset the stream position to the SOI.
  35503. break;
  35504. }
  35505. }
  35506. this.stream = stream;
  35507. this.maybeLength = maybeLength;
  35508. this.dict = dict;
  35509. DecodeStream.call(this, maybeLength);
  35510. }
  35511. JpegStream.prototype = Object.create(DecodeStream.prototype);
  35512. Object.defineProperty(JpegStream.prototype, 'bytes', {
  35513. get: function JpegStream_bytes() {
  35514. // If this.maybeLength is null, we'll get the entire stream.
  35515. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  35516. },
  35517. configurable: true
  35518. });
  35519. JpegStream.prototype.ensureBuffer = function JpegStream_ensureBuffer(req) {
  35520. if (this.bufferLength) {
  35521. return;
  35522. }
  35523. try {
  35524. var jpegImage = new JpegImage();
  35525. // checking if values needs to be transformed before conversion
  35526. if (this.forceRGB && this.dict && isArray(this.dict.get('Decode'))) {
  35527. var decodeArr = this.dict.get('Decode');
  35528. var bitsPerComponent = this.dict.get('BitsPerComponent') || 8;
  35529. var decodeArrLength = decodeArr.length;
  35530. var transform = new Int32Array(decodeArrLength);
  35531. var transformNeeded = false;
  35532. var maxValue = (1 << bitsPerComponent) - 1;
  35533. for (var i = 0; i < decodeArrLength; i += 2) {
  35534. transform[i] = ((decodeArr[i + 1] - decodeArr[i]) * 256) | 0;
  35535. transform[i + 1] = (decodeArr[i] * maxValue) | 0;
  35536. if (transform[i] !== 256 || transform[i + 1] !== 0) {
  35537. transformNeeded = true;
  35538. }
  35539. }
  35540. if (transformNeeded) {
  35541. jpegImage.decodeTransform = transform;
  35542. }
  35543. }
  35544. jpegImage.parse(this.bytes);
  35545. var data = jpegImage.getData(this.drawWidth, this.drawHeight,
  35546. this.forceRGB);
  35547. this.buffer = data;
  35548. this.bufferLength = data.length;
  35549. this.eof = true;
  35550. } catch (e) {
  35551. error('JPEG error: ' + e);
  35552. }
  35553. };
  35554. JpegStream.prototype.getBytes = function JpegStream_getBytes(length) {
  35555. this.ensureBuffer();
  35556. return this.buffer;
  35557. };
  35558. JpegStream.prototype.getIR = function JpegStream_getIR() {
  35559. return PDFJS.createObjectURL(this.bytes, 'image/jpeg');
  35560. };
  35561. /**
  35562. * Checks if the image can be decoded and displayed by the browser without any
  35563. * further processing such as color space conversions.
  35564. */
  35565. JpegStream.prototype.isNativelySupported =
  35566. function JpegStream_isNativelySupported(xref, res) {
  35567. var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);
  35568. return cs.name === 'DeviceGray' || cs.name === 'DeviceRGB';
  35569. };
  35570. /**
  35571. * Checks if the image can be decoded by the browser.
  35572. */
  35573. JpegStream.prototype.isNativelyDecodable =
  35574. function JpegStream_isNativelyDecodable(xref, res) {
  35575. var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);
  35576. var numComps = cs.numComps;
  35577. return numComps === 1 || numComps === 3;
  35578. };
  35579. return JpegStream;
  35580. })();
  35581. /**
  35582. * For JPEG 2000's we use a library to decode these images and
  35583. * the stream behaves like all the other DecodeStreams.
  35584. */
  35585. var JpxStream = (function JpxStreamClosure() {
  35586. function JpxStream(stream, maybeLength, dict) {
  35587. this.stream = stream;
  35588. this.maybeLength = maybeLength;
  35589. this.dict = dict;
  35590. DecodeStream.call(this, maybeLength);
  35591. }
  35592. JpxStream.prototype = Object.create(DecodeStream.prototype);
  35593. Object.defineProperty(JpxStream.prototype, 'bytes', {
  35594. get: function JpxStream_bytes() {
  35595. // If this.maybeLength is null, we'll get the entire stream.
  35596. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  35597. },
  35598. configurable: true
  35599. });
  35600. JpxStream.prototype.ensureBuffer = function JpxStream_ensureBuffer(req) {
  35601. if (this.bufferLength) {
  35602. return;
  35603. }
  35604. var jpxImage = new JpxImage();
  35605. jpxImage.parse(this.bytes);
  35606. var width = jpxImage.width;
  35607. var height = jpxImage.height;
  35608. var componentsCount = jpxImage.componentsCount;
  35609. var tileCount = jpxImage.tiles.length;
  35610. if (tileCount === 1) {
  35611. this.buffer = jpxImage.tiles[0].items;
  35612. } else {
  35613. var data = new Uint8Array(width * height * componentsCount);
  35614. for (var k = 0; k < tileCount; k++) {
  35615. var tileComponents = jpxImage.tiles[k];
  35616. var tileWidth = tileComponents.width;
  35617. var tileHeight = tileComponents.height;
  35618. var tileLeft = tileComponents.left;
  35619. var tileTop = tileComponents.top;
  35620. var src = tileComponents.items;
  35621. var srcPosition = 0;
  35622. var dataPosition = (width * tileTop + tileLeft) * componentsCount;
  35623. var imgRowSize = width * componentsCount;
  35624. var tileRowSize = tileWidth * componentsCount;
  35625. for (var j = 0; j < tileHeight; j++) {
  35626. var rowBytes = src.subarray(srcPosition, srcPosition + tileRowSize);
  35627. data.set(rowBytes, dataPosition);
  35628. srcPosition += tileRowSize;
  35629. dataPosition += imgRowSize;
  35630. }
  35631. }
  35632. this.buffer = data;
  35633. }
  35634. this.bufferLength = this.buffer.length;
  35635. this.eof = true;
  35636. };
  35637. return JpxStream;
  35638. })();
  35639. /**
  35640. * For JBIG2's we use a library to decode these images and
  35641. * the stream behaves like all the other DecodeStreams.
  35642. */
  35643. var Jbig2Stream = (function Jbig2StreamClosure() {
  35644. function Jbig2Stream(stream, maybeLength, dict) {
  35645. this.stream = stream;
  35646. this.maybeLength = maybeLength;
  35647. this.dict = dict;
  35648. DecodeStream.call(this, maybeLength);
  35649. }
  35650. Jbig2Stream.prototype = Object.create(DecodeStream.prototype);
  35651. Object.defineProperty(Jbig2Stream.prototype, 'bytes', {
  35652. get: function Jbig2Stream_bytes() {
  35653. // If this.maybeLength is null, we'll get the entire stream.
  35654. return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));
  35655. },
  35656. configurable: true
  35657. });
  35658. Jbig2Stream.prototype.ensureBuffer = function Jbig2Stream_ensureBuffer(req) {
  35659. if (this.bufferLength) {
  35660. return;
  35661. }
  35662. var jbig2Image = new Jbig2Image();
  35663. var chunks = [], xref = this.dict.xref;
  35664. var decodeParams = xref.fetchIfRef(this.dict.get('DecodeParms'));
  35665. // According to the PDF specification, DecodeParms can be either
  35666. // a dictionary, or an array whose elements are dictionaries.
  35667. if (isArray(decodeParams)) {
  35668. if (decodeParams.length > 1) {
  35669. warn('JBIG2 - \'DecodeParms\' array with multiple elements ' +
  35670. 'not supported.');
  35671. }
  35672. decodeParams = xref.fetchIfRef(decodeParams[0]);
  35673. }
  35674. if (decodeParams && decodeParams.has('JBIG2Globals')) {
  35675. var globalsStream = decodeParams.get('JBIG2Globals');
  35676. var globals = globalsStream.getBytes();
  35677. chunks.push({data: globals, start: 0, end: globals.length});
  35678. }
  35679. chunks.push({data: this.bytes, start: 0, end: this.bytes.length});
  35680. var data = jbig2Image.parseChunks(chunks);
  35681. var dataLength = data.length;
  35682. // JBIG2 had black as 1 and white as 0, inverting the colors
  35683. for (var i = 0; i < dataLength; i++) {
  35684. data[i] ^= 0xFF;
  35685. }
  35686. this.buffer = data;
  35687. this.bufferLength = dataLength;
  35688. this.eof = true;
  35689. };
  35690. return Jbig2Stream;
  35691. })();
  35692. var DecryptStream = (function DecryptStreamClosure() {
  35693. function DecryptStream(str, maybeLength, decrypt) {
  35694. this.str = str;
  35695. this.dict = str.dict;
  35696. this.decrypt = decrypt;
  35697. this.nextChunk = null;
  35698. this.initialized = false;
  35699. DecodeStream.call(this, maybeLength);
  35700. }
  35701. var chunkSize = 512;
  35702. DecryptStream.prototype = Object.create(DecodeStream.prototype);
  35703. DecryptStream.prototype.readBlock = function DecryptStream_readBlock() {
  35704. var chunk;
  35705. if (this.initialized) {
  35706. chunk = this.nextChunk;
  35707. } else {
  35708. chunk = this.str.getBytes(chunkSize);
  35709. this.initialized = true;
  35710. }
  35711. if (!chunk || chunk.length === 0) {
  35712. this.eof = true;
  35713. return;
  35714. }
  35715. this.nextChunk = this.str.getBytes(chunkSize);
  35716. var hasMoreData = this.nextChunk && this.nextChunk.length > 0;
  35717. var decrypt = this.decrypt;
  35718. chunk = decrypt(chunk, !hasMoreData);
  35719. var bufferLength = this.bufferLength;
  35720. var i, n = chunk.length;
  35721. var buffer = this.ensureBuffer(bufferLength + n);
  35722. for (i = 0; i < n; i++) {
  35723. buffer[bufferLength++] = chunk[i];
  35724. }
  35725. this.bufferLength = bufferLength;
  35726. };
  35727. return DecryptStream;
  35728. })();
  35729. var Ascii85Stream = (function Ascii85StreamClosure() {
  35730. function Ascii85Stream(str, maybeLength) {
  35731. this.str = str;
  35732. this.dict = str.dict;
  35733. this.input = new Uint8Array(5);
  35734. // Most streams increase in size when decoded, but Ascii85 streams
  35735. // typically shrink by ~20%.
  35736. if (maybeLength) {
  35737. maybeLength = 0.8 * maybeLength;
  35738. }
  35739. DecodeStream.call(this, maybeLength);
  35740. }
  35741. Ascii85Stream.prototype = Object.create(DecodeStream.prototype);
  35742. Ascii85Stream.prototype.readBlock = function Ascii85Stream_readBlock() {
  35743. var TILDA_CHAR = 0x7E; // '~'
  35744. var Z_LOWER_CHAR = 0x7A; // 'z'
  35745. var EOF = -1;
  35746. var str = this.str;
  35747. var c = str.getByte();
  35748. while (Lexer.isSpace(c)) {
  35749. c = str.getByte();
  35750. }
  35751. if (c === EOF || c === TILDA_CHAR) {
  35752. this.eof = true;
  35753. return;
  35754. }
  35755. var bufferLength = this.bufferLength, buffer;
  35756. var i;
  35757. // special code for z
  35758. if (c === Z_LOWER_CHAR) {
  35759. buffer = this.ensureBuffer(bufferLength + 4);
  35760. for (i = 0; i < 4; ++i) {
  35761. buffer[bufferLength + i] = 0;
  35762. }
  35763. this.bufferLength += 4;
  35764. } else {
  35765. var input = this.input;
  35766. input[0] = c;
  35767. for (i = 1; i < 5; ++i) {
  35768. c = str.getByte();
  35769. while (Lexer.isSpace(c)) {
  35770. c = str.getByte();
  35771. }
  35772. input[i] = c;
  35773. if (c === EOF || c === TILDA_CHAR) {
  35774. break;
  35775. }
  35776. }
  35777. buffer = this.ensureBuffer(bufferLength + i - 1);
  35778. this.bufferLength += i - 1;
  35779. // partial ending;
  35780. if (i < 5) {
  35781. for (; i < 5; ++i) {
  35782. input[i] = 0x21 + 84;
  35783. }
  35784. this.eof = true;
  35785. }
  35786. var t = 0;
  35787. for (i = 0; i < 5; ++i) {
  35788. t = t * 85 + (input[i] - 0x21);
  35789. }
  35790. for (i = 3; i >= 0; --i) {
  35791. buffer[bufferLength + i] = t & 0xFF;
  35792. t >>= 8;
  35793. }
  35794. }
  35795. };
  35796. return Ascii85Stream;
  35797. })();
  35798. var AsciiHexStream = (function AsciiHexStreamClosure() {
  35799. function AsciiHexStream(str, maybeLength) {
  35800. this.str = str;
  35801. this.dict = str.dict;
  35802. this.firstDigit = -1;
  35803. // Most streams increase in size when decoded, but AsciiHex streams shrink
  35804. // by 50%.
  35805. if (maybeLength) {
  35806. maybeLength = 0.5 * maybeLength;
  35807. }
  35808. DecodeStream.call(this, maybeLength);
  35809. }
  35810. AsciiHexStream.prototype = Object.create(DecodeStream.prototype);
  35811. AsciiHexStream.prototype.readBlock = function AsciiHexStream_readBlock() {
  35812. var UPSTREAM_BLOCK_SIZE = 8000;
  35813. var bytes = this.str.getBytes(UPSTREAM_BLOCK_SIZE);
  35814. if (!bytes.length) {
  35815. this.eof = true;
  35816. return;
  35817. }
  35818. var maxDecodeLength = (bytes.length + 1) >> 1;
  35819. var buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);
  35820. var bufferLength = this.bufferLength;
  35821. var firstDigit = this.firstDigit;
  35822. for (var i = 0, ii = bytes.length; i < ii; i++) {
  35823. var ch = bytes[i], digit;
  35824. if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
  35825. digit = ch & 0x0F;
  35826. } else if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
  35827. // 'A'-'Z', 'a'-'z'
  35828. digit = (ch & 0x0F) + 9;
  35829. } else if (ch === 0x3E) { // '>'
  35830. this.eof = true;
  35831. break;
  35832. } else { // probably whitespace
  35833. continue; // ignoring
  35834. }
  35835. if (firstDigit < 0) {
  35836. firstDigit = digit;
  35837. } else {
  35838. buffer[bufferLength++] = (firstDigit << 4) | digit;
  35839. firstDigit = -1;
  35840. }
  35841. }
  35842. if (firstDigit >= 0 && this.eof) {
  35843. // incomplete byte
  35844. buffer[bufferLength++] = (firstDigit << 4);
  35845. firstDigit = -1;
  35846. }
  35847. this.firstDigit = firstDigit;
  35848. this.bufferLength = bufferLength;
  35849. };
  35850. return AsciiHexStream;
  35851. })();
  35852. var RunLengthStream = (function RunLengthStreamClosure() {
  35853. function RunLengthStream(str, maybeLength) {
  35854. this.str = str;
  35855. this.dict = str.dict;
  35856. DecodeStream.call(this, maybeLength);
  35857. }
  35858. RunLengthStream.prototype = Object.create(DecodeStream.prototype);
  35859. RunLengthStream.prototype.readBlock = function RunLengthStream_readBlock() {
  35860. // The repeatHeader has following format. The first byte defines type of run
  35861. // and amount of bytes to repeat/copy: n = 0 through 127 - copy next n bytes
  35862. // (in addition to the second byte from the header), n = 129 through 255 -
  35863. // duplicate the second byte from the header (257 - n) times, n = 128 - end.
  35864. var repeatHeader = this.str.getBytes(2);
  35865. if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] === 128) {
  35866. this.eof = true;
  35867. return;
  35868. }
  35869. var buffer;
  35870. var bufferLength = this.bufferLength;
  35871. var n = repeatHeader[0];
  35872. if (n < 128) {
  35873. // copy n bytes
  35874. buffer = this.ensureBuffer(bufferLength + n + 1);
  35875. buffer[bufferLength++] = repeatHeader[1];
  35876. if (n > 0) {
  35877. var source = this.str.getBytes(n);
  35878. buffer.set(source, bufferLength);
  35879. bufferLength += n;
  35880. }
  35881. } else {
  35882. n = 257 - n;
  35883. var b = repeatHeader[1];
  35884. buffer = this.ensureBuffer(bufferLength + n + 1);
  35885. for (var i = 0; i < n; i++) {
  35886. buffer[bufferLength++] = b;
  35887. }
  35888. }
  35889. this.bufferLength = bufferLength;
  35890. };
  35891. return RunLengthStream;
  35892. })();
  35893. var CCITTFaxStream = (function CCITTFaxStreamClosure() {
  35894. var ccittEOL = -2;
  35895. var twoDimPass = 0;
  35896. var twoDimHoriz = 1;
  35897. var twoDimVert0 = 2;
  35898. var twoDimVertR1 = 3;
  35899. var twoDimVertL1 = 4;
  35900. var twoDimVertR2 = 5;
  35901. var twoDimVertL2 = 6;
  35902. var twoDimVertR3 = 7;
  35903. var twoDimVertL3 = 8;
  35904. var twoDimTable = [
  35905. [-1, -1], [-1, -1], // 000000x
  35906. [7, twoDimVertL3], // 0000010
  35907. [7, twoDimVertR3], // 0000011
  35908. [6, twoDimVertL2], [6, twoDimVertL2], // 000010x
  35909. [6, twoDimVertR2], [6, twoDimVertR2], // 000011x
  35910. [4, twoDimPass], [4, twoDimPass], // 0001xxx
  35911. [4, twoDimPass], [4, twoDimPass],
  35912. [4, twoDimPass], [4, twoDimPass],
  35913. [4, twoDimPass], [4, twoDimPass],
  35914. [3, twoDimHoriz], [3, twoDimHoriz], // 001xxxx
  35915. [3, twoDimHoriz], [3, twoDimHoriz],
  35916. [3, twoDimHoriz], [3, twoDimHoriz],
  35917. [3, twoDimHoriz], [3, twoDimHoriz],
  35918. [3, twoDimHoriz], [3, twoDimHoriz],
  35919. [3, twoDimHoriz], [3, twoDimHoriz],
  35920. [3, twoDimHoriz], [3, twoDimHoriz],
  35921. [3, twoDimHoriz], [3, twoDimHoriz],
  35922. [3, twoDimVertL1], [3, twoDimVertL1], // 010xxxx
  35923. [3, twoDimVertL1], [3, twoDimVertL1],
  35924. [3, twoDimVertL1], [3, twoDimVertL1],
  35925. [3, twoDimVertL1], [3, twoDimVertL1],
  35926. [3, twoDimVertL1], [3, twoDimVertL1],
  35927. [3, twoDimVertL1], [3, twoDimVertL1],
  35928. [3, twoDimVertL1], [3, twoDimVertL1],
  35929. [3, twoDimVertL1], [3, twoDimVertL1],
  35930. [3, twoDimVertR1], [3, twoDimVertR1], // 011xxxx
  35931. [3, twoDimVertR1], [3, twoDimVertR1],
  35932. [3, twoDimVertR1], [3, twoDimVertR1],
  35933. [3, twoDimVertR1], [3, twoDimVertR1],
  35934. [3, twoDimVertR1], [3, twoDimVertR1],
  35935. [3, twoDimVertR1], [3, twoDimVertR1],
  35936. [3, twoDimVertR1], [3, twoDimVertR1],
  35937. [3, twoDimVertR1], [3, twoDimVertR1],
  35938. [1, twoDimVert0], [1, twoDimVert0], // 1xxxxxx
  35939. [1, twoDimVert0], [1, twoDimVert0],
  35940. [1, twoDimVert0], [1, twoDimVert0],
  35941. [1, twoDimVert0], [1, twoDimVert0],
  35942. [1, twoDimVert0], [1, twoDimVert0],
  35943. [1, twoDimVert0], [1, twoDimVert0],
  35944. [1, twoDimVert0], [1, twoDimVert0],
  35945. [1, twoDimVert0], [1, twoDimVert0],
  35946. [1, twoDimVert0], [1, twoDimVert0],
  35947. [1, twoDimVert0], [1, twoDimVert0],
  35948. [1, twoDimVert0], [1, twoDimVert0],
  35949. [1, twoDimVert0], [1, twoDimVert0],
  35950. [1, twoDimVert0], [1, twoDimVert0],
  35951. [1, twoDimVert0], [1, twoDimVert0],
  35952. [1, twoDimVert0], [1, twoDimVert0],
  35953. [1, twoDimVert0], [1, twoDimVert0],
  35954. [1, twoDimVert0], [1, twoDimVert0],
  35955. [1, twoDimVert0], [1, twoDimVert0],
  35956. [1, twoDimVert0], [1, twoDimVert0],
  35957. [1, twoDimVert0], [1, twoDimVert0],
  35958. [1, twoDimVert0], [1, twoDimVert0],
  35959. [1, twoDimVert0], [1, twoDimVert0],
  35960. [1, twoDimVert0], [1, twoDimVert0],
  35961. [1, twoDimVert0], [1, twoDimVert0],
  35962. [1, twoDimVert0], [1, twoDimVert0],
  35963. [1, twoDimVert0], [1, twoDimVert0],
  35964. [1, twoDimVert0], [1, twoDimVert0],
  35965. [1, twoDimVert0], [1, twoDimVert0],
  35966. [1, twoDimVert0], [1, twoDimVert0],
  35967. [1, twoDimVert0], [1, twoDimVert0],
  35968. [1, twoDimVert0], [1, twoDimVert0],
  35969. [1, twoDimVert0], [1, twoDimVert0]
  35970. ];
  35971. var whiteTable1 = [
  35972. [-1, -1], // 00000
  35973. [12, ccittEOL], // 00001
  35974. [-1, -1], [-1, -1], // 0001x
  35975. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 001xx
  35976. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 010xx
  35977. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 011xx
  35978. [11, 1792], [11, 1792], // 1000x
  35979. [12, 1984], // 10010
  35980. [12, 2048], // 10011
  35981. [12, 2112], // 10100
  35982. [12, 2176], // 10101
  35983. [12, 2240], // 10110
  35984. [12, 2304], // 10111
  35985. [11, 1856], [11, 1856], // 1100x
  35986. [11, 1920], [11, 1920], // 1101x
  35987. [12, 2368], // 11100
  35988. [12, 2432], // 11101
  35989. [12, 2496], // 11110
  35990. [12, 2560] // 11111
  35991. ];
  35992. var whiteTable2 = [
  35993. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 0000000xx
  35994. [8, 29], [8, 29], // 00000010x
  35995. [8, 30], [8, 30], // 00000011x
  35996. [8, 45], [8, 45], // 00000100x
  35997. [8, 46], [8, 46], // 00000101x
  35998. [7, 22], [7, 22], [7, 22], [7, 22], // 0000011xx
  35999. [7, 23], [7, 23], [7, 23], [7, 23], // 0000100xx
  36000. [8, 47], [8, 47], // 00001010x
  36001. [8, 48], [8, 48], // 00001011x
  36002. [6, 13], [6, 13], [6, 13], [6, 13], // 000011xxx
  36003. [6, 13], [6, 13], [6, 13], [6, 13],
  36004. [7, 20], [7, 20], [7, 20], [7, 20], // 0001000xx
  36005. [8, 33], [8, 33], // 00010010x
  36006. [8, 34], [8, 34], // 00010011x
  36007. [8, 35], [8, 35], // 00010100x
  36008. [8, 36], [8, 36], // 00010101x
  36009. [8, 37], [8, 37], // 00010110x
  36010. [8, 38], [8, 38], // 00010111x
  36011. [7, 19], [7, 19], [7, 19], [7, 19], // 0001100xx
  36012. [8, 31], [8, 31], // 00011010x
  36013. [8, 32], [8, 32], // 00011011x
  36014. [6, 1], [6, 1], [6, 1], [6, 1], // 000111xxx
  36015. [6, 1], [6, 1], [6, 1], [6, 1],
  36016. [6, 12], [6, 12], [6, 12], [6, 12], // 001000xxx
  36017. [6, 12], [6, 12], [6, 12], [6, 12],
  36018. [8, 53], [8, 53], // 00100100x
  36019. [8, 54], [8, 54], // 00100101x
  36020. [7, 26], [7, 26], [7, 26], [7, 26], // 0010011xx
  36021. [8, 39], [8, 39], // 00101000x
  36022. [8, 40], [8, 40], // 00101001x
  36023. [8, 41], [8, 41], // 00101010x
  36024. [8, 42], [8, 42], // 00101011x
  36025. [8, 43], [8, 43], // 00101100x
  36026. [8, 44], [8, 44], // 00101101x
  36027. [7, 21], [7, 21], [7, 21], [7, 21], // 0010111xx
  36028. [7, 28], [7, 28], [7, 28], [7, 28], // 0011000xx
  36029. [8, 61], [8, 61], // 00110010x
  36030. [8, 62], [8, 62], // 00110011x
  36031. [8, 63], [8, 63], // 00110100x
  36032. [8, 0], [8, 0], // 00110101x
  36033. [8, 320], [8, 320], // 00110110x
  36034. [8, 384], [8, 384], // 00110111x
  36035. [5, 10], [5, 10], [5, 10], [5, 10], // 00111xxxx
  36036. [5, 10], [5, 10], [5, 10], [5, 10],
  36037. [5, 10], [5, 10], [5, 10], [5, 10],
  36038. [5, 10], [5, 10], [5, 10], [5, 10],
  36039. [5, 11], [5, 11], [5, 11], [5, 11], // 01000xxxx
  36040. [5, 11], [5, 11], [5, 11], [5, 11],
  36041. [5, 11], [5, 11], [5, 11], [5, 11],
  36042. [5, 11], [5, 11], [5, 11], [5, 11],
  36043. [7, 27], [7, 27], [7, 27], [7, 27], // 0100100xx
  36044. [8, 59], [8, 59], // 01001010x
  36045. [8, 60], [8, 60], // 01001011x
  36046. [9, 1472], // 010011000
  36047. [9, 1536], // 010011001
  36048. [9, 1600], // 010011010
  36049. [9, 1728], // 010011011
  36050. [7, 18], [7, 18], [7, 18], [7, 18], // 0100111xx
  36051. [7, 24], [7, 24], [7, 24], [7, 24], // 0101000xx
  36052. [8, 49], [8, 49], // 01010010x
  36053. [8, 50], [8, 50], // 01010011x
  36054. [8, 51], [8, 51], // 01010100x
  36055. [8, 52], [8, 52], // 01010101x
  36056. [7, 25], [7, 25], [7, 25], [7, 25], // 0101011xx
  36057. [8, 55], [8, 55], // 01011000x
  36058. [8, 56], [8, 56], // 01011001x
  36059. [8, 57], [8, 57], // 01011010x
  36060. [8, 58], [8, 58], // 01011011x
  36061. [6, 192], [6, 192], [6, 192], [6, 192], // 010111xxx
  36062. [6, 192], [6, 192], [6, 192], [6, 192],
  36063. [6, 1664], [6, 1664], [6, 1664], [6, 1664], // 011000xxx
  36064. [6, 1664], [6, 1664], [6, 1664], [6, 1664],
  36065. [8, 448], [8, 448], // 01100100x
  36066. [8, 512], [8, 512], // 01100101x
  36067. [9, 704], // 011001100
  36068. [9, 768], // 011001101
  36069. [8, 640], [8, 640], // 01100111x
  36070. [8, 576], [8, 576], // 01101000x
  36071. [9, 832], // 011010010
  36072. [9, 896], // 011010011
  36073. [9, 960], // 011010100
  36074. [9, 1024], // 011010101
  36075. [9, 1088], // 011010110
  36076. [9, 1152], // 011010111
  36077. [9, 1216], // 011011000
  36078. [9, 1280], // 011011001
  36079. [9, 1344], // 011011010
  36080. [9, 1408], // 011011011
  36081. [7, 256], [7, 256], [7, 256], [7, 256], // 0110111xx
  36082. [4, 2], [4, 2], [4, 2], [4, 2], // 0111xxxxx
  36083. [4, 2], [4, 2], [4, 2], [4, 2],
  36084. [4, 2], [4, 2], [4, 2], [4, 2],
  36085. [4, 2], [4, 2], [4, 2], [4, 2],
  36086. [4, 2], [4, 2], [4, 2], [4, 2],
  36087. [4, 2], [4, 2], [4, 2], [4, 2],
  36088. [4, 2], [4, 2], [4, 2], [4, 2],
  36089. [4, 2], [4, 2], [4, 2], [4, 2],
  36090. [4, 3], [4, 3], [4, 3], [4, 3], // 1000xxxxx
  36091. [4, 3], [4, 3], [4, 3], [4, 3],
  36092. [4, 3], [4, 3], [4, 3], [4, 3],
  36093. [4, 3], [4, 3], [4, 3], [4, 3],
  36094. [4, 3], [4, 3], [4, 3], [4, 3],
  36095. [4, 3], [4, 3], [4, 3], [4, 3],
  36096. [4, 3], [4, 3], [4, 3], [4, 3],
  36097. [4, 3], [4, 3], [4, 3], [4, 3],
  36098. [5, 128], [5, 128], [5, 128], [5, 128], // 10010xxxx
  36099. [5, 128], [5, 128], [5, 128], [5, 128],
  36100. [5, 128], [5, 128], [5, 128], [5, 128],
  36101. [5, 128], [5, 128], [5, 128], [5, 128],
  36102. [5, 8], [5, 8], [5, 8], [5, 8], // 10011xxxx
  36103. [5, 8], [5, 8], [5, 8], [5, 8],
  36104. [5, 8], [5, 8], [5, 8], [5, 8],
  36105. [5, 8], [5, 8], [5, 8], [5, 8],
  36106. [5, 9], [5, 9], [5, 9], [5, 9], // 10100xxxx
  36107. [5, 9], [5, 9], [5, 9], [5, 9],
  36108. [5, 9], [5, 9], [5, 9], [5, 9],
  36109. [5, 9], [5, 9], [5, 9], [5, 9],
  36110. [6, 16], [6, 16], [6, 16], [6, 16], // 101010xxx
  36111. [6, 16], [6, 16], [6, 16], [6, 16],
  36112. [6, 17], [6, 17], [6, 17], [6, 17], // 101011xxx
  36113. [6, 17], [6, 17], [6, 17], [6, 17],
  36114. [4, 4], [4, 4], [4, 4], [4, 4], // 1011xxxxx
  36115. [4, 4], [4, 4], [4, 4], [4, 4],
  36116. [4, 4], [4, 4], [4, 4], [4, 4],
  36117. [4, 4], [4, 4], [4, 4], [4, 4],
  36118. [4, 4], [4, 4], [4, 4], [4, 4],
  36119. [4, 4], [4, 4], [4, 4], [4, 4],
  36120. [4, 4], [4, 4], [4, 4], [4, 4],
  36121. [4, 4], [4, 4], [4, 4], [4, 4],
  36122. [4, 5], [4, 5], [4, 5], [4, 5], // 1100xxxxx
  36123. [4, 5], [4, 5], [4, 5], [4, 5],
  36124. [4, 5], [4, 5], [4, 5], [4, 5],
  36125. [4, 5], [4, 5], [4, 5], [4, 5],
  36126. [4, 5], [4, 5], [4, 5], [4, 5],
  36127. [4, 5], [4, 5], [4, 5], [4, 5],
  36128. [4, 5], [4, 5], [4, 5], [4, 5],
  36129. [4, 5], [4, 5], [4, 5], [4, 5],
  36130. [6, 14], [6, 14], [6, 14], [6, 14], // 110100xxx
  36131. [6, 14], [6, 14], [6, 14], [6, 14],
  36132. [6, 15], [6, 15], [6, 15], [6, 15], // 110101xxx
  36133. [6, 15], [6, 15], [6, 15], [6, 15],
  36134. [5, 64], [5, 64], [5, 64], [5, 64], // 11011xxxx
  36135. [5, 64], [5, 64], [5, 64], [5, 64],
  36136. [5, 64], [5, 64], [5, 64], [5, 64],
  36137. [5, 64], [5, 64], [5, 64], [5, 64],
  36138. [4, 6], [4, 6], [4, 6], [4, 6], // 1110xxxxx
  36139. [4, 6], [4, 6], [4, 6], [4, 6],
  36140. [4, 6], [4, 6], [4, 6], [4, 6],
  36141. [4, 6], [4, 6], [4, 6], [4, 6],
  36142. [4, 6], [4, 6], [4, 6], [4, 6],
  36143. [4, 6], [4, 6], [4, 6], [4, 6],
  36144. [4, 6], [4, 6], [4, 6], [4, 6],
  36145. [4, 6], [4, 6], [4, 6], [4, 6],
  36146. [4, 7], [4, 7], [4, 7], [4, 7], // 1111xxxxx
  36147. [4, 7], [4, 7], [4, 7], [4, 7],
  36148. [4, 7], [4, 7], [4, 7], [4, 7],
  36149. [4, 7], [4, 7], [4, 7], [4, 7],
  36150. [4, 7], [4, 7], [4, 7], [4, 7],
  36151. [4, 7], [4, 7], [4, 7], [4, 7],
  36152. [4, 7], [4, 7], [4, 7], [4, 7],
  36153. [4, 7], [4, 7], [4, 7], [4, 7]
  36154. ];
  36155. var blackTable1 = [
  36156. [-1, -1], [-1, -1], // 000000000000x
  36157. [12, ccittEOL], [12, ccittEOL], // 000000000001x
  36158. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000001xx
  36159. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000010xx
  36160. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000011xx
  36161. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000100xx
  36162. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000101xx
  36163. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000110xx
  36164. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 00000000111xx
  36165. [11, 1792], [11, 1792], [11, 1792], [11, 1792], // 00000001000xx
  36166. [12, 1984], [12, 1984], // 000000010010x
  36167. [12, 2048], [12, 2048], // 000000010011x
  36168. [12, 2112], [12, 2112], // 000000010100x
  36169. [12, 2176], [12, 2176], // 000000010101x
  36170. [12, 2240], [12, 2240], // 000000010110x
  36171. [12, 2304], [12, 2304], // 000000010111x
  36172. [11, 1856], [11, 1856], [11, 1856], [11, 1856], // 00000001100xx
  36173. [11, 1920], [11, 1920], [11, 1920], [11, 1920], // 00000001101xx
  36174. [12, 2368], [12, 2368], // 000000011100x
  36175. [12, 2432], [12, 2432], // 000000011101x
  36176. [12, 2496], [12, 2496], // 000000011110x
  36177. [12, 2560], [12, 2560], // 000000011111x
  36178. [10, 18], [10, 18], [10, 18], [10, 18], // 0000001000xxx
  36179. [10, 18], [10, 18], [10, 18], [10, 18],
  36180. [12, 52], [12, 52], // 000000100100x
  36181. [13, 640], // 0000001001010
  36182. [13, 704], // 0000001001011
  36183. [13, 768], // 0000001001100
  36184. [13, 832], // 0000001001101
  36185. [12, 55], [12, 55], // 000000100111x
  36186. [12, 56], [12, 56], // 000000101000x
  36187. [13, 1280], // 0000001010010
  36188. [13, 1344], // 0000001010011
  36189. [13, 1408], // 0000001010100
  36190. [13, 1472], // 0000001010101
  36191. [12, 59], [12, 59], // 000000101011x
  36192. [12, 60], [12, 60], // 000000101100x
  36193. [13, 1536], // 0000001011010
  36194. [13, 1600], // 0000001011011
  36195. [11, 24], [11, 24], [11, 24], [11, 24], // 00000010111xx
  36196. [11, 25], [11, 25], [11, 25], [11, 25], // 00000011000xx
  36197. [13, 1664], // 0000001100100
  36198. [13, 1728], // 0000001100101
  36199. [12, 320], [12, 320], // 000000110011x
  36200. [12, 384], [12, 384], // 000000110100x
  36201. [12, 448], [12, 448], // 000000110101x
  36202. [13, 512], // 0000001101100
  36203. [13, 576], // 0000001101101
  36204. [12, 53], [12, 53], // 000000110111x
  36205. [12, 54], [12, 54], // 000000111000x
  36206. [13, 896], // 0000001110010
  36207. [13, 960], // 0000001110011
  36208. [13, 1024], // 0000001110100
  36209. [13, 1088], // 0000001110101
  36210. [13, 1152], // 0000001110110
  36211. [13, 1216], // 0000001110111
  36212. [10, 64], [10, 64], [10, 64], [10, 64], // 0000001111xxx
  36213. [10, 64], [10, 64], [10, 64], [10, 64]
  36214. ];
  36215. var blackTable2 = [
  36216. [8, 13], [8, 13], [8, 13], [8, 13], // 00000100xxxx
  36217. [8, 13], [8, 13], [8, 13], [8, 13],
  36218. [8, 13], [8, 13], [8, 13], [8, 13],
  36219. [8, 13], [8, 13], [8, 13], [8, 13],
  36220. [11, 23], [11, 23], // 00000101000x
  36221. [12, 50], // 000001010010
  36222. [12, 51], // 000001010011
  36223. [12, 44], // 000001010100
  36224. [12, 45], // 000001010101
  36225. [12, 46], // 000001010110
  36226. [12, 47], // 000001010111
  36227. [12, 57], // 000001011000
  36228. [12, 58], // 000001011001
  36229. [12, 61], // 000001011010
  36230. [12, 256], // 000001011011
  36231. [10, 16], [10, 16], [10, 16], [10, 16], // 0000010111xx
  36232. [10, 17], [10, 17], [10, 17], [10, 17], // 0000011000xx
  36233. [12, 48], // 000001100100
  36234. [12, 49], // 000001100101
  36235. [12, 62], // 000001100110
  36236. [12, 63], // 000001100111
  36237. [12, 30], // 000001101000
  36238. [12, 31], // 000001101001
  36239. [12, 32], // 000001101010
  36240. [12, 33], // 000001101011
  36241. [12, 40], // 000001101100
  36242. [12, 41], // 000001101101
  36243. [11, 22], [11, 22], // 00000110111x
  36244. [8, 14], [8, 14], [8, 14], [8, 14], // 00000111xxxx
  36245. [8, 14], [8, 14], [8, 14], [8, 14],
  36246. [8, 14], [8, 14], [8, 14], [8, 14],
  36247. [8, 14], [8, 14], [8, 14], [8, 14],
  36248. [7, 10], [7, 10], [7, 10], [7, 10], // 0000100xxxxx
  36249. [7, 10], [7, 10], [7, 10], [7, 10],
  36250. [7, 10], [7, 10], [7, 10], [7, 10],
  36251. [7, 10], [7, 10], [7, 10], [7, 10],
  36252. [7, 10], [7, 10], [7, 10], [7, 10],
  36253. [7, 10], [7, 10], [7, 10], [7, 10],
  36254. [7, 10], [7, 10], [7, 10], [7, 10],
  36255. [7, 10], [7, 10], [7, 10], [7, 10],
  36256. [7, 11], [7, 11], [7, 11], [7, 11], // 0000101xxxxx
  36257. [7, 11], [7, 11], [7, 11], [7, 11],
  36258. [7, 11], [7, 11], [7, 11], [7, 11],
  36259. [7, 11], [7, 11], [7, 11], [7, 11],
  36260. [7, 11], [7, 11], [7, 11], [7, 11],
  36261. [7, 11], [7, 11], [7, 11], [7, 11],
  36262. [7, 11], [7, 11], [7, 11], [7, 11],
  36263. [7, 11], [7, 11], [7, 11], [7, 11],
  36264. [9, 15], [9, 15], [9, 15], [9, 15], // 000011000xxx
  36265. [9, 15], [9, 15], [9, 15], [9, 15],
  36266. [12, 128], // 000011001000
  36267. [12, 192], // 000011001001
  36268. [12, 26], // 000011001010
  36269. [12, 27], // 000011001011
  36270. [12, 28], // 000011001100
  36271. [12, 29], // 000011001101
  36272. [11, 19], [11, 19], // 00001100111x
  36273. [11, 20], [11, 20], // 00001101000x
  36274. [12, 34], // 000011010010
  36275. [12, 35], // 000011010011
  36276. [12, 36], // 000011010100
  36277. [12, 37], // 000011010101
  36278. [12, 38], // 000011010110
  36279. [12, 39], // 000011010111
  36280. [11, 21], [11, 21], // 00001101100x
  36281. [12, 42], // 000011011010
  36282. [12, 43], // 000011011011
  36283. [10, 0], [10, 0], [10, 0], [10, 0], // 0000110111xx
  36284. [7, 12], [7, 12], [7, 12], [7, 12], // 0000111xxxxx
  36285. [7, 12], [7, 12], [7, 12], [7, 12],
  36286. [7, 12], [7, 12], [7, 12], [7, 12],
  36287. [7, 12], [7, 12], [7, 12], [7, 12],
  36288. [7, 12], [7, 12], [7, 12], [7, 12],
  36289. [7, 12], [7, 12], [7, 12], [7, 12],
  36290. [7, 12], [7, 12], [7, 12], [7, 12],
  36291. [7, 12], [7, 12], [7, 12], [7, 12]
  36292. ];
  36293. var blackTable3 = [
  36294. [-1, -1], [-1, -1], [-1, -1], [-1, -1], // 0000xx
  36295. [6, 9], // 000100
  36296. [6, 8], // 000101
  36297. [5, 7], [5, 7], // 00011x
  36298. [4, 6], [4, 6], [4, 6], [4, 6], // 0010xx
  36299. [4, 5], [4, 5], [4, 5], [4, 5], // 0011xx
  36300. [3, 1], [3, 1], [3, 1], [3, 1], // 010xxx
  36301. [3, 1], [3, 1], [3, 1], [3, 1],
  36302. [3, 4], [3, 4], [3, 4], [3, 4], // 011xxx
  36303. [3, 4], [3, 4], [3, 4], [3, 4],
  36304. [2, 3], [2, 3], [2, 3], [2, 3], // 10xxxx
  36305. [2, 3], [2, 3], [2, 3], [2, 3],
  36306. [2, 3], [2, 3], [2, 3], [2, 3],
  36307. [2, 3], [2, 3], [2, 3], [2, 3],
  36308. [2, 2], [2, 2], [2, 2], [2, 2], // 11xxxx
  36309. [2, 2], [2, 2], [2, 2], [2, 2],
  36310. [2, 2], [2, 2], [2, 2], [2, 2],
  36311. [2, 2], [2, 2], [2, 2], [2, 2]
  36312. ];
  36313. function CCITTFaxStream(str, maybeLength, params) {
  36314. this.str = str;
  36315. this.dict = str.dict;
  36316. params = params || Dict.empty;
  36317. this.encoding = params.get('K') || 0;
  36318. this.eoline = params.get('EndOfLine') || false;
  36319. this.byteAlign = params.get('EncodedByteAlign') || false;
  36320. this.columns = params.get('Columns') || 1728;
  36321. this.rows = params.get('Rows') || 0;
  36322. var eoblock = params.get('EndOfBlock');
  36323. if (eoblock === null || eoblock === undefined) {
  36324. eoblock = true;
  36325. }
  36326. this.eoblock = eoblock;
  36327. this.black = params.get('BlackIs1') || false;
  36328. this.codingLine = new Uint32Array(this.columns + 1);
  36329. this.refLine = new Uint32Array(this.columns + 2);
  36330. this.codingLine[0] = this.columns;
  36331. this.codingPos = 0;
  36332. this.row = 0;
  36333. this.nextLine2D = this.encoding < 0;
  36334. this.inputBits = 0;
  36335. this.inputBuf = 0;
  36336. this.outputBits = 0;
  36337. var code1;
  36338. while ((code1 = this.lookBits(12)) === 0) {
  36339. this.eatBits(1);
  36340. }
  36341. if (code1 === 1) {
  36342. this.eatBits(12);
  36343. }
  36344. if (this.encoding > 0) {
  36345. this.nextLine2D = !this.lookBits(1);
  36346. this.eatBits(1);
  36347. }
  36348. DecodeStream.call(this, maybeLength);
  36349. }
  36350. CCITTFaxStream.prototype = Object.create(DecodeStream.prototype);
  36351. CCITTFaxStream.prototype.readBlock = function CCITTFaxStream_readBlock() {
  36352. while (!this.eof) {
  36353. var c = this.lookChar();
  36354. this.ensureBuffer(this.bufferLength + 1);
  36355. this.buffer[this.bufferLength++] = c;
  36356. }
  36357. };
  36358. CCITTFaxStream.prototype.addPixels =
  36359. function ccittFaxStreamAddPixels(a1, blackPixels) {
  36360. var codingLine = this.codingLine;
  36361. var codingPos = this.codingPos;
  36362. if (a1 > codingLine[codingPos]) {
  36363. if (a1 > this.columns) {
  36364. info('row is wrong length');
  36365. this.err = true;
  36366. a1 = this.columns;
  36367. }
  36368. if ((codingPos & 1) ^ blackPixels) {
  36369. ++codingPos;
  36370. }
  36371. codingLine[codingPos] = a1;
  36372. }
  36373. this.codingPos = codingPos;
  36374. };
  36375. CCITTFaxStream.prototype.addPixelsNeg =
  36376. function ccittFaxStreamAddPixelsNeg(a1, blackPixels) {
  36377. var codingLine = this.codingLine;
  36378. var codingPos = this.codingPos;
  36379. if (a1 > codingLine[codingPos]) {
  36380. if (a1 > this.columns) {
  36381. info('row is wrong length');
  36382. this.err = true;
  36383. a1 = this.columns;
  36384. }
  36385. if ((codingPos & 1) ^ blackPixels) {
  36386. ++codingPos;
  36387. }
  36388. codingLine[codingPos] = a1;
  36389. } else if (a1 < codingLine[codingPos]) {
  36390. if (a1 < 0) {
  36391. info('invalid code');
  36392. this.err = true;
  36393. a1 = 0;
  36394. }
  36395. while (codingPos > 0 && a1 < codingLine[codingPos - 1]) {
  36396. --codingPos;
  36397. }
  36398. codingLine[codingPos] = a1;
  36399. }
  36400. this.codingPos = codingPos;
  36401. };
  36402. CCITTFaxStream.prototype.lookChar = function CCITTFaxStream_lookChar() {
  36403. var refLine = this.refLine;
  36404. var codingLine = this.codingLine;
  36405. var columns = this.columns;
  36406. var refPos, blackPixels, bits, i;
  36407. if (this.outputBits === 0) {
  36408. if (this.eof) {
  36409. return null;
  36410. }
  36411. this.err = false;
  36412. var code1, code2, code3;
  36413. if (this.nextLine2D) {
  36414. for (i = 0; codingLine[i] < columns; ++i) {
  36415. refLine[i] = codingLine[i];
  36416. }
  36417. refLine[i++] = columns;
  36418. refLine[i] = columns;
  36419. codingLine[0] = 0;
  36420. this.codingPos = 0;
  36421. refPos = 0;
  36422. blackPixels = 0;
  36423. while (codingLine[this.codingPos] < columns) {
  36424. code1 = this.getTwoDimCode();
  36425. switch (code1) {
  36426. case twoDimPass:
  36427. this.addPixels(refLine[refPos + 1], blackPixels);
  36428. if (refLine[refPos + 1] < columns) {
  36429. refPos += 2;
  36430. }
  36431. break;
  36432. case twoDimHoriz:
  36433. code1 = code2 = 0;
  36434. if (blackPixels) {
  36435. do {
  36436. code1 += (code3 = this.getBlackCode());
  36437. } while (code3 >= 64);
  36438. do {
  36439. code2 += (code3 = this.getWhiteCode());
  36440. } while (code3 >= 64);
  36441. } else {
  36442. do {
  36443. code1 += (code3 = this.getWhiteCode());
  36444. } while (code3 >= 64);
  36445. do {
  36446. code2 += (code3 = this.getBlackCode());
  36447. } while (code3 >= 64);
  36448. }
  36449. this.addPixels(codingLine[this.codingPos] +
  36450. code1, blackPixels);
  36451. if (codingLine[this.codingPos] < columns) {
  36452. this.addPixels(codingLine[this.codingPos] + code2,
  36453. blackPixels ^ 1);
  36454. }
  36455. while (refLine[refPos] <= codingLine[this.codingPos] &&
  36456. refLine[refPos] < columns) {
  36457. refPos += 2;
  36458. }
  36459. break;
  36460. case twoDimVertR3:
  36461. this.addPixels(refLine[refPos] + 3, blackPixels);
  36462. blackPixels ^= 1;
  36463. if (codingLine[this.codingPos] < columns) {
  36464. ++refPos;
  36465. while (refLine[refPos] <= codingLine[this.codingPos] &&
  36466. refLine[refPos] < columns) {
  36467. refPos += 2;
  36468. }
  36469. }
  36470. break;
  36471. case twoDimVertR2:
  36472. this.addPixels(refLine[refPos] + 2, blackPixels);
  36473. blackPixels ^= 1;
  36474. if (codingLine[this.codingPos] < columns) {
  36475. ++refPos;
  36476. while (refLine[refPos] <= codingLine[this.codingPos] &&
  36477. refLine[refPos] < columns) {
  36478. refPos += 2;
  36479. }
  36480. }
  36481. break;
  36482. case twoDimVertR1:
  36483. this.addPixels(refLine[refPos] + 1, blackPixels);
  36484. blackPixels ^= 1;
  36485. if (codingLine[this.codingPos] < columns) {
  36486. ++refPos;
  36487. while (refLine[refPos] <= codingLine[this.codingPos] &&
  36488. refLine[refPos] < columns) {
  36489. refPos += 2;
  36490. }
  36491. }
  36492. break;
  36493. case twoDimVert0:
  36494. this.addPixels(refLine[refPos], blackPixels);
  36495. blackPixels ^= 1;
  36496. if (codingLine[this.codingPos] < columns) {
  36497. ++refPos;
  36498. while (refLine[refPos] <= codingLine[this.codingPos] &&
  36499. refLine[refPos] < columns) {
  36500. refPos += 2;
  36501. }
  36502. }
  36503. break;
  36504. case twoDimVertL3:
  36505. this.addPixelsNeg(refLine[refPos] - 3, blackPixels);
  36506. blackPixels ^= 1;
  36507. if (codingLine[this.codingPos] < columns) {
  36508. if (refPos > 0) {
  36509. --refPos;
  36510. } else {
  36511. ++refPos;
  36512. }
  36513. while (refLine[refPos] <= codingLine[this.codingPos] &&
  36514. refLine[refPos] < columns) {
  36515. refPos += 2;
  36516. }
  36517. }
  36518. break;
  36519. case twoDimVertL2:
  36520. this.addPixelsNeg(refLine[refPos] - 2, blackPixels);
  36521. blackPixels ^= 1;
  36522. if (codingLine[this.codingPos] < columns) {
  36523. if (refPos > 0) {
  36524. --refPos;
  36525. } else {
  36526. ++refPos;
  36527. }
  36528. while (refLine[refPos] <= codingLine[this.codingPos] &&
  36529. refLine[refPos] < columns) {
  36530. refPos += 2;
  36531. }
  36532. }
  36533. break;
  36534. case twoDimVertL1:
  36535. this.addPixelsNeg(refLine[refPos] - 1, blackPixels);
  36536. blackPixels ^= 1;
  36537. if (codingLine[this.codingPos] < columns) {
  36538. if (refPos > 0) {
  36539. --refPos;
  36540. } else {
  36541. ++refPos;
  36542. }
  36543. while (refLine[refPos] <= codingLine[this.codingPos] &&
  36544. refLine[refPos] < columns) {
  36545. refPos += 2;
  36546. }
  36547. }
  36548. break;
  36549. case EOF:
  36550. this.addPixels(columns, 0);
  36551. this.eof = true;
  36552. break;
  36553. default:
  36554. info('bad 2d code');
  36555. this.addPixels(columns, 0);
  36556. this.err = true;
  36557. }
  36558. }
  36559. } else {
  36560. codingLine[0] = 0;
  36561. this.codingPos = 0;
  36562. blackPixels = 0;
  36563. while (codingLine[this.codingPos] < columns) {
  36564. code1 = 0;
  36565. if (blackPixels) {
  36566. do {
  36567. code1 += (code3 = this.getBlackCode());
  36568. } while (code3 >= 64);
  36569. } else {
  36570. do {
  36571. code1 += (code3 = this.getWhiteCode());
  36572. } while (code3 >= 64);
  36573. }
  36574. this.addPixels(codingLine[this.codingPos] + code1, blackPixels);
  36575. blackPixels ^= 1;
  36576. }
  36577. }
  36578. var gotEOL = false;
  36579. if (!this.eoblock && this.row === this.rows - 1) {
  36580. this.eof = true;
  36581. } else if (this.eoline || !this.byteAlign) {
  36582. code1 = this.lookBits(12);
  36583. if (this.eoline) {
  36584. while (code1 !== EOF && code1 !== 1) {
  36585. this.eatBits(1);
  36586. code1 = this.lookBits(12);
  36587. }
  36588. } else {
  36589. while (code1 === 0) {
  36590. this.eatBits(1);
  36591. code1 = this.lookBits(12);
  36592. }
  36593. }
  36594. if (code1 === 1) {
  36595. this.eatBits(12);
  36596. gotEOL = true;
  36597. } else if (code1 === EOF) {
  36598. this.eof = true;
  36599. }
  36600. }
  36601. if (this.byteAlign && !gotEOL) {
  36602. this.inputBits &= ~7;
  36603. }
  36604. if (!this.eof && this.encoding > 0) {
  36605. this.nextLine2D = !this.lookBits(1);
  36606. this.eatBits(1);
  36607. }
  36608. if (this.eoblock && gotEOL && this.byteAlign) {
  36609. code1 = this.lookBits(12);
  36610. if (code1 === 1) {
  36611. this.eatBits(12);
  36612. if (this.encoding > 0) {
  36613. this.lookBits(1);
  36614. this.eatBits(1);
  36615. }
  36616. if (this.encoding >= 0) {
  36617. for (i = 0; i < 4; ++i) {
  36618. code1 = this.lookBits(12);
  36619. if (code1 !== 1) {
  36620. info('bad rtc code: ' + code1);
  36621. }
  36622. this.eatBits(12);
  36623. if (this.encoding > 0) {
  36624. this.lookBits(1);
  36625. this.eatBits(1);
  36626. }
  36627. }
  36628. }
  36629. this.eof = true;
  36630. }
  36631. } else if (this.err && this.eoline) {
  36632. while (true) {
  36633. code1 = this.lookBits(13);
  36634. if (code1 === EOF) {
  36635. this.eof = true;
  36636. return null;
  36637. }
  36638. if ((code1 >> 1) === 1) {
  36639. break;
  36640. }
  36641. this.eatBits(1);
  36642. }
  36643. this.eatBits(12);
  36644. if (this.encoding > 0) {
  36645. this.eatBits(1);
  36646. this.nextLine2D = !(code1 & 1);
  36647. }
  36648. }
  36649. if (codingLine[0] > 0) {
  36650. this.outputBits = codingLine[this.codingPos = 0];
  36651. } else {
  36652. this.outputBits = codingLine[this.codingPos = 1];
  36653. }
  36654. this.row++;
  36655. }
  36656. var c;
  36657. if (this.outputBits >= 8) {
  36658. c = (this.codingPos & 1) ? 0 : 0xFF;
  36659. this.outputBits -= 8;
  36660. if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {
  36661. this.codingPos++;
  36662. this.outputBits = (codingLine[this.codingPos] -
  36663. codingLine[this.codingPos - 1]);
  36664. }
  36665. } else {
  36666. bits = 8;
  36667. c = 0;
  36668. do {
  36669. if (this.outputBits > bits) {
  36670. c <<= bits;
  36671. if (!(this.codingPos & 1)) {
  36672. c |= 0xFF >> (8 - bits);
  36673. }
  36674. this.outputBits -= bits;
  36675. bits = 0;
  36676. } else {
  36677. c <<= this.outputBits;
  36678. if (!(this.codingPos & 1)) {
  36679. c |= 0xFF >> (8 - this.outputBits);
  36680. }
  36681. bits -= this.outputBits;
  36682. this.outputBits = 0;
  36683. if (codingLine[this.codingPos] < columns) {
  36684. this.codingPos++;
  36685. this.outputBits = (codingLine[this.codingPos] -
  36686. codingLine[this.codingPos - 1]);
  36687. } else if (bits > 0) {
  36688. c <<= bits;
  36689. bits = 0;
  36690. }
  36691. }
  36692. } while (bits);
  36693. }
  36694. if (this.black) {
  36695. c ^= 0xFF;
  36696. }
  36697. return c;
  36698. };
  36699. // This functions returns the code found from the table.
  36700. // The start and end parameters set the boundaries for searching the table.
  36701. // The limit parameter is optional. Function returns an array with three
  36702. // values. The first array element indicates whether a valid code is being
  36703. // returned. The second array element is the actual code. The third array
  36704. // element indicates whether EOF was reached.
  36705. CCITTFaxStream.prototype.findTableCode =
  36706. function ccittFaxStreamFindTableCode(start, end, table, limit) {
  36707. var limitValue = limit || 0;
  36708. for (var i = start; i <= end; ++i) {
  36709. var code = this.lookBits(i);
  36710. if (code === EOF) {
  36711. return [true, 1, false];
  36712. }
  36713. if (i < end) {
  36714. code <<= end - i;
  36715. }
  36716. if (!limitValue || code >= limitValue) {
  36717. var p = table[code - limitValue];
  36718. if (p[0] === i) {
  36719. this.eatBits(i);
  36720. return [true, p[1], true];
  36721. }
  36722. }
  36723. }
  36724. return [false, 0, false];
  36725. };
  36726. CCITTFaxStream.prototype.getTwoDimCode =
  36727. function ccittFaxStreamGetTwoDimCode() {
  36728. var code = 0;
  36729. var p;
  36730. if (this.eoblock) {
  36731. code = this.lookBits(7);
  36732. p = twoDimTable[code];
  36733. if (p && p[0] > 0) {
  36734. this.eatBits(p[0]);
  36735. return p[1];
  36736. }
  36737. } else {
  36738. var result = this.findTableCode(1, 7, twoDimTable);
  36739. if (result[0] && result[2]) {
  36740. return result[1];
  36741. }
  36742. }
  36743. info('Bad two dim code');
  36744. return EOF;
  36745. };
  36746. CCITTFaxStream.prototype.getWhiteCode =
  36747. function ccittFaxStreamGetWhiteCode() {
  36748. var code = 0;
  36749. var p;
  36750. if (this.eoblock) {
  36751. code = this.lookBits(12);
  36752. if (code === EOF) {
  36753. return 1;
  36754. }
  36755. if ((code >> 5) === 0) {
  36756. p = whiteTable1[code];
  36757. } else {
  36758. p = whiteTable2[code >> 3];
  36759. }
  36760. if (p[0] > 0) {
  36761. this.eatBits(p[0]);
  36762. return p[1];
  36763. }
  36764. } else {
  36765. var result = this.findTableCode(1, 9, whiteTable2);
  36766. if (result[0]) {
  36767. return result[1];
  36768. }
  36769. result = this.findTableCode(11, 12, whiteTable1);
  36770. if (result[0]) {
  36771. return result[1];
  36772. }
  36773. }
  36774. info('bad white code');
  36775. this.eatBits(1);
  36776. return 1;
  36777. };
  36778. CCITTFaxStream.prototype.getBlackCode =
  36779. function ccittFaxStreamGetBlackCode() {
  36780. var code, p;
  36781. if (this.eoblock) {
  36782. code = this.lookBits(13);
  36783. if (code === EOF) {
  36784. return 1;
  36785. }
  36786. if ((code >> 7) === 0) {
  36787. p = blackTable1[code];
  36788. } else if ((code >> 9) === 0 && (code >> 7) !== 0) {
  36789. p = blackTable2[(code >> 1) - 64];
  36790. } else {
  36791. p = blackTable3[code >> 7];
  36792. }
  36793. if (p[0] > 0) {
  36794. this.eatBits(p[0]);
  36795. return p[1];
  36796. }
  36797. } else {
  36798. var result = this.findTableCode(2, 6, blackTable3);
  36799. if (result[0]) {
  36800. return result[1];
  36801. }
  36802. result = this.findTableCode(7, 12, blackTable2, 64);
  36803. if (result[0]) {
  36804. return result[1];
  36805. }
  36806. result = this.findTableCode(10, 13, blackTable1);
  36807. if (result[0]) {
  36808. return result[1];
  36809. }
  36810. }
  36811. info('bad black code');
  36812. this.eatBits(1);
  36813. return 1;
  36814. };
  36815. CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) {
  36816. var c;
  36817. while (this.inputBits < n) {
  36818. if ((c = this.str.getByte()) === -1) {
  36819. if (this.inputBits === 0) {
  36820. return EOF;
  36821. }
  36822. return ((this.inputBuf << (n - this.inputBits)) &
  36823. (0xFFFF >> (16 - n)));
  36824. }
  36825. this.inputBuf = (this.inputBuf << 8) + c;
  36826. this.inputBits += 8;
  36827. }
  36828. return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n));
  36829. };
  36830. CCITTFaxStream.prototype.eatBits = function CCITTFaxStream_eatBits(n) {
  36831. if ((this.inputBits -= n) < 0) {
  36832. this.inputBits = 0;
  36833. }
  36834. };
  36835. return CCITTFaxStream;
  36836. })();
  36837. var LZWStream = (function LZWStreamClosure() {
  36838. function LZWStream(str, maybeLength, earlyChange) {
  36839. this.str = str;
  36840. this.dict = str.dict;
  36841. this.cachedData = 0;
  36842. this.bitsCached = 0;
  36843. var maxLzwDictionarySize = 4096;
  36844. var lzwState = {
  36845. earlyChange: earlyChange,
  36846. codeLength: 9,
  36847. nextCode: 258,
  36848. dictionaryValues: new Uint8Array(maxLzwDictionarySize),
  36849. dictionaryLengths: new Uint16Array(maxLzwDictionarySize),
  36850. dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize),
  36851. currentSequence: new Uint8Array(maxLzwDictionarySize),
  36852. currentSequenceLength: 0
  36853. };
  36854. for (var i = 0; i < 256; ++i) {
  36855. lzwState.dictionaryValues[i] = i;
  36856. lzwState.dictionaryLengths[i] = 1;
  36857. }
  36858. this.lzwState = lzwState;
  36859. DecodeStream.call(this, maybeLength);
  36860. }
  36861. LZWStream.prototype = Object.create(DecodeStream.prototype);
  36862. LZWStream.prototype.readBits = function LZWStream_readBits(n) {
  36863. var bitsCached = this.bitsCached;
  36864. var cachedData = this.cachedData;
  36865. while (bitsCached < n) {
  36866. var c = this.str.getByte();
  36867. if (c === -1) {
  36868. this.eof = true;
  36869. return null;
  36870. }
  36871. cachedData = (cachedData << 8) | c;
  36872. bitsCached += 8;
  36873. }
  36874. this.bitsCached = (bitsCached -= n);
  36875. this.cachedData = cachedData;
  36876. this.lastCode = null;
  36877. return (cachedData >>> bitsCached) & ((1 << n) - 1);
  36878. };
  36879. LZWStream.prototype.readBlock = function LZWStream_readBlock() {
  36880. var blockSize = 512;
  36881. var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize;
  36882. var i, j, q;
  36883. var lzwState = this.lzwState;
  36884. if (!lzwState) {
  36885. return; // eof was found
  36886. }
  36887. var earlyChange = lzwState.earlyChange;
  36888. var nextCode = lzwState.nextCode;
  36889. var dictionaryValues = lzwState.dictionaryValues;
  36890. var dictionaryLengths = lzwState.dictionaryLengths;
  36891. var dictionaryPrevCodes = lzwState.dictionaryPrevCodes;
  36892. var codeLength = lzwState.codeLength;
  36893. var prevCode = lzwState.prevCode;
  36894. var currentSequence = lzwState.currentSequence;
  36895. var currentSequenceLength = lzwState.currentSequenceLength;
  36896. var decodedLength = 0;
  36897. var currentBufferLength = this.bufferLength;
  36898. var buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
  36899. for (i = 0; i < blockSize; i++) {
  36900. var code = this.readBits(codeLength);
  36901. var hasPrev = currentSequenceLength > 0;
  36902. if (code < 256) {
  36903. currentSequence[0] = code;
  36904. currentSequenceLength = 1;
  36905. } else if (code >= 258) {
  36906. if (code < nextCode) {
  36907. currentSequenceLength = dictionaryLengths[code];
  36908. for (j = currentSequenceLength - 1, q = code; j >= 0; j--) {
  36909. currentSequence[j] = dictionaryValues[q];
  36910. q = dictionaryPrevCodes[q];
  36911. }
  36912. } else {
  36913. currentSequence[currentSequenceLength++] = currentSequence[0];
  36914. }
  36915. } else if (code === 256) {
  36916. codeLength = 9;
  36917. nextCode = 258;
  36918. currentSequenceLength = 0;
  36919. continue;
  36920. } else {
  36921. this.eof = true;
  36922. delete this.lzwState;
  36923. break;
  36924. }
  36925. if (hasPrev) {
  36926. dictionaryPrevCodes[nextCode] = prevCode;
  36927. dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1;
  36928. dictionaryValues[nextCode] = currentSequence[0];
  36929. nextCode++;
  36930. codeLength = (nextCode + earlyChange) & (nextCode + earlyChange - 1) ?
  36931. codeLength : Math.min(Math.log(nextCode + earlyChange) /
  36932. 0.6931471805599453 + 1, 12) | 0;
  36933. }
  36934. prevCode = code;
  36935. decodedLength += currentSequenceLength;
  36936. if (estimatedDecodedSize < decodedLength) {
  36937. do {
  36938. estimatedDecodedSize += decodedSizeDelta;
  36939. } while (estimatedDecodedSize < decodedLength);
  36940. buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
  36941. }
  36942. for (j = 0; j < currentSequenceLength; j++) {
  36943. buffer[currentBufferLength++] = currentSequence[j];
  36944. }
  36945. }
  36946. lzwState.nextCode = nextCode;
  36947. lzwState.codeLength = codeLength;
  36948. lzwState.prevCode = prevCode;
  36949. lzwState.currentSequenceLength = currentSequenceLength;
  36950. this.bufferLength = currentBufferLength;
  36951. };
  36952. return LZWStream;
  36953. })();
  36954. var NullStream = (function NullStreamClosure() {
  36955. function NullStream() {
  36956. Stream.call(this, new Uint8Array(0));
  36957. }
  36958. NullStream.prototype = Stream.prototype;
  36959. return NullStream;
  36960. })();
  36961. var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
  36962. setup: function wphSetup(handler) {
  36963. var pdfManager;
  36964. function loadDocument(recoveryMode) {
  36965. var loadDocumentCapability = createPromiseCapability();
  36966. var parseSuccess = function parseSuccess() {
  36967. var numPagesPromise = pdfManager.ensureDoc('numPages');
  36968. var fingerprintPromise = pdfManager.ensureDoc('fingerprint');
  36969. var encryptedPromise = pdfManager.ensureXRef('encrypt');
  36970. Promise.all([numPagesPromise, fingerprintPromise,
  36971. encryptedPromise]).then(function onDocReady(results) {
  36972. var doc = {
  36973. numPages: results[0],
  36974. fingerprint: results[1],
  36975. encrypted: !!results[2],
  36976. };
  36977. loadDocumentCapability.resolve(doc);
  36978. },
  36979. parseFailure);
  36980. };
  36981. var parseFailure = function parseFailure(e) {
  36982. loadDocumentCapability.reject(e);
  36983. };
  36984. pdfManager.ensureDoc('checkHeader', []).then(function() {
  36985. pdfManager.ensureDoc('parseStartXRef', []).then(function() {
  36986. pdfManager.ensureDoc('parse', [recoveryMode]).then(
  36987. parseSuccess, parseFailure);
  36988. }, parseFailure);
  36989. }, parseFailure);
  36990. return loadDocumentCapability.promise;
  36991. }
  36992. function getPdfManager(data) {
  36993. var pdfManagerCapability = createPromiseCapability();
  36994. var source = data.source;
  36995. var disableRange = data.disableRange;
  36996. if (source.data) {
  36997. try {
  36998. pdfManager = new LocalPdfManager(source.data, source.password);
  36999. pdfManagerCapability.resolve();
  37000. } catch (ex) {
  37001. pdfManagerCapability.reject(ex);
  37002. }
  37003. return pdfManagerCapability.promise;
  37004. } else if (source.chunkedViewerLoading) {
  37005. try {
  37006. pdfManager = new NetworkPdfManager(source, handler);
  37007. pdfManagerCapability.resolve();
  37008. } catch (ex) {
  37009. pdfManagerCapability.reject(ex);
  37010. }
  37011. return pdfManagerCapability.promise;
  37012. }
  37013. var networkManager = new NetworkManager(source.url, {
  37014. httpHeaders: source.httpHeaders,
  37015. withCredentials: source.withCredentials
  37016. });
  37017. var cachedChunks = [];
  37018. var fullRequestXhrId = networkManager.requestFull({
  37019. onHeadersReceived: function onHeadersReceived() {
  37020. if (disableRange) {
  37021. return;
  37022. }
  37023. var fullRequestXhr = networkManager.getRequestXhr(fullRequestXhrId);
  37024. if (fullRequestXhr.getResponseHeader('Accept-Ranges') !== 'bytes') {
  37025. return;
  37026. }
  37027. var contentEncoding =
  37028. fullRequestXhr.getResponseHeader('Content-Encoding') || 'identity';
  37029. if (contentEncoding !== 'identity') {
  37030. return;
  37031. }
  37032. var length = fullRequestXhr.getResponseHeader('Content-Length');
  37033. length = parseInt(length, 10);
  37034. if (!isInt(length)) {
  37035. return;
  37036. }
  37037. source.length = length;
  37038. if (length <= 2 * RANGE_CHUNK_SIZE) {
  37039. // The file size is smaller than the size of two chunks, so it does
  37040. // not make any sense to abort the request and retry with a range
  37041. // request.
  37042. return;
  37043. }
  37044. if (networkManager.isStreamingRequest(fullRequestXhrId)) {
  37045. // We can continue fetching when progressive loading is enabled,
  37046. // and we don't need the autoFetch feature.
  37047. source.disableAutoFetch = true;
  37048. } else {
  37049. // NOTE: by cancelling the full request, and then issuing range
  37050. // requests, there will be an issue for sites where you can only
  37051. // request the pdf once. However, if this is the case, then the
  37052. // server should not be returning that it can support range
  37053. // requests.
  37054. networkManager.abortRequest(fullRequestXhrId);
  37055. }
  37056. try {
  37057. pdfManager = new NetworkPdfManager(source, handler);
  37058. pdfManagerCapability.resolve(pdfManager);
  37059. } catch (ex) {
  37060. pdfManagerCapability.reject(ex);
  37061. }
  37062. },
  37063. onProgressiveData: source.disableStream ? null :
  37064. function onProgressiveData(chunk) {
  37065. if (!pdfManager) {
  37066. cachedChunks.push(chunk);
  37067. return;
  37068. }
  37069. pdfManager.sendProgressiveData(chunk);
  37070. },
  37071. onDone: function onDone(args) {
  37072. if (pdfManager) {
  37073. return; // already processed
  37074. }
  37075. var pdfFile;
  37076. if (args === null) {
  37077. // TODO add some streaming manager, e.g. for unknown length files.
  37078. // The data was returned in the onProgressiveData, combining...
  37079. var pdfFileLength = 0, pos = 0;
  37080. cachedChunks.forEach(function (chunk) {
  37081. pdfFileLength += chunk.byteLength;
  37082. });
  37083. if (source.length && pdfFileLength !== source.length) {
  37084. warn('reported HTTP length is different from actual');
  37085. }
  37086. var pdfFileArray = new Uint8Array(pdfFileLength);
  37087. cachedChunks.forEach(function (chunk) {
  37088. pdfFileArray.set(new Uint8Array(chunk), pos);
  37089. pos += chunk.byteLength;
  37090. });
  37091. pdfFile = pdfFileArray.buffer;
  37092. } else {
  37093. pdfFile = args.chunk;
  37094. }
  37095. // the data is array, instantiating directly from it
  37096. try {
  37097. pdfManager = new LocalPdfManager(pdfFile, source.password);
  37098. pdfManagerCapability.resolve();
  37099. } catch (ex) {
  37100. pdfManagerCapability.reject(ex);
  37101. }
  37102. },
  37103. onError: function onError(status) {
  37104. var exception;
  37105. if (status === 404) {
  37106. exception = new MissingPDFException('Missing PDF "' +
  37107. source.url + '".');
  37108. handler.send('MissingPDF', exception);
  37109. } else {
  37110. exception = new UnexpectedResponseException(
  37111. 'Unexpected server response (' + status +
  37112. ') while retrieving PDF "' + source.url + '".', status);
  37113. handler.send('UnexpectedResponse', exception);
  37114. }
  37115. },
  37116. onProgress: function onProgress(evt) {
  37117. handler.send('DocProgress', {
  37118. loaded: evt.loaded,
  37119. total: evt.lengthComputable ? evt.total : source.length
  37120. });
  37121. }
  37122. });
  37123. return pdfManagerCapability.promise;
  37124. }
  37125. handler.on('test', function wphSetupTest(data) {
  37126. // check if Uint8Array can be sent to worker
  37127. if (!(data instanceof Uint8Array)) {
  37128. handler.send('test', false);
  37129. return;
  37130. }
  37131. // making sure postMessage transfers are working
  37132. var supportTransfers = data[0] === 255;
  37133. handler.postMessageTransfers = supportTransfers;
  37134. // check if the response property is supported by xhr
  37135. var xhr = new XMLHttpRequest();
  37136. var responseExists = 'response' in xhr;
  37137. // check if the property is actually implemented
  37138. try {
  37139. var dummy = xhr.responseType;
  37140. } catch (e) {
  37141. responseExists = false;
  37142. }
  37143. if (!responseExists) {
  37144. handler.send('test', false);
  37145. return;
  37146. }
  37147. handler.send('test', {
  37148. supportTypedArray: true,
  37149. supportTransfers: supportTransfers
  37150. });
  37151. });
  37152. handler.on('GetDocRequest', function wphSetupDoc(data) {
  37153. var onSuccess = function(doc) {
  37154. handler.send('GetDoc', { pdfInfo: doc });
  37155. };
  37156. var onFailure = function(e) {
  37157. if (e instanceof PasswordException) {
  37158. if (e.code === PasswordResponses.NEED_PASSWORD) {
  37159. handler.send('NeedPassword', e);
  37160. } else if (e.code === PasswordResponses.INCORRECT_PASSWORD) {
  37161. handler.send('IncorrectPassword', e);
  37162. }
  37163. } else if (e instanceof InvalidPDFException) {
  37164. handler.send('InvalidPDF', e);
  37165. } else if (e instanceof MissingPDFException) {
  37166. handler.send('MissingPDF', e);
  37167. } else if (e instanceof UnexpectedResponseException) {
  37168. handler.send('UnexpectedResponse', e);
  37169. } else {
  37170. handler.send('UnknownError',
  37171. new UnknownErrorException(e.message, e.toString()));
  37172. }
  37173. };
  37174. PDFJS.maxImageSize = data.maxImageSize === undefined ?
  37175. -1 : data.maxImageSize;
  37176. PDFJS.disableFontFace = data.disableFontFace;
  37177. PDFJS.disableCreateObjectURL = data.disableCreateObjectURL;
  37178. PDFJS.verbosity = data.verbosity;
  37179. PDFJS.cMapUrl = data.cMapUrl === undefined ?
  37180. null : data.cMapUrl;
  37181. PDFJS.cMapPacked = data.cMapPacked === true;
  37182. getPdfManager(data).then(function () {
  37183. handler.send('PDFManagerReady', null);
  37184. pdfManager.onLoadedStream().then(function(stream) {
  37185. handler.send('DataLoaded', { length: stream.bytes.byteLength });
  37186. });
  37187. }).then(function pdfManagerReady() {
  37188. loadDocument(false).then(onSuccess, function loadFailure(ex) {
  37189. // Try again with recoveryMode == true
  37190. if (!(ex instanceof XRefParseException)) {
  37191. if (ex instanceof PasswordException) {
  37192. // after password exception prepare to receive a new password
  37193. // to repeat loading
  37194. pdfManager.passwordChanged().then(pdfManagerReady);
  37195. }
  37196. onFailure(ex);
  37197. return;
  37198. }
  37199. pdfManager.requestLoadedStream();
  37200. pdfManager.onLoadedStream().then(function() {
  37201. loadDocument(true).then(onSuccess, onFailure);
  37202. });
  37203. }, onFailure);
  37204. }, onFailure);
  37205. });
  37206. handler.on('GetPage', function wphSetupGetPage(data) {
  37207. return pdfManager.getPage(data.pageIndex).then(function(page) {
  37208. var rotatePromise = pdfManager.ensure(page, 'rotate');
  37209. var refPromise = pdfManager.ensure(page, 'ref');
  37210. var viewPromise = pdfManager.ensure(page, 'view');
  37211. return Promise.all([rotatePromise, refPromise, viewPromise]).then(
  37212. function(results) {
  37213. return {
  37214. rotate: results[0],
  37215. ref: results[1],
  37216. view: results[2]
  37217. };
  37218. });
  37219. });
  37220. });
  37221. handler.on('GetPageIndex', function wphSetupGetPageIndex(data) {
  37222. var ref = new Ref(data.ref.num, data.ref.gen);
  37223. var catalog = pdfManager.pdfDocument.catalog;
  37224. return catalog.getPageIndex(ref);
  37225. });
  37226. handler.on('GetDestinations',
  37227. function wphSetupGetDestinations(data) {
  37228. return pdfManager.ensureCatalog('destinations');
  37229. }
  37230. );
  37231. handler.on('GetDestination',
  37232. function wphSetupGetDestination(data) {
  37233. return pdfManager.ensureCatalog('getDestination', [ data.id ]);
  37234. }
  37235. );
  37236. handler.on('GetAttachments',
  37237. function wphSetupGetAttachments(data) {
  37238. return pdfManager.ensureCatalog('attachments');
  37239. }
  37240. );
  37241. handler.on('GetJavaScript',
  37242. function wphSetupGetJavaScript(data) {
  37243. return pdfManager.ensureCatalog('javaScript');
  37244. }
  37245. );
  37246. handler.on('GetOutline',
  37247. function wphSetupGetOutline(data) {
  37248. return pdfManager.ensureCatalog('documentOutline');
  37249. }
  37250. );
  37251. handler.on('GetMetadata',
  37252. function wphSetupGetMetadata(data) {
  37253. return Promise.all([pdfManager.ensureDoc('documentInfo'),
  37254. pdfManager.ensureCatalog('metadata')]);
  37255. }
  37256. );
  37257. handler.on('GetData', function wphSetupGetData(data) {
  37258. pdfManager.requestLoadedStream();
  37259. return pdfManager.onLoadedStream().then(function(stream) {
  37260. return stream.bytes;
  37261. });
  37262. });
  37263. handler.on('GetStats',
  37264. function wphSetupGetStats(data) {
  37265. return pdfManager.pdfDocument.xref.stats;
  37266. }
  37267. );
  37268. handler.on('UpdatePassword', function wphSetupUpdatePassword(data) {
  37269. pdfManager.updatePassword(data);
  37270. });
  37271. handler.on('GetAnnotations', function wphSetupGetAnnotations(data) {
  37272. return pdfManager.getPage(data.pageIndex).then(function(page) {
  37273. return pdfManager.ensure(page, 'getAnnotationsData', []);
  37274. });
  37275. });
  37276. handler.on('RenderPageRequest', function wphSetupRenderPage(data) {
  37277. pdfManager.getPage(data.pageIndex).then(function(page) {
  37278. var pageNum = data.pageIndex + 1;
  37279. var start = Date.now();
  37280. // Pre compile the pdf page and fetch the fonts/images.
  37281. page.getOperatorList(handler, data.intent).then(function(operatorList) {
  37282. info('page=' + pageNum + ' - getOperatorList: time=' +
  37283. (Date.now() - start) + 'ms, len=' + operatorList.fnArray.length);
  37284. }, function(e) {
  37285. var minimumStackMessage =
  37286. 'worker.js: while trying to getPage() and getOperatorList()';
  37287. var wrappedException;
  37288. // Turn the error into an obj that can be serialized
  37289. if (typeof e === 'string') {
  37290. wrappedException = {
  37291. message: e,
  37292. stack: minimumStackMessage
  37293. };
  37294. } else if (typeof e === 'object') {
  37295. wrappedException = {
  37296. message: e.message || e.toString(),
  37297. stack: e.stack || minimumStackMessage
  37298. };
  37299. } else {
  37300. wrappedException = {
  37301. message: 'Unknown exception type: ' + (typeof e),
  37302. stack: minimumStackMessage
  37303. };
  37304. }
  37305. handler.send('PageError', {
  37306. pageNum: pageNum,
  37307. error: wrappedException,
  37308. intent: data.intent
  37309. });
  37310. });
  37311. });
  37312. }, this);
  37313. handler.on('GetTextContent', function wphExtractText(data) {
  37314. return pdfManager.getPage(data.pageIndex).then(function(page) {
  37315. var pageNum = data.pageIndex + 1;
  37316. var start = Date.now();
  37317. return page.extractTextContent().then(function(textContent) {
  37318. info('text indexing: page=' + pageNum + ' - time=' +
  37319. (Date.now() - start) + 'ms');
  37320. return textContent;
  37321. });
  37322. });
  37323. });
  37324. handler.on('Cleanup', function wphCleanup(data) {
  37325. return pdfManager.cleanup();
  37326. });
  37327. handler.on('Terminate', function wphTerminate(data) {
  37328. pdfManager.terminate();
  37329. });
  37330. }
  37331. };
  37332. var consoleTimer = {};
  37333. var workerConsole = {
  37334. log: function log() {
  37335. var args = Array.prototype.slice.call(arguments);
  37336. globalScope.postMessage({
  37337. action: 'console_log',
  37338. data: args
  37339. });
  37340. },
  37341. error: function error() {
  37342. var args = Array.prototype.slice.call(arguments);
  37343. globalScope.postMessage({
  37344. action: 'console_error',
  37345. data: args
  37346. });
  37347. throw 'pdf.js execution error';
  37348. },
  37349. time: function time(name) {
  37350. consoleTimer[name] = Date.now();
  37351. },
  37352. timeEnd: function timeEnd(name) {
  37353. var time = consoleTimer[name];
  37354. if (!time) {
  37355. error('Unknown timer name ' + name);
  37356. }
  37357. this.log('Timer:', name, Date.now() - time);
  37358. }
  37359. };
  37360. // Worker thread?
  37361. if (typeof window === 'undefined') {
  37362. if (!('console' in globalScope)) {
  37363. globalScope.console = workerConsole;
  37364. }
  37365. // Listen for unsupported features so we can pass them on to the main thread.
  37366. PDFJS.UnsupportedManager.listen(function (msg) {
  37367. globalScope.postMessage({
  37368. action: '_unsupported_feature',
  37369. data: msg
  37370. });
  37371. });
  37372. var handler = new MessageHandler('worker_processor', this);
  37373. WorkerMessageHandler.setup(handler);
  37374. }
  37375. /* This class implements the QM Coder decoding as defined in
  37376. * JPEG 2000 Part I Final Committee Draft Version 1.0
  37377. * Annex C.3 Arithmetic decoding procedure
  37378. * available at http://www.jpeg.org/public/fcd15444-1.pdf
  37379. *
  37380. * The arithmetic decoder is used in conjunction with context models to decode
  37381. * JPEG2000 and JBIG2 streams.
  37382. */
  37383. var ArithmeticDecoder = (function ArithmeticDecoderClosure() {
  37384. // Table C-2
  37385. var QeTable = [
  37386. {qe: 0x5601, nmps: 1, nlps: 1, switchFlag: 1},
  37387. {qe: 0x3401, nmps: 2, nlps: 6, switchFlag: 0},
  37388. {qe: 0x1801, nmps: 3, nlps: 9, switchFlag: 0},
  37389. {qe: 0x0AC1, nmps: 4, nlps: 12, switchFlag: 0},
  37390. {qe: 0x0521, nmps: 5, nlps: 29, switchFlag: 0},
  37391. {qe: 0x0221, nmps: 38, nlps: 33, switchFlag: 0},
  37392. {qe: 0x5601, nmps: 7, nlps: 6, switchFlag: 1},
  37393. {qe: 0x5401, nmps: 8, nlps: 14, switchFlag: 0},
  37394. {qe: 0x4801, nmps: 9, nlps: 14, switchFlag: 0},
  37395. {qe: 0x3801, nmps: 10, nlps: 14, switchFlag: 0},
  37396. {qe: 0x3001, nmps: 11, nlps: 17, switchFlag: 0},
  37397. {qe: 0x2401, nmps: 12, nlps: 18, switchFlag: 0},
  37398. {qe: 0x1C01, nmps: 13, nlps: 20, switchFlag: 0},
  37399. {qe: 0x1601, nmps: 29, nlps: 21, switchFlag: 0},
  37400. {qe: 0x5601, nmps: 15, nlps: 14, switchFlag: 1},
  37401. {qe: 0x5401, nmps: 16, nlps: 14, switchFlag: 0},
  37402. {qe: 0x5101, nmps: 17, nlps: 15, switchFlag: 0},
  37403. {qe: 0x4801, nmps: 18, nlps: 16, switchFlag: 0},
  37404. {qe: 0x3801, nmps: 19, nlps: 17, switchFlag: 0},
  37405. {qe: 0x3401, nmps: 20, nlps: 18, switchFlag: 0},
  37406. {qe: 0x3001, nmps: 21, nlps: 19, switchFlag: 0},
  37407. {qe: 0x2801, nmps: 22, nlps: 19, switchFlag: 0},
  37408. {qe: 0x2401, nmps: 23, nlps: 20, switchFlag: 0},
  37409. {qe: 0x2201, nmps: 24, nlps: 21, switchFlag: 0},
  37410. {qe: 0x1C01, nmps: 25, nlps: 22, switchFlag: 0},
  37411. {qe: 0x1801, nmps: 26, nlps: 23, switchFlag: 0},
  37412. {qe: 0x1601, nmps: 27, nlps: 24, switchFlag: 0},
  37413. {qe: 0x1401, nmps: 28, nlps: 25, switchFlag: 0},
  37414. {qe: 0x1201, nmps: 29, nlps: 26, switchFlag: 0},
  37415. {qe: 0x1101, nmps: 30, nlps: 27, switchFlag: 0},
  37416. {qe: 0x0AC1, nmps: 31, nlps: 28, switchFlag: 0},
  37417. {qe: 0x09C1, nmps: 32, nlps: 29, switchFlag: 0},
  37418. {qe: 0x08A1, nmps: 33, nlps: 30, switchFlag: 0},
  37419. {qe: 0x0521, nmps: 34, nlps: 31, switchFlag: 0},
  37420. {qe: 0x0441, nmps: 35, nlps: 32, switchFlag: 0},
  37421. {qe: 0x02A1, nmps: 36, nlps: 33, switchFlag: 0},
  37422. {qe: 0x0221, nmps: 37, nlps: 34, switchFlag: 0},
  37423. {qe: 0x0141, nmps: 38, nlps: 35, switchFlag: 0},
  37424. {qe: 0x0111, nmps: 39, nlps: 36, switchFlag: 0},
  37425. {qe: 0x0085, nmps: 40, nlps: 37, switchFlag: 0},
  37426. {qe: 0x0049, nmps: 41, nlps: 38, switchFlag: 0},
  37427. {qe: 0x0025, nmps: 42, nlps: 39, switchFlag: 0},
  37428. {qe: 0x0015, nmps: 43, nlps: 40, switchFlag: 0},
  37429. {qe: 0x0009, nmps: 44, nlps: 41, switchFlag: 0},
  37430. {qe: 0x0005, nmps: 45, nlps: 42, switchFlag: 0},
  37431. {qe: 0x0001, nmps: 45, nlps: 43, switchFlag: 0},
  37432. {qe: 0x5601, nmps: 46, nlps: 46, switchFlag: 0}
  37433. ];
  37434. // C.3.5 Initialisation of the decoder (INITDEC)
  37435. function ArithmeticDecoder(data, start, end) {
  37436. this.data = data;
  37437. this.bp = start;
  37438. this.dataEnd = end;
  37439. this.chigh = data[start];
  37440. this.clow = 0;
  37441. this.byteIn();
  37442. this.chigh = ((this.chigh << 7) & 0xFFFF) | ((this.clow >> 9) & 0x7F);
  37443. this.clow = (this.clow << 7) & 0xFFFF;
  37444. this.ct -= 7;
  37445. this.a = 0x8000;
  37446. }
  37447. ArithmeticDecoder.prototype = {
  37448. // C.3.4 Compressed data input (BYTEIN)
  37449. byteIn: function ArithmeticDecoder_byteIn() {
  37450. var data = this.data;
  37451. var bp = this.bp;
  37452. if (data[bp] === 0xFF) {
  37453. var b1 = data[bp + 1];
  37454. if (b1 > 0x8F) {
  37455. this.clow += 0xFF00;
  37456. this.ct = 8;
  37457. } else {
  37458. bp++;
  37459. this.clow += (data[bp] << 9);
  37460. this.ct = 7;
  37461. this.bp = bp;
  37462. }
  37463. } else {
  37464. bp++;
  37465. this.clow += bp < this.dataEnd ? (data[bp] << 8) : 0xFF00;
  37466. this.ct = 8;
  37467. this.bp = bp;
  37468. }
  37469. if (this.clow > 0xFFFF) {
  37470. this.chigh += (this.clow >> 16);
  37471. this.clow &= 0xFFFF;
  37472. }
  37473. },
  37474. // C.3.2 Decoding a decision (DECODE)
  37475. readBit: function ArithmeticDecoder_readBit(contexts, pos) {
  37476. // contexts are packed into 1 byte:
  37477. // highest 7 bits carry cx.index, lowest bit carries cx.mps
  37478. var cx_index = contexts[pos] >> 1, cx_mps = contexts[pos] & 1;
  37479. var qeTableIcx = QeTable[cx_index];
  37480. var qeIcx = qeTableIcx.qe;
  37481. var d;
  37482. var a = this.a - qeIcx;
  37483. if (this.chigh < qeIcx) {
  37484. // exchangeLps
  37485. if (a < qeIcx) {
  37486. a = qeIcx;
  37487. d = cx_mps;
  37488. cx_index = qeTableIcx.nmps;
  37489. } else {
  37490. a = qeIcx;
  37491. d = 1 ^ cx_mps;
  37492. if (qeTableIcx.switchFlag === 1) {
  37493. cx_mps = d;
  37494. }
  37495. cx_index = qeTableIcx.nlps;
  37496. }
  37497. } else {
  37498. this.chigh -= qeIcx;
  37499. if ((a & 0x8000) !== 0) {
  37500. this.a = a;
  37501. return cx_mps;
  37502. }
  37503. // exchangeMps
  37504. if (a < qeIcx) {
  37505. d = 1 ^ cx_mps;
  37506. if (qeTableIcx.switchFlag === 1) {
  37507. cx_mps = d;
  37508. }
  37509. cx_index = qeTableIcx.nlps;
  37510. } else {
  37511. d = cx_mps;
  37512. cx_index = qeTableIcx.nmps;
  37513. }
  37514. }
  37515. // C.3.3 renormD;
  37516. do {
  37517. if (this.ct === 0) {
  37518. this.byteIn();
  37519. }
  37520. a <<= 1;
  37521. this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1);
  37522. this.clow = (this.clow << 1) & 0xFFFF;
  37523. this.ct--;
  37524. } while ((a & 0x8000) === 0);
  37525. this.a = a;
  37526. contexts[pos] = cx_index << 1 | cx_mps;
  37527. return d;
  37528. }
  37529. };
  37530. return ArithmeticDecoder;
  37531. })();
  37532. var JpegImage = (function jpegImage() {
  37533. var dctZigZag = new Uint8Array([
  37534. 0,
  37535. 1, 8,
  37536. 16, 9, 2,
  37537. 3, 10, 17, 24,
  37538. 32, 25, 18, 11, 4,
  37539. 5, 12, 19, 26, 33, 40,
  37540. 48, 41, 34, 27, 20, 13, 6,
  37541. 7, 14, 21, 28, 35, 42, 49, 56,
  37542. 57, 50, 43, 36, 29, 22, 15,
  37543. 23, 30, 37, 44, 51, 58,
  37544. 59, 52, 45, 38, 31,
  37545. 39, 46, 53, 60,
  37546. 61, 54, 47,
  37547. 55, 62,
  37548. 63
  37549. ]);
  37550. var dctCos1 = 4017; // cos(pi/16)
  37551. var dctSin1 = 799; // sin(pi/16)
  37552. var dctCos3 = 3406; // cos(3*pi/16)
  37553. var dctSin3 = 2276; // sin(3*pi/16)
  37554. var dctCos6 = 1567; // cos(6*pi/16)
  37555. var dctSin6 = 3784; // sin(6*pi/16)
  37556. var dctSqrt2 = 5793; // sqrt(2)
  37557. var dctSqrt1d2 = 2896; // sqrt(2) / 2
  37558. function constructor() {
  37559. }
  37560. function buildHuffmanTable(codeLengths, values) {
  37561. var k = 0, code = [], i, j, length = 16;
  37562. while (length > 0 && !codeLengths[length - 1]) {
  37563. length--;
  37564. }
  37565. code.push({children: [], index: 0});
  37566. var p = code[0], q;
  37567. for (i = 0; i < length; i++) {
  37568. for (j = 0; j < codeLengths[i]; j++) {
  37569. p = code.pop();
  37570. p.children[p.index] = values[k];
  37571. while (p.index > 0) {
  37572. p = code.pop();
  37573. }
  37574. p.index++;
  37575. code.push(p);
  37576. while (code.length <= i) {
  37577. code.push(q = {children: [], index: 0});
  37578. p.children[p.index] = q.children;
  37579. p = q;
  37580. }
  37581. k++;
  37582. }
  37583. if (i + 1 < length) {
  37584. // p here points to last code
  37585. code.push(q = {children: [], index: 0});
  37586. p.children[p.index] = q.children;
  37587. p = q;
  37588. }
  37589. }
  37590. return code[0].children;
  37591. }
  37592. function getBlockBufferOffset(component, row, col) {
  37593. return 64 * ((component.blocksPerLine + 1) * row + col);
  37594. }
  37595. function decodeScan(data, offset, frame, components, resetInterval,
  37596. spectralStart, spectralEnd, successivePrev, successive) {
  37597. var precision = frame.precision;
  37598. var samplesPerLine = frame.samplesPerLine;
  37599. var scanLines = frame.scanLines;
  37600. var mcusPerLine = frame.mcusPerLine;
  37601. var progressive = frame.progressive;
  37602. var maxH = frame.maxH, maxV = frame.maxV;
  37603. var startOffset = offset, bitsData = 0, bitsCount = 0;
  37604. function readBit() {
  37605. if (bitsCount > 0) {
  37606. bitsCount--;
  37607. return (bitsData >> bitsCount) & 1;
  37608. }
  37609. bitsData = data[offset++];
  37610. if (bitsData === 0xFF) {
  37611. var nextByte = data[offset++];
  37612. if (nextByte) {
  37613. throw 'unexpected marker: ' +
  37614. ((bitsData << 8) | nextByte).toString(16);
  37615. }
  37616. // unstuff 0
  37617. }
  37618. bitsCount = 7;
  37619. return bitsData >>> 7;
  37620. }
  37621. function decodeHuffman(tree) {
  37622. var node = tree;
  37623. while (true) {
  37624. node = node[readBit()];
  37625. if (typeof node === 'number') {
  37626. return node;
  37627. }
  37628. if (typeof node !== 'object') {
  37629. throw 'invalid huffman sequence';
  37630. }
  37631. }
  37632. }
  37633. function receive(length) {
  37634. var n = 0;
  37635. while (length > 0) {
  37636. n = (n << 1) | readBit();
  37637. length--;
  37638. }
  37639. return n;
  37640. }
  37641. function receiveAndExtend(length) {
  37642. if (length === 1) {
  37643. return readBit() === 1 ? 1 : -1;
  37644. }
  37645. var n = receive(length);
  37646. if (n >= 1 << (length - 1)) {
  37647. return n;
  37648. }
  37649. return n + (-1 << length) + 1;
  37650. }
  37651. function decodeBaseline(component, offset) {
  37652. var t = decodeHuffman(component.huffmanTableDC);
  37653. var diff = t === 0 ? 0 : receiveAndExtend(t);
  37654. component.blockData[offset] = (component.pred += diff);
  37655. var k = 1;
  37656. while (k < 64) {
  37657. var rs = decodeHuffman(component.huffmanTableAC);
  37658. var s = rs & 15, r = rs >> 4;
  37659. if (s === 0) {
  37660. if (r < 15) {
  37661. break;
  37662. }
  37663. k += 16;
  37664. continue;
  37665. }
  37666. k += r;
  37667. var z = dctZigZag[k];
  37668. component.blockData[offset + z] = receiveAndExtend(s);
  37669. k++;
  37670. }
  37671. }
  37672. function decodeDCFirst(component, offset) {
  37673. var t = decodeHuffman(component.huffmanTableDC);
  37674. var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
  37675. component.blockData[offset] = (component.pred += diff);
  37676. }
  37677. function decodeDCSuccessive(component, offset) {
  37678. component.blockData[offset] |= readBit() << successive;
  37679. }
  37680. var eobrun = 0;
  37681. function decodeACFirst(component, offset) {
  37682. if (eobrun > 0) {
  37683. eobrun--;
  37684. return;
  37685. }
  37686. var k = spectralStart, e = spectralEnd;
  37687. while (k <= e) {
  37688. var rs = decodeHuffman(component.huffmanTableAC);
  37689. var s = rs & 15, r = rs >> 4;
  37690. if (s === 0) {
  37691. if (r < 15) {
  37692. eobrun = receive(r) + (1 << r) - 1;
  37693. break;
  37694. }
  37695. k += 16;
  37696. continue;
  37697. }
  37698. k += r;
  37699. var z = dctZigZag[k];
  37700. component.blockData[offset + z] =
  37701. receiveAndExtend(s) * (1 << successive);
  37702. k++;
  37703. }
  37704. }
  37705. var successiveACState = 0, successiveACNextValue;
  37706. function decodeACSuccessive(component, offset) {
  37707. var k = spectralStart;
  37708. var e = spectralEnd;
  37709. var r = 0;
  37710. var s;
  37711. var rs;
  37712. while (k <= e) {
  37713. var z = dctZigZag[k];
  37714. switch (successiveACState) {
  37715. case 0: // initial state
  37716. rs = decodeHuffman(component.huffmanTableAC);
  37717. s = rs & 15;
  37718. r = rs >> 4;
  37719. if (s === 0) {
  37720. if (r < 15) {
  37721. eobrun = receive(r) + (1 << r);
  37722. successiveACState = 4;
  37723. } else {
  37724. r = 16;
  37725. successiveACState = 1;
  37726. }
  37727. } else {
  37728. if (s !== 1) {
  37729. throw 'invalid ACn encoding';
  37730. }
  37731. successiveACNextValue = receiveAndExtend(s);
  37732. successiveACState = r ? 2 : 3;
  37733. }
  37734. continue;
  37735. case 1: // skipping r zero items
  37736. case 2:
  37737. if (component.blockData[offset + z]) {
  37738. component.blockData[offset + z] += (readBit() << successive);
  37739. } else {
  37740. r--;
  37741. if (r === 0) {
  37742. successiveACState = successiveACState === 2 ? 3 : 0;
  37743. }
  37744. }
  37745. break;
  37746. case 3: // set value for a zero item
  37747. if (component.blockData[offset + z]) {
  37748. component.blockData[offset + z] += (readBit() << successive);
  37749. } else {
  37750. component.blockData[offset + z] =
  37751. successiveACNextValue << successive;
  37752. successiveACState = 0;
  37753. }
  37754. break;
  37755. case 4: // eob
  37756. if (component.blockData[offset + z]) {
  37757. component.blockData[offset + z] += (readBit() << successive);
  37758. }
  37759. break;
  37760. }
  37761. k++;
  37762. }
  37763. if (successiveACState === 4) {
  37764. eobrun--;
  37765. if (eobrun === 0) {
  37766. successiveACState = 0;
  37767. }
  37768. }
  37769. }
  37770. function decodeMcu(component, decode, mcu, row, col) {
  37771. var mcuRow = (mcu / mcusPerLine) | 0;
  37772. var mcuCol = mcu % mcusPerLine;
  37773. var blockRow = mcuRow * component.v + row;
  37774. var blockCol = mcuCol * component.h + col;
  37775. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  37776. decode(component, offset);
  37777. }
  37778. function decodeBlock(component, decode, mcu) {
  37779. var blockRow = (mcu / component.blocksPerLine) | 0;
  37780. var blockCol = mcu % component.blocksPerLine;
  37781. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  37782. decode(component, offset);
  37783. }
  37784. var componentsLength = components.length;
  37785. var component, i, j, k, n;
  37786. var decodeFn;
  37787. if (progressive) {
  37788. if (spectralStart === 0) {
  37789. decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
  37790. } else {
  37791. decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
  37792. }
  37793. } else {
  37794. decodeFn = decodeBaseline;
  37795. }
  37796. var mcu = 0, marker;
  37797. var mcuExpected;
  37798. if (componentsLength === 1) {
  37799. mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
  37800. } else {
  37801. mcuExpected = mcusPerLine * frame.mcusPerColumn;
  37802. }
  37803. if (!resetInterval) {
  37804. resetInterval = mcuExpected;
  37805. }
  37806. var h, v;
  37807. while (mcu < mcuExpected) {
  37808. // reset interval stuff
  37809. for (i = 0; i < componentsLength; i++) {
  37810. components[i].pred = 0;
  37811. }
  37812. eobrun = 0;
  37813. if (componentsLength === 1) {
  37814. component = components[0];
  37815. for (n = 0; n < resetInterval; n++) {
  37816. decodeBlock(component, decodeFn, mcu);
  37817. mcu++;
  37818. }
  37819. } else {
  37820. for (n = 0; n < resetInterval; n++) {
  37821. for (i = 0; i < componentsLength; i++) {
  37822. component = components[i];
  37823. h = component.h;
  37824. v = component.v;
  37825. for (j = 0; j < v; j++) {
  37826. for (k = 0; k < h; k++) {
  37827. decodeMcu(component, decodeFn, mcu, j, k);
  37828. }
  37829. }
  37830. }
  37831. mcu++;
  37832. }
  37833. }
  37834. // find marker
  37835. bitsCount = 0;
  37836. marker = (data[offset] << 8) | data[offset + 1];
  37837. if (marker <= 0xFF00) {
  37838. throw 'marker was not found';
  37839. }
  37840. if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
  37841. offset += 2;
  37842. } else {
  37843. break;
  37844. }
  37845. }
  37846. return offset - startOffset;
  37847. }
  37848. // A port of poppler's IDCT method which in turn is taken from:
  37849. // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
  37850. // 'Practical Fast 1-D DCT Algorithms with 11 Multiplications',
  37851. // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
  37852. // 988-991.
  37853. function quantizeAndInverse(component, blockBufferOffset, p) {
  37854. var qt = component.quantizationTable, blockData = component.blockData;
  37855. var v0, v1, v2, v3, v4, v5, v6, v7;
  37856. var p0, p1, p2, p3, p4, p5, p6, p7;
  37857. var t;
  37858. // inverse DCT on rows
  37859. for (var row = 0; row < 64; row += 8) {
  37860. // gather block data
  37861. p0 = blockData[blockBufferOffset + row];
  37862. p1 = blockData[blockBufferOffset + row + 1];
  37863. p2 = blockData[blockBufferOffset + row + 2];
  37864. p3 = blockData[blockBufferOffset + row + 3];
  37865. p4 = blockData[blockBufferOffset + row + 4];
  37866. p5 = blockData[blockBufferOffset + row + 5];
  37867. p6 = blockData[blockBufferOffset + row + 6];
  37868. p7 = blockData[blockBufferOffset + row + 7];
  37869. // dequant p0
  37870. p0 *= qt[row];
  37871. // check for all-zero AC coefficients
  37872. if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
  37873. t = (dctSqrt2 * p0 + 512) >> 10;
  37874. p[row] = t;
  37875. p[row + 1] = t;
  37876. p[row + 2] = t;
  37877. p[row + 3] = t;
  37878. p[row + 4] = t;
  37879. p[row + 5] = t;
  37880. p[row + 6] = t;
  37881. p[row + 7] = t;
  37882. continue;
  37883. }
  37884. // dequant p1 ... p7
  37885. p1 *= qt[row + 1];
  37886. p2 *= qt[row + 2];
  37887. p3 *= qt[row + 3];
  37888. p4 *= qt[row + 4];
  37889. p5 *= qt[row + 5];
  37890. p6 *= qt[row + 6];
  37891. p7 *= qt[row + 7];
  37892. // stage 4
  37893. v0 = (dctSqrt2 * p0 + 128) >> 8;
  37894. v1 = (dctSqrt2 * p4 + 128) >> 8;
  37895. v2 = p2;
  37896. v3 = p6;
  37897. v4 = (dctSqrt1d2 * (p1 - p7) + 128) >> 8;
  37898. v7 = (dctSqrt1d2 * (p1 + p7) + 128) >> 8;
  37899. v5 = p3 << 4;
  37900. v6 = p5 << 4;
  37901. // stage 3
  37902. v0 = (v0 + v1 + 1) >> 1;
  37903. v1 = v0 - v1;
  37904. t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
  37905. v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
  37906. v3 = t;
  37907. v4 = (v4 + v6 + 1) >> 1;
  37908. v6 = v4 - v6;
  37909. v7 = (v7 + v5 + 1) >> 1;
  37910. v5 = v7 - v5;
  37911. // stage 2
  37912. v0 = (v0 + v3 + 1) >> 1;
  37913. v3 = v0 - v3;
  37914. v1 = (v1 + v2 + 1) >> 1;
  37915. v2 = v1 - v2;
  37916. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  37917. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  37918. v7 = t;
  37919. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  37920. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  37921. v6 = t;
  37922. // stage 1
  37923. p[row] = v0 + v7;
  37924. p[row + 7] = v0 - v7;
  37925. p[row + 1] = v1 + v6;
  37926. p[row + 6] = v1 - v6;
  37927. p[row + 2] = v2 + v5;
  37928. p[row + 5] = v2 - v5;
  37929. p[row + 3] = v3 + v4;
  37930. p[row + 4] = v3 - v4;
  37931. }
  37932. // inverse DCT on columns
  37933. for (var col = 0; col < 8; ++col) {
  37934. p0 = p[col];
  37935. p1 = p[col + 8];
  37936. p2 = p[col + 16];
  37937. p3 = p[col + 24];
  37938. p4 = p[col + 32];
  37939. p5 = p[col + 40];
  37940. p6 = p[col + 48];
  37941. p7 = p[col + 56];
  37942. // check for all-zero AC coefficients
  37943. if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
  37944. t = (dctSqrt2 * p0 + 8192) >> 14;
  37945. // convert to 8 bit
  37946. t = (t < -2040) ? 0 : (t >= 2024) ? 255 : (t + 2056) >> 4;
  37947. blockData[blockBufferOffset + col] = t;
  37948. blockData[blockBufferOffset + col + 8] = t;
  37949. blockData[blockBufferOffset + col + 16] = t;
  37950. blockData[blockBufferOffset + col + 24] = t;
  37951. blockData[blockBufferOffset + col + 32] = t;
  37952. blockData[blockBufferOffset + col + 40] = t;
  37953. blockData[blockBufferOffset + col + 48] = t;
  37954. blockData[blockBufferOffset + col + 56] = t;
  37955. continue;
  37956. }
  37957. // stage 4
  37958. v0 = (dctSqrt2 * p0 + 2048) >> 12;
  37959. v1 = (dctSqrt2 * p4 + 2048) >> 12;
  37960. v2 = p2;
  37961. v3 = p6;
  37962. v4 = (dctSqrt1d2 * (p1 - p7) + 2048) >> 12;
  37963. v7 = (dctSqrt1d2 * (p1 + p7) + 2048) >> 12;
  37964. v5 = p3;
  37965. v6 = p5;
  37966. // stage 3
  37967. // Shift v0 by 128.5 << 5 here, so we don't need to shift p0...p7 when
  37968. // converting to UInt8 range later.
  37969. v0 = ((v0 + v1 + 1) >> 1) + 4112;
  37970. v1 = v0 - v1;
  37971. t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
  37972. v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
  37973. v3 = t;
  37974. v4 = (v4 + v6 + 1) >> 1;
  37975. v6 = v4 - v6;
  37976. v7 = (v7 + v5 + 1) >> 1;
  37977. v5 = v7 - v5;
  37978. // stage 2
  37979. v0 = (v0 + v3 + 1) >> 1;
  37980. v3 = v0 - v3;
  37981. v1 = (v1 + v2 + 1) >> 1;
  37982. v2 = v1 - v2;
  37983. t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
  37984. v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
  37985. v7 = t;
  37986. t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
  37987. v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
  37988. v6 = t;
  37989. // stage 1
  37990. p0 = v0 + v7;
  37991. p7 = v0 - v7;
  37992. p1 = v1 + v6;
  37993. p6 = v1 - v6;
  37994. p2 = v2 + v5;
  37995. p5 = v2 - v5;
  37996. p3 = v3 + v4;
  37997. p4 = v3 - v4;
  37998. // convert to 8-bit integers
  37999. p0 = (p0 < 16) ? 0 : (p0 >= 4080) ? 255 : p0 >> 4;
  38000. p1 = (p1 < 16) ? 0 : (p1 >= 4080) ? 255 : p1 >> 4;
  38001. p2 = (p2 < 16) ? 0 : (p2 >= 4080) ? 255 : p2 >> 4;
  38002. p3 = (p3 < 16) ? 0 : (p3 >= 4080) ? 255 : p3 >> 4;
  38003. p4 = (p4 < 16) ? 0 : (p4 >= 4080) ? 255 : p4 >> 4;
  38004. p5 = (p5 < 16) ? 0 : (p5 >= 4080) ? 255 : p5 >> 4;
  38005. p6 = (p6 < 16) ? 0 : (p6 >= 4080) ? 255 : p6 >> 4;
  38006. p7 = (p7 < 16) ? 0 : (p7 >= 4080) ? 255 : p7 >> 4;
  38007. // store block data
  38008. blockData[blockBufferOffset + col] = p0;
  38009. blockData[blockBufferOffset + col + 8] = p1;
  38010. blockData[blockBufferOffset + col + 16] = p2;
  38011. blockData[blockBufferOffset + col + 24] = p3;
  38012. blockData[blockBufferOffset + col + 32] = p4;
  38013. blockData[blockBufferOffset + col + 40] = p5;
  38014. blockData[blockBufferOffset + col + 48] = p6;
  38015. blockData[blockBufferOffset + col + 56] = p7;
  38016. }
  38017. }
  38018. function buildComponentData(frame, component) {
  38019. var blocksPerLine = component.blocksPerLine;
  38020. var blocksPerColumn = component.blocksPerColumn;
  38021. var computationBuffer = new Int16Array(64);
  38022. for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
  38023. for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
  38024. var offset = getBlockBufferOffset(component, blockRow, blockCol);
  38025. quantizeAndInverse(component, offset, computationBuffer);
  38026. }
  38027. }
  38028. return component.blockData;
  38029. }
  38030. function clamp0to255(a) {
  38031. return a <= 0 ? 0 : a >= 255 ? 255 : a;
  38032. }
  38033. constructor.prototype = {
  38034. parse: function parse(data) {
  38035. function readUint16() {
  38036. var value = (data[offset] << 8) | data[offset + 1];
  38037. offset += 2;
  38038. return value;
  38039. }
  38040. function readDataBlock() {
  38041. var length = readUint16();
  38042. var array = data.subarray(offset, offset + length - 2);
  38043. offset += array.length;
  38044. return array;
  38045. }
  38046. function prepareComponents(frame) {
  38047. var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH);
  38048. var mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV);
  38049. for (var i = 0; i < frame.components.length; i++) {
  38050. component = frame.components[i];
  38051. var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) *
  38052. component.h / frame.maxH);
  38053. var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) *
  38054. component.v / frame.maxV);
  38055. var blocksPerLineForMcu = mcusPerLine * component.h;
  38056. var blocksPerColumnForMcu = mcusPerColumn * component.v;
  38057. var blocksBufferSize = 64 * blocksPerColumnForMcu *
  38058. (blocksPerLineForMcu + 1);
  38059. component.blockData = new Int16Array(blocksBufferSize);
  38060. component.blocksPerLine = blocksPerLine;
  38061. component.blocksPerColumn = blocksPerColumn;
  38062. }
  38063. frame.mcusPerLine = mcusPerLine;
  38064. frame.mcusPerColumn = mcusPerColumn;
  38065. }
  38066. var offset = 0, length = data.length;
  38067. var jfif = null;
  38068. var adobe = null;
  38069. var pixels = null;
  38070. var frame, resetInterval;
  38071. var quantizationTables = [];
  38072. var huffmanTablesAC = [], huffmanTablesDC = [];
  38073. var fileMarker = readUint16();
  38074. if (fileMarker !== 0xFFD8) { // SOI (Start of Image)
  38075. throw 'SOI not found';
  38076. }
  38077. fileMarker = readUint16();
  38078. while (fileMarker !== 0xFFD9) { // EOI (End of image)
  38079. var i, j, l;
  38080. switch(fileMarker) {
  38081. case 0xFFE0: // APP0 (Application Specific)
  38082. case 0xFFE1: // APP1
  38083. case 0xFFE2: // APP2
  38084. case 0xFFE3: // APP3
  38085. case 0xFFE4: // APP4
  38086. case 0xFFE5: // APP5
  38087. case 0xFFE6: // APP6
  38088. case 0xFFE7: // APP7
  38089. case 0xFFE8: // APP8
  38090. case 0xFFE9: // APP9
  38091. case 0xFFEA: // APP10
  38092. case 0xFFEB: // APP11
  38093. case 0xFFEC: // APP12
  38094. case 0xFFED: // APP13
  38095. case 0xFFEE: // APP14
  38096. case 0xFFEF: // APP15
  38097. case 0xFFFE: // COM (Comment)
  38098. var appData = readDataBlock();
  38099. if (fileMarker === 0xFFE0) {
  38100. if (appData[0] === 0x4A && appData[1] === 0x46 &&
  38101. appData[2] === 0x49 && appData[3] === 0x46 &&
  38102. appData[4] === 0) { // 'JFIF\x00'
  38103. jfif = {
  38104. version: { major: appData[5], minor: appData[6] },
  38105. densityUnits: appData[7],
  38106. xDensity: (appData[8] << 8) | appData[9],
  38107. yDensity: (appData[10] << 8) | appData[11],
  38108. thumbWidth: appData[12],
  38109. thumbHeight: appData[13],
  38110. thumbData: appData.subarray(14, 14 +
  38111. 3 * appData[12] * appData[13])
  38112. };
  38113. }
  38114. }
  38115. // TODO APP1 - Exif
  38116. if (fileMarker === 0xFFEE) {
  38117. if (appData[0] === 0x41 && appData[1] === 0x64 &&
  38118. appData[2] === 0x6F && appData[3] === 0x62 &&
  38119. appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00'
  38120. adobe = {
  38121. version: appData[6],
  38122. flags0: (appData[7] << 8) | appData[8],
  38123. flags1: (appData[9] << 8) | appData[10],
  38124. transformCode: appData[11]
  38125. };
  38126. }
  38127. }
  38128. break;
  38129. case 0xFFDB: // DQT (Define Quantization Tables)
  38130. var quantizationTablesLength = readUint16();
  38131. var quantizationTablesEnd = quantizationTablesLength + offset - 2;
  38132. var z;
  38133. while (offset < quantizationTablesEnd) {
  38134. var quantizationTableSpec = data[offset++];
  38135. var tableData = new Uint16Array(64);
  38136. if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
  38137. for (j = 0; j < 64; j++) {
  38138. z = dctZigZag[j];
  38139. tableData[z] = data[offset++];
  38140. }
  38141. } else if ((quantizationTableSpec >> 4) === 1) { //16 bit
  38142. for (j = 0; j < 64; j++) {
  38143. z = dctZigZag[j];
  38144. tableData[z] = readUint16();
  38145. }
  38146. } else {
  38147. throw 'DQT: invalid table spec';
  38148. }
  38149. quantizationTables[quantizationTableSpec & 15] = tableData;
  38150. }
  38151. break;
  38152. case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
  38153. case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
  38154. case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
  38155. if (frame) {
  38156. throw 'Only single frame JPEGs supported';
  38157. }
  38158. readUint16(); // skip data length
  38159. frame = {};
  38160. frame.extended = (fileMarker === 0xFFC1);
  38161. frame.progressive = (fileMarker === 0xFFC2);
  38162. frame.precision = data[offset++];
  38163. frame.scanLines = readUint16();
  38164. frame.samplesPerLine = readUint16();
  38165. frame.components = [];
  38166. frame.componentIds = {};
  38167. var componentsCount = data[offset++], componentId;
  38168. var maxH = 0, maxV = 0;
  38169. for (i = 0; i < componentsCount; i++) {
  38170. componentId = data[offset];
  38171. var h = data[offset + 1] >> 4;
  38172. var v = data[offset + 1] & 15;
  38173. if (maxH < h) {
  38174. maxH = h;
  38175. }
  38176. if (maxV < v) {
  38177. maxV = v;
  38178. }
  38179. var qId = data[offset + 2];
  38180. l = frame.components.push({
  38181. h: h,
  38182. v: v,
  38183. quantizationTable: quantizationTables[qId]
  38184. });
  38185. frame.componentIds[componentId] = l - 1;
  38186. offset += 3;
  38187. }
  38188. frame.maxH = maxH;
  38189. frame.maxV = maxV;
  38190. prepareComponents(frame);
  38191. break;
  38192. case 0xFFC4: // DHT (Define Huffman Tables)
  38193. var huffmanLength = readUint16();
  38194. for (i = 2; i < huffmanLength;) {
  38195. var huffmanTableSpec = data[offset++];
  38196. var codeLengths = new Uint8Array(16);
  38197. var codeLengthSum = 0;
  38198. for (j = 0; j < 16; j++, offset++) {
  38199. codeLengthSum += (codeLengths[j] = data[offset]);
  38200. }
  38201. var huffmanValues = new Uint8Array(codeLengthSum);
  38202. for (j = 0; j < codeLengthSum; j++, offset++) {
  38203. huffmanValues[j] = data[offset];
  38204. }
  38205. i += 17 + codeLengthSum;
  38206. ((huffmanTableSpec >> 4) === 0 ?
  38207. huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
  38208. buildHuffmanTable(codeLengths, huffmanValues);
  38209. }
  38210. break;
  38211. case 0xFFDD: // DRI (Define Restart Interval)
  38212. readUint16(); // skip data length
  38213. resetInterval = readUint16();
  38214. break;
  38215. case 0xFFDA: // SOS (Start of Scan)
  38216. var scanLength = readUint16();
  38217. var selectorsCount = data[offset++];
  38218. var components = [], component;
  38219. for (i = 0; i < selectorsCount; i++) {
  38220. var componentIndex = frame.componentIds[data[offset++]];
  38221. component = frame.components[componentIndex];
  38222. var tableSpec = data[offset++];
  38223. component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
  38224. component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
  38225. components.push(component);
  38226. }
  38227. var spectralStart = data[offset++];
  38228. var spectralEnd = data[offset++];
  38229. var successiveApproximation = data[offset++];
  38230. var processed = decodeScan(data, offset,
  38231. frame, components, resetInterval,
  38232. spectralStart, spectralEnd,
  38233. successiveApproximation >> 4, successiveApproximation & 15);
  38234. offset += processed;
  38235. break;
  38236. default:
  38237. if (data[offset - 3] === 0xFF &&
  38238. data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
  38239. // could be incorrect encoding -- last 0xFF byte of the previous
  38240. // block was eaten by the encoder
  38241. offset -= 3;
  38242. break;
  38243. }
  38244. throw 'unknown JPEG marker ' + fileMarker.toString(16);
  38245. }
  38246. fileMarker = readUint16();
  38247. }
  38248. this.width = frame.samplesPerLine;
  38249. this.height = frame.scanLines;
  38250. this.jfif = jfif;
  38251. this.adobe = adobe;
  38252. this.components = [];
  38253. for (i = 0; i < frame.components.length; i++) {
  38254. component = frame.components[i];
  38255. this.components.push({
  38256. output: buildComponentData(frame, component),
  38257. scaleX: component.h / frame.maxH,
  38258. scaleY: component.v / frame.maxV,
  38259. blocksPerLine: component.blocksPerLine,
  38260. blocksPerColumn: component.blocksPerColumn
  38261. });
  38262. }
  38263. this.numComponents = this.components.length;
  38264. },
  38265. _getLinearizedBlockData: function getLinearizedBlockData(width, height) {
  38266. var scaleX = this.width / width, scaleY = this.height / height;
  38267. var component, componentScaleX, componentScaleY, blocksPerScanline;
  38268. var x, y, i, j, k;
  38269. var index;
  38270. var offset = 0;
  38271. var output;
  38272. var numComponents = this.components.length;
  38273. var dataLength = width * height * numComponents;
  38274. var data = new Uint8Array(dataLength);
  38275. var xScaleBlockOffset = new Uint32Array(width);
  38276. var mask3LSB = 0xfffffff8; // used to clear the 3 LSBs
  38277. for (i = 0; i < numComponents; i++) {
  38278. component = this.components[i];
  38279. componentScaleX = component.scaleX * scaleX;
  38280. componentScaleY = component.scaleY * scaleY;
  38281. offset = i;
  38282. output = component.output;
  38283. blocksPerScanline = (component.blocksPerLine + 1) << 3;
  38284. // precalculate the xScaleBlockOffset
  38285. for (x = 0; x < width; x++) {
  38286. j = 0 | (x * componentScaleX);
  38287. xScaleBlockOffset[x] = ((j & mask3LSB) << 3) | (j & 7);
  38288. }
  38289. // linearize the blocks of the component
  38290. for (y = 0; y < height; y++) {
  38291. j = 0 | (y * componentScaleY);
  38292. index = blocksPerScanline * (j & mask3LSB) | ((j & 7) << 3);
  38293. for (x = 0; x < width; x++) {
  38294. data[offset] = output[index + xScaleBlockOffset[x]];
  38295. offset += numComponents;
  38296. }
  38297. }
  38298. }
  38299. // decodeTransform contains pairs of multiplier (-256..256) and additive
  38300. var transform = this.decodeTransform;
  38301. if (transform) {
  38302. for (i = 0; i < dataLength;) {
  38303. for (j = 0, k = 0; j < numComponents; j++, i++, k += 2) {
  38304. data[i] = ((data[i] * transform[k]) >> 8) + transform[k + 1];
  38305. }
  38306. }
  38307. }
  38308. return data;
  38309. },
  38310. _isColorConversionNeeded: function isColorConversionNeeded() {
  38311. if (this.adobe && this.adobe.transformCode) {
  38312. // The adobe transform marker overrides any previous setting
  38313. return true;
  38314. } else if (this.numComponents === 3) {
  38315. return true;
  38316. } else {
  38317. return false;
  38318. }
  38319. },
  38320. _convertYccToRgb: function convertYccToRgb(data) {
  38321. var Y, Cb, Cr;
  38322. for (var i = 0, length = data.length; i < length; i += 3) {
  38323. Y = data[i ];
  38324. Cb = data[i + 1];
  38325. Cr = data[i + 2];
  38326. data[i ] = clamp0to255(Y - 179.456 + 1.402 * Cr);
  38327. data[i + 1] = clamp0to255(Y + 135.459 - 0.344 * Cb - 0.714 * Cr);
  38328. data[i + 2] = clamp0to255(Y - 226.816 + 1.772 * Cb);
  38329. }
  38330. return data;
  38331. },
  38332. _convertYcckToRgb: function convertYcckToRgb(data) {
  38333. var Y, Cb, Cr, k;
  38334. var offset = 0;
  38335. for (var i = 0, length = data.length; i < length; i += 4) {
  38336. Y = data[i];
  38337. Cb = data[i + 1];
  38338. Cr = data[i + 2];
  38339. k = data[i + 3];
  38340. var r = -122.67195406894 +
  38341. Cb * (-6.60635669420364e-5 * Cb + 0.000437130475926232 * Cr -
  38342. 5.4080610064599e-5 * Y + 0.00048449797120281 * k -
  38343. 0.154362151871126) +
  38344. Cr * (-0.000957964378445773 * Cr + 0.000817076911346625 * Y -
  38345. 0.00477271405408747 * k + 1.53380253221734) +
  38346. Y * (0.000961250184130688 * Y - 0.00266257332283933 * k +
  38347. 0.48357088451265) +
  38348. k * (-0.000336197177618394 * k + 0.484791561490776);
  38349. var g = 107.268039397724 +
  38350. Cb * (2.19927104525741e-5 * Cb - 0.000640992018297945 * Cr +
  38351. 0.000659397001245577 * Y + 0.000426105652938837 * k -
  38352. 0.176491792462875) +
  38353. Cr * (-0.000778269941513683 * Cr + 0.00130872261408275 * Y +
  38354. 0.000770482631801132 * k - 0.151051492775562) +
  38355. Y * (0.00126935368114843 * Y - 0.00265090189010898 * k +
  38356. 0.25802910206845) +
  38357. k * (-0.000318913117588328 * k - 0.213742400323665);
  38358. var b = -20.810012546947 +
  38359. Cb * (-0.000570115196973677 * Cb - 2.63409051004589e-5 * Cr +
  38360. 0.0020741088115012 * Y - 0.00288260236853442 * k +
  38361. 0.814272968359295) +
  38362. Cr * (-1.53496057440975e-5 * Cr - 0.000132689043961446 * Y +
  38363. 0.000560833691242812 * k - 0.195152027534049) +
  38364. Y * (0.00174418132927582 * Y - 0.00255243321439347 * k +
  38365. 0.116935020465145) +
  38366. k * (-0.000343531996510555 * k + 0.24165260232407);
  38367. data[offset++] = clamp0to255(r);
  38368. data[offset++] = clamp0to255(g);
  38369. data[offset++] = clamp0to255(b);
  38370. }
  38371. return data;
  38372. },
  38373. _convertYcckToCmyk: function convertYcckToCmyk(data) {
  38374. var Y, Cb, Cr;
  38375. for (var i = 0, length = data.length; i < length; i += 4) {
  38376. Y = data[i];
  38377. Cb = data[i + 1];
  38378. Cr = data[i + 2];
  38379. data[i ] = clamp0to255(434.456 - Y - 1.402 * Cr);
  38380. data[i + 1] = clamp0to255(119.541 - Y + 0.344 * Cb + 0.714 * Cr);
  38381. data[i + 2] = clamp0to255(481.816 - Y - 1.772 * Cb);
  38382. // K in data[i + 3] is unchanged
  38383. }
  38384. return data;
  38385. },
  38386. _convertCmykToRgb: function convertCmykToRgb(data) {
  38387. var c, m, y, k;
  38388. var offset = 0;
  38389. var min = -255 * 255 * 255;
  38390. var scale = 1 / 255 / 255;
  38391. for (var i = 0, length = data.length; i < length; i += 4) {
  38392. c = data[i];
  38393. m = data[i + 1];
  38394. y = data[i + 2];
  38395. k = data[i + 3];
  38396. var r =
  38397. c * (-4.387332384609988 * c + 54.48615194189176 * m +
  38398. 18.82290502165302 * y + 212.25662451639585 * k -
  38399. 72734.4411664936) +
  38400. m * (1.7149763477362134 * m - 5.6096736904047315 * y -
  38401. 17.873870861415444 * k - 1401.7366389350734) +
  38402. y * (-2.5217340131683033 * y - 21.248923337353073 * k +
  38403. 4465.541406466231) -
  38404. k * (21.86122147463605 * k + 48317.86113160301);
  38405. var g =
  38406. c * (8.841041422036149 * c + 60.118027045597366 * m +
  38407. 6.871425592049007 * y + 31.159100130055922 * k -
  38408. 20220.756542821975) +
  38409. m * (-15.310361306967817 * m + 17.575251261109482 * y +
  38410. 131.35250912493976 * k - 48691.05921601825) +
  38411. y * (4.444339102852739 * y + 9.8632861493405 * k -
  38412. 6341.191035517494) -
  38413. k * (20.737325471181034 * k + 47890.15695978492);
  38414. var b =
  38415. c * (0.8842522430003296 * c + 8.078677503112928 * m +
  38416. 30.89978309703729 * y - 0.23883238689178934 * k -
  38417. 3616.812083916688) +
  38418. m * (10.49593273432072 * m + 63.02378494754052 * y +
  38419. 50.606957656360734 * k - 28620.90484698408) +
  38420. y * (0.03296041114873217 * y + 115.60384449646641 * k -
  38421. 49363.43385999684) -
  38422. k * (22.33816807309886 * k + 45932.16563550634);
  38423. data[offset++] = r >= 0 ? 255 : r <= min ? 0 : 255 + r * scale | 0;
  38424. data[offset++] = g >= 0 ? 255 : g <= min ? 0 : 255 + g * scale | 0;
  38425. data[offset++] = b >= 0 ? 255 : b <= min ? 0 : 255 + b * scale | 0;
  38426. }
  38427. return data;
  38428. },
  38429. getData: function getData(width, height, forceRGBoutput) {
  38430. if (this.numComponents > 4) {
  38431. throw 'Unsupported color mode';
  38432. }
  38433. // type of data: Uint8Array(width * height * numComponents)
  38434. var data = this._getLinearizedBlockData(width, height);
  38435. if (this.numComponents === 3) {
  38436. return this._convertYccToRgb(data);
  38437. } else if (this.numComponents === 4) {
  38438. if (this._isColorConversionNeeded()) {
  38439. if (forceRGBoutput) {
  38440. return this._convertYcckToRgb(data);
  38441. } else {
  38442. return this._convertYcckToCmyk(data);
  38443. }
  38444. } else if (forceRGBoutput) {
  38445. return this._convertCmykToRgb(data);
  38446. }
  38447. }
  38448. return data;
  38449. }
  38450. };
  38451. return constructor;
  38452. })();
  38453. var JpxImage = (function JpxImageClosure() {
  38454. // Table E.1
  38455. var SubbandsGainLog2 = {
  38456. 'LL': 0,
  38457. 'LH': 1,
  38458. 'HL': 1,
  38459. 'HH': 2
  38460. };
  38461. function JpxImage() {
  38462. this.failOnCorruptedImage = false;
  38463. }
  38464. JpxImage.prototype = {
  38465. parse: function JpxImage_parse(data) {
  38466. var head = readUint16(data, 0);
  38467. // No box header, immediate start of codestream (SOC)
  38468. if (head === 0xFF4F) {
  38469. this.parseCodestream(data, 0, data.length);
  38470. return;
  38471. }
  38472. var position = 0, length = data.length;
  38473. while (position < length) {
  38474. var headerSize = 8;
  38475. var lbox = readUint32(data, position);
  38476. var tbox = readUint32(data, position + 4);
  38477. position += headerSize;
  38478. if (lbox === 1) {
  38479. // XLBox: read UInt64 according to spec.
  38480. // JavaScript's int precision of 53 bit should be sufficient here.
  38481. lbox = readUint32(data, position) * 4294967296 +
  38482. readUint32(data, position + 4);
  38483. position += 8;
  38484. headerSize += 8;
  38485. }
  38486. if (lbox === 0) {
  38487. lbox = length - position + headerSize;
  38488. }
  38489. if (lbox < headerSize) {
  38490. throw new Error('JPX Error: Invalid box field size');
  38491. }
  38492. var dataLength = lbox - headerSize;
  38493. var jumpDataLength = true;
  38494. switch (tbox) {
  38495. case 0x6A703268: // 'jp2h'
  38496. jumpDataLength = false; // parsing child boxes
  38497. break;
  38498. case 0x636F6C72: // 'colr'
  38499. // Colorspaces are not used, the CS from the PDF is used.
  38500. var method = data[position];
  38501. var precedence = data[position + 1];
  38502. var approximation = data[position + 2];
  38503. if (method === 1) {
  38504. // enumerated colorspace
  38505. var colorspace = readUint32(data, position + 3);
  38506. switch (colorspace) {
  38507. case 16: // this indicates a sRGB colorspace
  38508. case 17: // this indicates a grayscale colorspace
  38509. case 18: // this indicates a YUV colorspace
  38510. break;
  38511. default:
  38512. warn('Unknown colorspace ' + colorspace);
  38513. break;
  38514. }
  38515. } else if (method === 2) {
  38516. info('ICC profile not supported');
  38517. }
  38518. break;
  38519. case 0x6A703263: // 'jp2c'
  38520. this.parseCodestream(data, position, position + dataLength);
  38521. break;
  38522. case 0x6A502020: // 'jP\024\024'
  38523. if (0x0d0a870a !== readUint32(data, position)) {
  38524. warn('Invalid JP2 signature');
  38525. }
  38526. break;
  38527. // The following header types are valid but currently not used:
  38528. case 0x6A501A1A: // 'jP\032\032'
  38529. case 0x66747970: // 'ftyp'
  38530. case 0x72726571: // 'rreq'
  38531. case 0x72657320: // 'res '
  38532. case 0x69686472: // 'ihdr'
  38533. break;
  38534. default:
  38535. var headerType = String.fromCharCode((tbox >> 24) & 0xFF,
  38536. (tbox >> 16) & 0xFF,
  38537. (tbox >> 8) & 0xFF,
  38538. tbox & 0xFF);
  38539. warn('Unsupported header type ' + tbox + ' (' + headerType + ')');
  38540. break;
  38541. }
  38542. if (jumpDataLength) {
  38543. position += dataLength;
  38544. }
  38545. }
  38546. },
  38547. parseImageProperties: function JpxImage_parseImageProperties(stream) {
  38548. var newByte = stream.getByte();
  38549. while (newByte >= 0) {
  38550. var oldByte = newByte;
  38551. newByte = stream.getByte();
  38552. var code = (oldByte << 8) | newByte;
  38553. // Image and tile size (SIZ)
  38554. if (code === 0xFF51) {
  38555. stream.skip(4);
  38556. var Xsiz = stream.getInt32() >>> 0; // Byte 4
  38557. var Ysiz = stream.getInt32() >>> 0; // Byte 8
  38558. var XOsiz = stream.getInt32() >>> 0; // Byte 12
  38559. var YOsiz = stream.getInt32() >>> 0; // Byte 16
  38560. stream.skip(16);
  38561. var Csiz = stream.getUint16(); // Byte 36
  38562. this.width = Xsiz - XOsiz;
  38563. this.height = Ysiz - YOsiz;
  38564. this.componentsCount = Csiz;
  38565. // Results are always returned as Uint8Arrays
  38566. this.bitsPerComponent = 8;
  38567. return;
  38568. }
  38569. }
  38570. throw new Error('JPX Error: No size marker found in JPX stream');
  38571. },
  38572. parseCodestream: function JpxImage_parseCodestream(data, start, end) {
  38573. var context = {};
  38574. try {
  38575. var doNotRecover = false;
  38576. var position = start;
  38577. while (position + 1 < end) {
  38578. var code = readUint16(data, position);
  38579. position += 2;
  38580. var length = 0, j, sqcd, spqcds, spqcdSize, scalarExpounded, tile;
  38581. switch (code) {
  38582. case 0xFF4F: // Start of codestream (SOC)
  38583. context.mainHeader = true;
  38584. break;
  38585. case 0xFFD9: // End of codestream (EOC)
  38586. break;
  38587. case 0xFF51: // Image and tile size (SIZ)
  38588. length = readUint16(data, position);
  38589. var siz = {};
  38590. siz.Xsiz = readUint32(data, position + 4);
  38591. siz.Ysiz = readUint32(data, position + 8);
  38592. siz.XOsiz = readUint32(data, position + 12);
  38593. siz.YOsiz = readUint32(data, position + 16);
  38594. siz.XTsiz = readUint32(data, position + 20);
  38595. siz.YTsiz = readUint32(data, position + 24);
  38596. siz.XTOsiz = readUint32(data, position + 28);
  38597. siz.YTOsiz = readUint32(data, position + 32);
  38598. var componentsCount = readUint16(data, position + 36);
  38599. siz.Csiz = componentsCount;
  38600. var components = [];
  38601. j = position + 38;
  38602. for (var i = 0; i < componentsCount; i++) {
  38603. var component = {
  38604. precision: (data[j] & 0x7F) + 1,
  38605. isSigned: !!(data[j] & 0x80),
  38606. XRsiz: data[j + 1],
  38607. YRsiz: data[j + 1]
  38608. };
  38609. calculateComponentDimensions(component, siz);
  38610. components.push(component);
  38611. }
  38612. context.SIZ = siz;
  38613. context.components = components;
  38614. calculateTileGrids(context, components);
  38615. context.QCC = [];
  38616. context.COC = [];
  38617. break;
  38618. case 0xFF55: // Tile-part lengths, main header (TLM)
  38619. var Ltlm = readUint16(data, position); // Marker segment length
  38620. // Skip tile length markers
  38621. position += Ltlm;
  38622. break;
  38623. case 0xFF5C: // Quantization default (QCD)
  38624. length = readUint16(data, position);
  38625. var qcd = {};
  38626. j = position + 2;
  38627. sqcd = data[j++];
  38628. switch (sqcd & 0x1F) {
  38629. case 0:
  38630. spqcdSize = 8;
  38631. scalarExpounded = true;
  38632. break;
  38633. case 1:
  38634. spqcdSize = 16;
  38635. scalarExpounded = false;
  38636. break;
  38637. case 2:
  38638. spqcdSize = 16;
  38639. scalarExpounded = true;
  38640. break;
  38641. default:
  38642. throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
  38643. }
  38644. qcd.noQuantization = (spqcdSize === 8);
  38645. qcd.scalarExpounded = scalarExpounded;
  38646. qcd.guardBits = sqcd >> 5;
  38647. spqcds = [];
  38648. while (j < length + position) {
  38649. var spqcd = {};
  38650. if (spqcdSize === 8) {
  38651. spqcd.epsilon = data[j++] >> 3;
  38652. spqcd.mu = 0;
  38653. } else {
  38654. spqcd.epsilon = data[j] >> 3;
  38655. spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
  38656. j += 2;
  38657. }
  38658. spqcds.push(spqcd);
  38659. }
  38660. qcd.SPqcds = spqcds;
  38661. if (context.mainHeader) {
  38662. context.QCD = qcd;
  38663. } else {
  38664. context.currentTile.QCD = qcd;
  38665. context.currentTile.QCC = [];
  38666. }
  38667. break;
  38668. case 0xFF5D: // Quantization component (QCC)
  38669. length = readUint16(data, position);
  38670. var qcc = {};
  38671. j = position + 2;
  38672. var cqcc;
  38673. if (context.SIZ.Csiz < 257) {
  38674. cqcc = data[j++];
  38675. } else {
  38676. cqcc = readUint16(data, j);
  38677. j += 2;
  38678. }
  38679. sqcd = data[j++];
  38680. switch (sqcd & 0x1F) {
  38681. case 0:
  38682. spqcdSize = 8;
  38683. scalarExpounded = true;
  38684. break;
  38685. case 1:
  38686. spqcdSize = 16;
  38687. scalarExpounded = false;
  38688. break;
  38689. case 2:
  38690. spqcdSize = 16;
  38691. scalarExpounded = true;
  38692. break;
  38693. default:
  38694. throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
  38695. }
  38696. qcc.noQuantization = (spqcdSize === 8);
  38697. qcc.scalarExpounded = scalarExpounded;
  38698. qcc.guardBits = sqcd >> 5;
  38699. spqcds = [];
  38700. while (j < (length + position)) {
  38701. spqcd = {};
  38702. if (spqcdSize === 8) {
  38703. spqcd.epsilon = data[j++] >> 3;
  38704. spqcd.mu = 0;
  38705. } else {
  38706. spqcd.epsilon = data[j] >> 3;
  38707. spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
  38708. j += 2;
  38709. }
  38710. spqcds.push(spqcd);
  38711. }
  38712. qcc.SPqcds = spqcds;
  38713. if (context.mainHeader) {
  38714. context.QCC[cqcc] = qcc;
  38715. } else {
  38716. context.currentTile.QCC[cqcc] = qcc;
  38717. }
  38718. break;
  38719. case 0xFF52: // Coding style default (COD)
  38720. length = readUint16(data, position);
  38721. var cod = {};
  38722. j = position + 2;
  38723. var scod = data[j++];
  38724. cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
  38725. cod.sopMarkerUsed = !!(scod & 2);
  38726. cod.ephMarkerUsed = !!(scod & 4);
  38727. cod.progressionOrder = data[j++];
  38728. cod.layersCount = readUint16(data, j);
  38729. j += 2;
  38730. cod.multipleComponentTransform = data[j++];
  38731. cod.decompositionLevelsCount = data[j++];
  38732. cod.xcb = (data[j++] & 0xF) + 2;
  38733. cod.ycb = (data[j++] & 0xF) + 2;
  38734. var blockStyle = data[j++];
  38735. cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
  38736. cod.resetContextProbabilities = !!(blockStyle & 2);
  38737. cod.terminationOnEachCodingPass = !!(blockStyle & 4);
  38738. cod.verticalyStripe = !!(blockStyle & 8);
  38739. cod.predictableTermination = !!(blockStyle & 16);
  38740. cod.segmentationSymbolUsed = !!(blockStyle & 32);
  38741. cod.reversibleTransformation = data[j++];
  38742. if (cod.entropyCoderWithCustomPrecincts) {
  38743. var precinctsSizes = [];
  38744. while (j < length + position) {
  38745. var precinctsSize = data[j++];
  38746. precinctsSizes.push({
  38747. PPx: precinctsSize & 0xF,
  38748. PPy: precinctsSize >> 4
  38749. });
  38750. }
  38751. cod.precinctsSizes = precinctsSizes;
  38752. }
  38753. var unsupported = [];
  38754. if (cod.selectiveArithmeticCodingBypass) {
  38755. unsupported.push('selectiveArithmeticCodingBypass');
  38756. }
  38757. if (cod.resetContextProbabilities) {
  38758. unsupported.push('resetContextProbabilities');
  38759. }
  38760. if (cod.terminationOnEachCodingPass) {
  38761. unsupported.push('terminationOnEachCodingPass');
  38762. }
  38763. if (cod.verticalyStripe) {
  38764. unsupported.push('verticalyStripe');
  38765. }
  38766. if (cod.predictableTermination) {
  38767. unsupported.push('predictableTermination');
  38768. }
  38769. if (unsupported.length > 0) {
  38770. doNotRecover = true;
  38771. throw new Error('JPX Error: Unsupported COD options (' +
  38772. unsupported.join(', ') + ')');
  38773. }
  38774. if (context.mainHeader) {
  38775. context.COD = cod;
  38776. } else {
  38777. context.currentTile.COD = cod;
  38778. context.currentTile.COC = [];
  38779. }
  38780. break;
  38781. case 0xFF90: // Start of tile-part (SOT)
  38782. length = readUint16(data, position);
  38783. tile = {};
  38784. tile.index = readUint16(data, position + 2);
  38785. tile.length = readUint32(data, position + 4);
  38786. tile.dataEnd = tile.length + position - 2;
  38787. tile.partIndex = data[position + 8];
  38788. tile.partsCount = data[position + 9];
  38789. context.mainHeader = false;
  38790. if (tile.partIndex === 0) {
  38791. // reset component specific settings
  38792. tile.COD = context.COD;
  38793. tile.COC = context.COC.slice(0); // clone of the global COC
  38794. tile.QCD = context.QCD;
  38795. tile.QCC = context.QCC.slice(0); // clone of the global COC
  38796. }
  38797. context.currentTile = tile;
  38798. break;
  38799. case 0xFF93: // Start of data (SOD)
  38800. tile = context.currentTile;
  38801. if (tile.partIndex === 0) {
  38802. initializeTile(context, tile.index);
  38803. buildPackets(context);
  38804. }
  38805. // moving to the end of the data
  38806. length = tile.dataEnd - position;
  38807. parseTilePackets(context, data, position, length);
  38808. break;
  38809. case 0xFF64: // Comment (COM)
  38810. length = readUint16(data, position);
  38811. // skipping content
  38812. break;
  38813. case 0xFF53: // Coding style component (COC)
  38814. throw new Error('JPX Error: Codestream code 0xFF53 (COC) is ' +
  38815. 'not implemented');
  38816. default:
  38817. throw new Error('JPX Error: Unknown codestream code: ' +
  38818. code.toString(16));
  38819. }
  38820. position += length;
  38821. }
  38822. } catch (e) {
  38823. if (doNotRecover || this.failOnCorruptedImage) {
  38824. throw e;
  38825. } else {
  38826. warn('Trying to recover from ' + e.message);
  38827. }
  38828. }
  38829. this.tiles = transformComponents(context);
  38830. this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
  38831. this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
  38832. this.componentsCount = context.SIZ.Csiz;
  38833. }
  38834. };
  38835. function calculateComponentDimensions(component, siz) {
  38836. // Section B.2 Component mapping
  38837. component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
  38838. component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
  38839. component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
  38840. component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
  38841. component.width = component.x1 - component.x0;
  38842. component.height = component.y1 - component.y0;
  38843. }
  38844. function calculateTileGrids(context, components) {
  38845. var siz = context.SIZ;
  38846. // Section B.3 Division into tile and tile-components
  38847. var tile, tiles = [];
  38848. var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
  38849. var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
  38850. for (var q = 0; q < numYtiles; q++) {
  38851. for (var p = 0; p < numXtiles; p++) {
  38852. tile = {};
  38853. tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
  38854. tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
  38855. tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
  38856. tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
  38857. tile.width = tile.tx1 - tile.tx0;
  38858. tile.height = tile.ty1 - tile.ty0;
  38859. tile.components = [];
  38860. tiles.push(tile);
  38861. }
  38862. }
  38863. context.tiles = tiles;
  38864. var componentsCount = siz.Csiz;
  38865. for (var i = 0, ii = componentsCount; i < ii; i++) {
  38866. var component = components[i];
  38867. for (var j = 0, jj = tiles.length; j < jj; j++) {
  38868. var tileComponent = {};
  38869. tile = tiles[j];
  38870. tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
  38871. tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
  38872. tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
  38873. tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
  38874. tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
  38875. tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
  38876. tile.components[i] = tileComponent;
  38877. }
  38878. }
  38879. }
  38880. function getBlocksDimensions(context, component, r) {
  38881. var codOrCoc = component.codingStyleParameters;
  38882. var result = {};
  38883. if (!codOrCoc.entropyCoderWithCustomPrecincts) {
  38884. result.PPx = 15;
  38885. result.PPy = 15;
  38886. } else {
  38887. result.PPx = codOrCoc.precinctsSizes[r].PPx;
  38888. result.PPy = codOrCoc.precinctsSizes[r].PPy;
  38889. }
  38890. // calculate codeblock size as described in section B.7
  38891. result.xcb_ = (r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) :
  38892. Math.min(codOrCoc.xcb, result.PPx));
  38893. result.ycb_ = (r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) :
  38894. Math.min(codOrCoc.ycb, result.PPy));
  38895. return result;
  38896. }
  38897. function buildPrecincts(context, resolution, dimensions) {
  38898. // Section B.6 Division resolution to precincts
  38899. var precinctWidth = 1 << dimensions.PPx;
  38900. var precinctHeight = 1 << dimensions.PPy;
  38901. // Jasper introduces codeblock groups for mapping each subband codeblocks
  38902. // to precincts. Precinct partition divides a resolution according to width
  38903. // and height parameters. The subband that belongs to the resolution level
  38904. // has a different size than the level, unless it is the zero resolution.
  38905. // From Jasper documentation: jpeg2000.pdf, section K: Tier-2 coding:
  38906. // The precinct partitioning for a particular subband is derived from a
  38907. // partitioning of its parent LL band (i.e., the LL band at the next higher
  38908. // resolution level)... The LL band associated with each resolution level is
  38909. // divided into precincts... Each of the resulting precinct regions is then
  38910. // mapped into its child subbands (if any) at the next lower resolution
  38911. // level. This is accomplished by using the coordinate transformation
  38912. // (u, v) = (ceil(x/2), ceil(y/2)) where (x, y) and (u, v) are the
  38913. // coordinates of a point in the LL band and child subband, respectively.
  38914. var isZeroRes = resolution.resLevel === 0;
  38915. var precinctWidthInSubband = 1 << (dimensions.PPx + (isZeroRes ? 0 : -1));
  38916. var precinctHeightInSubband = 1 << (dimensions.PPy + (isZeroRes ? 0 : -1));
  38917. var numprecinctswide = (resolution.trx1 > resolution.trx0 ?
  38918. Math.ceil(resolution.trx1 / precinctWidth) -
  38919. Math.floor(resolution.trx0 / precinctWidth) : 0);
  38920. var numprecinctshigh = (resolution.try1 > resolution.try0 ?
  38921. Math.ceil(resolution.try1 / precinctHeight) -
  38922. Math.floor(resolution.try0 / precinctHeight) : 0);
  38923. var numprecincts = numprecinctswide * numprecinctshigh;
  38924. resolution.precinctParameters = {
  38925. precinctWidth: precinctWidth,
  38926. precinctHeight: precinctHeight,
  38927. numprecinctswide: numprecinctswide,
  38928. numprecinctshigh: numprecinctshigh,
  38929. numprecincts: numprecincts,
  38930. precinctWidthInSubband: precinctWidthInSubband,
  38931. precinctHeightInSubband: precinctHeightInSubband
  38932. };
  38933. }
  38934. function buildCodeblocks(context, subband, dimensions) {
  38935. // Section B.7 Division sub-band into code-blocks
  38936. var xcb_ = dimensions.xcb_;
  38937. var ycb_ = dimensions.ycb_;
  38938. var codeblockWidth = 1 << xcb_;
  38939. var codeblockHeight = 1 << ycb_;
  38940. var cbx0 = subband.tbx0 >> xcb_;
  38941. var cby0 = subband.tby0 >> ycb_;
  38942. var cbx1 = (subband.tbx1 + codeblockWidth - 1) >> xcb_;
  38943. var cby1 = (subband.tby1 + codeblockHeight - 1) >> ycb_;
  38944. var precinctParameters = subband.resolution.precinctParameters;
  38945. var codeblocks = [];
  38946. var precincts = [];
  38947. var i, j, codeblock, precinctNumber;
  38948. for (j = cby0; j < cby1; j++) {
  38949. for (i = cbx0; i < cbx1; i++) {
  38950. codeblock = {
  38951. cbx: i,
  38952. cby: j,
  38953. tbx0: codeblockWidth * i,
  38954. tby0: codeblockHeight * j,
  38955. tbx1: codeblockWidth * (i + 1),
  38956. tby1: codeblockHeight * (j + 1)
  38957. };
  38958. codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
  38959. codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
  38960. codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
  38961. codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
  38962. // Calculate precinct number for this codeblock, codeblock position
  38963. // should be relative to its subband, use actual dimension and position
  38964. // See comment about codeblock group width and height
  38965. var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) /
  38966. precinctParameters.precinctWidthInSubband);
  38967. var pj = Math.floor((codeblock.tby0_ - subband.tby0) /
  38968. precinctParameters.precinctHeightInSubband);
  38969. precinctNumber = pi + (pj * precinctParameters.numprecinctswide);
  38970. codeblock.precinctNumber = precinctNumber;
  38971. codeblock.subbandType = subband.type;
  38972. codeblock.Lblock = 3;
  38973. if (codeblock.tbx1_ <= codeblock.tbx0_ ||
  38974. codeblock.tby1_ <= codeblock.tby0_) {
  38975. continue;
  38976. }
  38977. codeblocks.push(codeblock);
  38978. // building precinct for the sub-band
  38979. var precinct = precincts[precinctNumber];
  38980. if (precinct !== undefined) {
  38981. if (i < precinct.cbxMin) {
  38982. precinct.cbxMin = i;
  38983. } else if (i > precinct.cbxMax) {
  38984. precinct.cbxMax = i;
  38985. }
  38986. if (j < precinct.cbyMin) {
  38987. precinct.cbxMin = j;
  38988. } else if (j > precinct.cbyMax) {
  38989. precinct.cbyMax = j;
  38990. }
  38991. } else {
  38992. precincts[precinctNumber] = precinct = {
  38993. cbxMin: i,
  38994. cbyMin: j,
  38995. cbxMax: i,
  38996. cbyMax: j
  38997. };
  38998. }
  38999. codeblock.precinct = precinct;
  39000. }
  39001. }
  39002. subband.codeblockParameters = {
  39003. codeblockWidth: xcb_,
  39004. codeblockHeight: ycb_,
  39005. numcodeblockwide: cbx1 - cbx0 + 1,
  39006. numcodeblockhigh: cby1 - cby0 + 1
  39007. };
  39008. subband.codeblocks = codeblocks;
  39009. subband.precincts = precincts;
  39010. }
  39011. function createPacket(resolution, precinctNumber, layerNumber) {
  39012. var precinctCodeblocks = [];
  39013. // Section B.10.8 Order of info in packet
  39014. var subbands = resolution.subbands;
  39015. // sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence
  39016. for (var i = 0, ii = subbands.length; i < ii; i++) {
  39017. var subband = subbands[i];
  39018. var codeblocks = subband.codeblocks;
  39019. for (var j = 0, jj = codeblocks.length; j < jj; j++) {
  39020. var codeblock = codeblocks[j];
  39021. if (codeblock.precinctNumber !== precinctNumber) {
  39022. continue;
  39023. }
  39024. precinctCodeblocks.push(codeblock);
  39025. }
  39026. }
  39027. return {
  39028. layerNumber: layerNumber,
  39029. codeblocks: precinctCodeblocks
  39030. };
  39031. }
  39032. function LayerResolutionComponentPositionIterator(context) {
  39033. var siz = context.SIZ;
  39034. var tileIndex = context.currentTile.index;
  39035. var tile = context.tiles[tileIndex];
  39036. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39037. var componentsCount = siz.Csiz;
  39038. var maxDecompositionLevelsCount = 0;
  39039. for (var q = 0; q < componentsCount; q++) {
  39040. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39041. tile.components[q].codingStyleParameters.decompositionLevelsCount);
  39042. }
  39043. var l = 0, r = 0, i = 0, k = 0;
  39044. this.nextPacket = function JpxImage_nextPacket() {
  39045. // Section B.12.1.1 Layer-resolution-component-position
  39046. for (; l < layersCount; l++) {
  39047. for (; r <= maxDecompositionLevelsCount; r++) {
  39048. for (; i < componentsCount; i++) {
  39049. var component = tile.components[i];
  39050. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39051. continue;
  39052. }
  39053. var resolution = component.resolutions[r];
  39054. var numprecincts = resolution.precinctParameters.numprecincts;
  39055. for (; k < numprecincts;) {
  39056. var packet = createPacket(resolution, k, l);
  39057. k++;
  39058. return packet;
  39059. }
  39060. k = 0;
  39061. }
  39062. i = 0;
  39063. }
  39064. r = 0;
  39065. }
  39066. throw new Error('JPX Error: Out of packets');
  39067. };
  39068. }
  39069. function ResolutionLayerComponentPositionIterator(context) {
  39070. var siz = context.SIZ;
  39071. var tileIndex = context.currentTile.index;
  39072. var tile = context.tiles[tileIndex];
  39073. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39074. var componentsCount = siz.Csiz;
  39075. var maxDecompositionLevelsCount = 0;
  39076. for (var q = 0; q < componentsCount; q++) {
  39077. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39078. tile.components[q].codingStyleParameters.decompositionLevelsCount);
  39079. }
  39080. var r = 0, l = 0, i = 0, k = 0;
  39081. this.nextPacket = function JpxImage_nextPacket() {
  39082. // Section B.12.1.2 Resolution-layer-component-position
  39083. for (; r <= maxDecompositionLevelsCount; r++) {
  39084. for (; l < layersCount; l++) {
  39085. for (; i < componentsCount; i++) {
  39086. var component = tile.components[i];
  39087. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39088. continue;
  39089. }
  39090. var resolution = component.resolutions[r];
  39091. var numprecincts = resolution.precinctParameters.numprecincts;
  39092. for (; k < numprecincts;) {
  39093. var packet = createPacket(resolution, k, l);
  39094. k++;
  39095. return packet;
  39096. }
  39097. k = 0;
  39098. }
  39099. i = 0;
  39100. }
  39101. l = 0;
  39102. }
  39103. throw new Error('JPX Error: Out of packets');
  39104. };
  39105. }
  39106. function ResolutionPositionComponentLayerIterator(context) {
  39107. var siz = context.SIZ;
  39108. var tileIndex = context.currentTile.index;
  39109. var tile = context.tiles[tileIndex];
  39110. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39111. var componentsCount = siz.Csiz;
  39112. var l, r, c, p;
  39113. var maxDecompositionLevelsCount = 0;
  39114. for (c = 0; c < componentsCount; c++) {
  39115. var component = tile.components[c];
  39116. maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
  39117. component.codingStyleParameters.decompositionLevelsCount);
  39118. }
  39119. var maxNumPrecinctsInLevel = new Int32Array(
  39120. maxDecompositionLevelsCount + 1);
  39121. for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
  39122. var maxNumPrecincts = 0;
  39123. for (c = 0; c < componentsCount; ++c) {
  39124. var resolutions = tile.components[c].resolutions;
  39125. if (r < resolutions.length) {
  39126. maxNumPrecincts = Math.max(maxNumPrecincts,
  39127. resolutions[r].precinctParameters.numprecincts);
  39128. }
  39129. }
  39130. maxNumPrecinctsInLevel[r] = maxNumPrecincts;
  39131. }
  39132. l = 0;
  39133. r = 0;
  39134. c = 0;
  39135. p = 0;
  39136. this.nextPacket = function JpxImage_nextPacket() {
  39137. // Section B.12.1.3 Resolution-position-component-layer
  39138. for (; r <= maxDecompositionLevelsCount; r++) {
  39139. for (; p < maxNumPrecinctsInLevel[r]; p++) {
  39140. for (; c < componentsCount; c++) {
  39141. var component = tile.components[c];
  39142. if (r > component.codingStyleParameters.decompositionLevelsCount) {
  39143. continue;
  39144. }
  39145. var resolution = component.resolutions[r];
  39146. var numprecincts = resolution.precinctParameters.numprecincts;
  39147. if (p >= numprecincts) {
  39148. continue;
  39149. }
  39150. for (; l < layersCount;) {
  39151. var packet = createPacket(resolution, p, l);
  39152. l++;
  39153. return packet;
  39154. }
  39155. l = 0;
  39156. }
  39157. c = 0;
  39158. }
  39159. p = 0;
  39160. }
  39161. throw new Error('JPX Error: Out of packets');
  39162. };
  39163. }
  39164. function PositionComponentResolutionLayerIterator(context) {
  39165. var siz = context.SIZ;
  39166. var tileIndex = context.currentTile.index;
  39167. var tile = context.tiles[tileIndex];
  39168. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39169. var componentsCount = siz.Csiz;
  39170. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  39171. var precinctsIterationSizes = precinctsSizes;
  39172. var l = 0, r = 0, c = 0, px = 0, py = 0;
  39173. this.nextPacket = function JpxImage_nextPacket() {
  39174. // Section B.12.1.4 Position-component-resolution-layer
  39175. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  39176. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  39177. for (; c < componentsCount; c++) {
  39178. var component = tile.components[c];
  39179. var decompositionLevelsCount =
  39180. component.codingStyleParameters.decompositionLevelsCount;
  39181. for (; r <= decompositionLevelsCount; r++) {
  39182. var resolution = component.resolutions[r];
  39183. var sizeInImageScale =
  39184. precinctsSizes.components[c].resolutions[r];
  39185. var k = getPrecinctIndexIfExist(
  39186. px,
  39187. py,
  39188. sizeInImageScale,
  39189. precinctsIterationSizes,
  39190. resolution);
  39191. if (k === null) {
  39192. continue;
  39193. }
  39194. for (; l < layersCount;) {
  39195. var packet = createPacket(resolution, k, l);
  39196. l++;
  39197. return packet;
  39198. }
  39199. l = 0;
  39200. }
  39201. r = 0;
  39202. }
  39203. c = 0;
  39204. }
  39205. px = 0;
  39206. }
  39207. throw new Error('JPX Error: Out of packets');
  39208. };
  39209. }
  39210. function ComponentPositionResolutionLayerIterator(context) {
  39211. var siz = context.SIZ;
  39212. var tileIndex = context.currentTile.index;
  39213. var tile = context.tiles[tileIndex];
  39214. var layersCount = tile.codingStyleDefaultParameters.layersCount;
  39215. var componentsCount = siz.Csiz;
  39216. var precinctsSizes = getPrecinctSizesInImageScale(tile);
  39217. var l = 0, r = 0, c = 0, px = 0, py = 0;
  39218. this.nextPacket = function JpxImage_nextPacket() {
  39219. // Section B.12.1.5 Component-position-resolution-layer
  39220. for (; c < componentsCount; ++c) {
  39221. var component = tile.components[c];
  39222. var precinctsIterationSizes = precinctsSizes.components[c];
  39223. var decompositionLevelsCount =
  39224. component.codingStyleParameters.decompositionLevelsCount;
  39225. for (; py < precinctsIterationSizes.maxNumHigh; py++) {
  39226. for (; px < precinctsIterationSizes.maxNumWide; px++) {
  39227. for (; r <= decompositionLevelsCount; r++) {
  39228. var resolution = component.resolutions[r];
  39229. var sizeInImageScale = precinctsIterationSizes.resolutions[r];
  39230. var k = getPrecinctIndexIfExist(
  39231. px,
  39232. py,
  39233. sizeInImageScale,
  39234. precinctsIterationSizes,
  39235. resolution);
  39236. if (k === null) {
  39237. continue;
  39238. }
  39239. for (; l < layersCount;) {
  39240. var packet = createPacket(resolution, k, l);
  39241. l++;
  39242. return packet;
  39243. }
  39244. l = 0;
  39245. }
  39246. r = 0;
  39247. }
  39248. px = 0;
  39249. }
  39250. py = 0;
  39251. }
  39252. throw new Error('JPX Error: Out of packets');
  39253. };
  39254. }
  39255. function getPrecinctIndexIfExist(
  39256. pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
  39257. var posX = pxIndex * precinctIterationSizes.minWidth;
  39258. var posY = pyIndex * precinctIterationSizes.minHeight;
  39259. if (posX % sizeInImageScale.width !== 0 ||
  39260. posY % sizeInImageScale.height !== 0) {
  39261. return null;
  39262. }
  39263. var startPrecinctRowIndex =
  39264. (posY / sizeInImageScale.width) *
  39265. resolution.precinctParameters.numprecinctswide;
  39266. return (posX / sizeInImageScale.height) + startPrecinctRowIndex;
  39267. }
  39268. function getPrecinctSizesInImageScale(tile) {
  39269. var componentsCount = tile.components.length;
  39270. var minWidth = Number.MAX_VALUE;
  39271. var minHeight = Number.MAX_VALUE;
  39272. var maxNumWide = 0;
  39273. var maxNumHigh = 0;
  39274. var sizePerComponent = new Array(componentsCount);
  39275. for (var c = 0; c < componentsCount; c++) {
  39276. var component = tile.components[c];
  39277. var decompositionLevelsCount =
  39278. component.codingStyleParameters.decompositionLevelsCount;
  39279. var sizePerResolution = new Array(decompositionLevelsCount + 1);
  39280. var minWidthCurrentComponent = Number.MAX_VALUE;
  39281. var minHeightCurrentComponent = Number.MAX_VALUE;
  39282. var maxNumWideCurrentComponent = 0;
  39283. var maxNumHighCurrentComponent = 0;
  39284. var scale = 1;
  39285. for (var r = decompositionLevelsCount; r >= 0; --r) {
  39286. var resolution = component.resolutions[r];
  39287. var widthCurrentResolution =
  39288. scale * resolution.precinctParameters.precinctWidth;
  39289. var heightCurrentResolution =
  39290. scale * resolution.precinctParameters.precinctHeight;
  39291. minWidthCurrentComponent = Math.min(
  39292. minWidthCurrentComponent,
  39293. widthCurrentResolution);
  39294. minHeightCurrentComponent = Math.min(
  39295. minHeightCurrentComponent,
  39296. heightCurrentResolution);
  39297. maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent,
  39298. resolution.precinctParameters.numprecinctswide);
  39299. maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent,
  39300. resolution.precinctParameters.numprecinctshigh);
  39301. sizePerResolution[r] = {
  39302. width: widthCurrentResolution,
  39303. height: heightCurrentResolution
  39304. };
  39305. scale <<= 1;
  39306. }
  39307. minWidth = Math.min(minWidth, minWidthCurrentComponent);
  39308. minHeight = Math.min(minHeight, minHeightCurrentComponent);
  39309. maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
  39310. maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
  39311. sizePerComponent[c] = {
  39312. resolutions: sizePerResolution,
  39313. minWidth: minWidthCurrentComponent,
  39314. minHeight: minHeightCurrentComponent,
  39315. maxNumWide: maxNumWideCurrentComponent,
  39316. maxNumHigh: maxNumHighCurrentComponent
  39317. };
  39318. }
  39319. return {
  39320. components: sizePerComponent,
  39321. minWidth: minWidth,
  39322. minHeight: minHeight,
  39323. maxNumWide: maxNumWide,
  39324. maxNumHigh: maxNumHigh
  39325. };
  39326. }
  39327. function buildPackets(context) {
  39328. var siz = context.SIZ;
  39329. var tileIndex = context.currentTile.index;
  39330. var tile = context.tiles[tileIndex];
  39331. var componentsCount = siz.Csiz;
  39332. // Creating resolutions and sub-bands for each component
  39333. for (var c = 0; c < componentsCount; c++) {
  39334. var component = tile.components[c];
  39335. var decompositionLevelsCount =
  39336. component.codingStyleParameters.decompositionLevelsCount;
  39337. // Section B.5 Resolution levels and sub-bands
  39338. var resolutions = [];
  39339. var subbands = [];
  39340. for (var r = 0; r <= decompositionLevelsCount; r++) {
  39341. var blocksDimensions = getBlocksDimensions(context, component, r);
  39342. var resolution = {};
  39343. var scale = 1 << (decompositionLevelsCount - r);
  39344. resolution.trx0 = Math.ceil(component.tcx0 / scale);
  39345. resolution.try0 = Math.ceil(component.tcy0 / scale);
  39346. resolution.trx1 = Math.ceil(component.tcx1 / scale);
  39347. resolution.try1 = Math.ceil(component.tcy1 / scale);
  39348. resolution.resLevel = r;
  39349. buildPrecincts(context, resolution, blocksDimensions);
  39350. resolutions.push(resolution);
  39351. var subband;
  39352. if (r === 0) {
  39353. // one sub-band (LL) with last decomposition
  39354. subband = {};
  39355. subband.type = 'LL';
  39356. subband.tbx0 = Math.ceil(component.tcx0 / scale);
  39357. subband.tby0 = Math.ceil(component.tcy0 / scale);
  39358. subband.tbx1 = Math.ceil(component.tcx1 / scale);
  39359. subband.tby1 = Math.ceil(component.tcy1 / scale);
  39360. subband.resolution = resolution;
  39361. buildCodeblocks(context, subband, blocksDimensions);
  39362. subbands.push(subband);
  39363. resolution.subbands = [subband];
  39364. } else {
  39365. var bscale = 1 << (decompositionLevelsCount - r + 1);
  39366. var resolutionSubbands = [];
  39367. // three sub-bands (HL, LH and HH) with rest of decompositions
  39368. subband = {};
  39369. subband.type = 'HL';
  39370. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  39371. subband.tby0 = Math.ceil(component.tcy0 / bscale);
  39372. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  39373. subband.tby1 = Math.ceil(component.tcy1 / bscale);
  39374. subband.resolution = resolution;
  39375. buildCodeblocks(context, subband, blocksDimensions);
  39376. subbands.push(subband);
  39377. resolutionSubbands.push(subband);
  39378. subband = {};
  39379. subband.type = 'LH';
  39380. subband.tbx0 = Math.ceil(component.tcx0 / bscale);
  39381. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  39382. subband.tbx1 = Math.ceil(component.tcx1 / bscale);
  39383. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  39384. subband.resolution = resolution;
  39385. buildCodeblocks(context, subband, blocksDimensions);
  39386. subbands.push(subband);
  39387. resolutionSubbands.push(subband);
  39388. subband = {};
  39389. subband.type = 'HH';
  39390. subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
  39391. subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
  39392. subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
  39393. subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
  39394. subband.resolution = resolution;
  39395. buildCodeblocks(context, subband, blocksDimensions);
  39396. subbands.push(subband);
  39397. resolutionSubbands.push(subband);
  39398. resolution.subbands = resolutionSubbands;
  39399. }
  39400. }
  39401. component.resolutions = resolutions;
  39402. component.subbands = subbands;
  39403. }
  39404. // Generate the packets sequence
  39405. var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
  39406. switch (progressionOrder) {
  39407. case 0:
  39408. tile.packetsIterator =
  39409. new LayerResolutionComponentPositionIterator(context);
  39410. break;
  39411. case 1:
  39412. tile.packetsIterator =
  39413. new ResolutionLayerComponentPositionIterator(context);
  39414. break;
  39415. case 2:
  39416. tile.packetsIterator =
  39417. new ResolutionPositionComponentLayerIterator(context);
  39418. break;
  39419. case 3:
  39420. tile.packetsIterator =
  39421. new PositionComponentResolutionLayerIterator(context);
  39422. break;
  39423. case 4:
  39424. tile.packetsIterator =
  39425. new ComponentPositionResolutionLayerIterator(context);
  39426. break;
  39427. default:
  39428. throw new Error('JPX Error: Unsupported progression order ' +
  39429. progressionOrder);
  39430. }
  39431. }
  39432. function parseTilePackets(context, data, offset, dataLength) {
  39433. var position = 0;
  39434. var buffer, bufferSize = 0, skipNextBit = false;
  39435. function readBits(count) {
  39436. while (bufferSize < count) {
  39437. var b = data[offset + position];
  39438. position++;
  39439. if (skipNextBit) {
  39440. buffer = (buffer << 7) | b;
  39441. bufferSize += 7;
  39442. skipNextBit = false;
  39443. } else {
  39444. buffer = (buffer << 8) | b;
  39445. bufferSize += 8;
  39446. }
  39447. if (b === 0xFF) {
  39448. skipNextBit = true;
  39449. }
  39450. }
  39451. bufferSize -= count;
  39452. return (buffer >>> bufferSize) & ((1 << count) - 1);
  39453. }
  39454. function skipMarkerIfEqual(value) {
  39455. if (data[offset + position - 1] === 0xFF &&
  39456. data[offset + position] === value) {
  39457. skipBytes(1);
  39458. return true;
  39459. } else if (data[offset + position] === 0xFF &&
  39460. data[offset + position + 1] === value) {
  39461. skipBytes(2);
  39462. return true;
  39463. }
  39464. return false;
  39465. }
  39466. function skipBytes(count) {
  39467. position += count;
  39468. }
  39469. function alignToByte() {
  39470. bufferSize = 0;
  39471. if (skipNextBit) {
  39472. position++;
  39473. skipNextBit = false;
  39474. }
  39475. }
  39476. function readCodingpasses() {
  39477. if (readBits(1) === 0) {
  39478. return 1;
  39479. }
  39480. if (readBits(1) === 0) {
  39481. return 2;
  39482. }
  39483. var value = readBits(2);
  39484. if (value < 3) {
  39485. return value + 3;
  39486. }
  39487. value = readBits(5);
  39488. if (value < 31) {
  39489. return value + 6;
  39490. }
  39491. value = readBits(7);
  39492. return value + 37;
  39493. }
  39494. var tileIndex = context.currentTile.index;
  39495. var tile = context.tiles[tileIndex];
  39496. var sopMarkerUsed = context.COD.sopMarkerUsed;
  39497. var ephMarkerUsed = context.COD.ephMarkerUsed;
  39498. var packetsIterator = tile.packetsIterator;
  39499. while (position < dataLength) {
  39500. alignToByte();
  39501. if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
  39502. // Skip also marker segment length and packet sequence ID
  39503. skipBytes(4);
  39504. }
  39505. var packet = packetsIterator.nextPacket();
  39506. if (!readBits(1)) {
  39507. continue;
  39508. }
  39509. var layerNumber = packet.layerNumber;
  39510. var queue = [], codeblock;
  39511. for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
  39512. codeblock = packet.codeblocks[i];
  39513. var precinct = codeblock.precinct;
  39514. var codeblockColumn = codeblock.cbx - precinct.cbxMin;
  39515. var codeblockRow = codeblock.cby - precinct.cbyMin;
  39516. var codeblockIncluded = false;
  39517. var firstTimeInclusion = false;
  39518. var valueReady;
  39519. if (codeblock['included'] !== undefined) {
  39520. codeblockIncluded = !!readBits(1);
  39521. } else {
  39522. // reading inclusion tree
  39523. precinct = codeblock.precinct;
  39524. var inclusionTree, zeroBitPlanesTree;
  39525. if (precinct['inclusionTree'] !== undefined) {
  39526. inclusionTree = precinct.inclusionTree;
  39527. } else {
  39528. // building inclusion and zero bit-planes trees
  39529. var width = precinct.cbxMax - precinct.cbxMin + 1;
  39530. var height = precinct.cbyMax - precinct.cbyMin + 1;
  39531. inclusionTree = new InclusionTree(width, height, layerNumber);
  39532. zeroBitPlanesTree = new TagTree(width, height);
  39533. precinct.inclusionTree = inclusionTree;
  39534. precinct.zeroBitPlanesTree = zeroBitPlanesTree;
  39535. }
  39536. if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
  39537. while (true) {
  39538. if (readBits(1)) {
  39539. valueReady = !inclusionTree.nextLevel();
  39540. if (valueReady) {
  39541. codeblock.included = true;
  39542. codeblockIncluded = firstTimeInclusion = true;
  39543. break;
  39544. }
  39545. } else {
  39546. inclusionTree.incrementValue(layerNumber);
  39547. break;
  39548. }
  39549. }
  39550. }
  39551. }
  39552. if (!codeblockIncluded) {
  39553. continue;
  39554. }
  39555. if (firstTimeInclusion) {
  39556. zeroBitPlanesTree = precinct.zeroBitPlanesTree;
  39557. zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
  39558. while (true) {
  39559. if (readBits(1)) {
  39560. valueReady = !zeroBitPlanesTree.nextLevel();
  39561. if (valueReady) {
  39562. break;
  39563. }
  39564. } else {
  39565. zeroBitPlanesTree.incrementValue();
  39566. }
  39567. }
  39568. codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
  39569. }
  39570. var codingpasses = readCodingpasses();
  39571. while (readBits(1)) {
  39572. codeblock.Lblock++;
  39573. }
  39574. var codingpassesLog2 = log2(codingpasses);
  39575. // rounding down log2
  39576. var bits = ((codingpasses < (1 << codingpassesLog2)) ?
  39577. codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
  39578. var codedDataLength = readBits(bits);
  39579. queue.push({
  39580. codeblock: codeblock,
  39581. codingpasses: codingpasses,
  39582. dataLength: codedDataLength
  39583. });
  39584. }
  39585. alignToByte();
  39586. if (ephMarkerUsed) {
  39587. skipMarkerIfEqual(0x92);
  39588. }
  39589. while (queue.length > 0) {
  39590. var packetItem = queue.shift();
  39591. codeblock = packetItem.codeblock;
  39592. if (codeblock['data'] === undefined) {
  39593. codeblock.data = [];
  39594. }
  39595. codeblock.data.push({
  39596. data: data,
  39597. start: offset + position,
  39598. end: offset + position + packetItem.dataLength,
  39599. codingpasses: packetItem.codingpasses
  39600. });
  39601. position += packetItem.dataLength;
  39602. }
  39603. }
  39604. return position;
  39605. }
  39606. function copyCoefficients(coefficients, levelWidth, levelHeight, subband,
  39607. delta, mb, reversible, segmentationSymbolUsed) {
  39608. var x0 = subband.tbx0;
  39609. var y0 = subband.tby0;
  39610. var width = subband.tbx1 - subband.tbx0;
  39611. var codeblocks = subband.codeblocks;
  39612. var right = subband.type.charAt(0) === 'H' ? 1 : 0;
  39613. var bottom = subband.type.charAt(1) === 'H' ? levelWidth : 0;
  39614. for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
  39615. var codeblock = codeblocks[i];
  39616. var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
  39617. var blockHeight = codeblock.tby1_ - codeblock.tby0_;
  39618. if (blockWidth === 0 || blockHeight === 0) {
  39619. continue;
  39620. }
  39621. if (codeblock['data'] === undefined) {
  39622. continue;
  39623. }
  39624. var bitModel, currentCodingpassType;
  39625. bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType,
  39626. codeblock.zeroBitPlanes, mb);
  39627. currentCodingpassType = 2; // first bit plane starts from cleanup
  39628. // collect data
  39629. var data = codeblock.data, totalLength = 0, codingpasses = 0;
  39630. var j, jj, dataItem;
  39631. for (j = 0, jj = data.length; j < jj; j++) {
  39632. dataItem = data[j];
  39633. totalLength += dataItem.end - dataItem.start;
  39634. codingpasses += dataItem.codingpasses;
  39635. }
  39636. var encodedData = new Uint8Array(totalLength);
  39637. var position = 0;
  39638. for (j = 0, jj = data.length; j < jj; j++) {
  39639. dataItem = data[j];
  39640. var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
  39641. encodedData.set(chunk, position);
  39642. position += chunk.length;
  39643. }
  39644. // decoding the item
  39645. var decoder = new ArithmeticDecoder(encodedData, 0, totalLength);
  39646. bitModel.setDecoder(decoder);
  39647. for (j = 0; j < codingpasses; j++) {
  39648. switch (currentCodingpassType) {
  39649. case 0:
  39650. bitModel.runSignificancePropogationPass();
  39651. break;
  39652. case 1:
  39653. bitModel.runMagnitudeRefinementPass();
  39654. break;
  39655. case 2:
  39656. bitModel.runCleanupPass();
  39657. if (segmentationSymbolUsed) {
  39658. bitModel.checkSegmentationSymbol();
  39659. }
  39660. break;
  39661. }
  39662. currentCodingpassType = (currentCodingpassType + 1) % 3;
  39663. }
  39664. var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width;
  39665. var sign = bitModel.coefficentsSign;
  39666. var magnitude = bitModel.coefficentsMagnitude;
  39667. var bitsDecoded = bitModel.bitsDecoded;
  39668. var magnitudeCorrection = reversible ? 0 : 0.5;
  39669. var k, n, nb;
  39670. position = 0;
  39671. // Do the interleaving of Section F.3.3 here, so we do not need
  39672. // to copy later. LL level is not interleaved, just copied.
  39673. var interleave = (subband.type !== 'LL');
  39674. for (j = 0; j < blockHeight; j++) {
  39675. var row = (offset / width) | 0; // row in the non-interleaved subband
  39676. var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
  39677. for (k = 0; k < blockWidth; k++) {
  39678. n = magnitude[position];
  39679. if (n !== 0) {
  39680. n = (n + magnitudeCorrection) * delta;
  39681. if (sign[position] !== 0) {
  39682. n = -n;
  39683. }
  39684. nb = bitsDecoded[position];
  39685. var pos = interleave ? (levelOffset + (offset << 1)) : offset;
  39686. if (reversible && (nb >= mb)) {
  39687. coefficients[pos] = n;
  39688. } else {
  39689. coefficients[pos] = n * (1 << (mb - nb));
  39690. }
  39691. }
  39692. offset++;
  39693. position++;
  39694. }
  39695. offset += width - blockWidth;
  39696. }
  39697. }
  39698. }
  39699. function transformTile(context, tile, c) {
  39700. var component = tile.components[c];
  39701. var codingStyleParameters = component.codingStyleParameters;
  39702. var quantizationParameters = component.quantizationParameters;
  39703. var decompositionLevelsCount =
  39704. codingStyleParameters.decompositionLevelsCount;
  39705. var spqcds = quantizationParameters.SPqcds;
  39706. var scalarExpounded = quantizationParameters.scalarExpounded;
  39707. var guardBits = quantizationParameters.guardBits;
  39708. var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
  39709. var precision = context.components[c].precision;
  39710. var reversible = codingStyleParameters.reversibleTransformation;
  39711. var transform = (reversible ? new ReversibleTransform() :
  39712. new IrreversibleTransform());
  39713. var subbandCoefficients = [];
  39714. var b = 0;
  39715. for (var i = 0; i <= decompositionLevelsCount; i++) {
  39716. var resolution = component.resolutions[i];
  39717. var width = resolution.trx1 - resolution.trx0;
  39718. var height = resolution.try1 - resolution.try0;
  39719. // Allocate space for the whole sublevel.
  39720. var coefficients = new Float32Array(width * height);
  39721. for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
  39722. var mu, epsilon;
  39723. if (!scalarExpounded) {
  39724. // formula E-5
  39725. mu = spqcds[0].mu;
  39726. epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
  39727. } else {
  39728. mu = spqcds[b].mu;
  39729. epsilon = spqcds[b].epsilon;
  39730. b++;
  39731. }
  39732. var subband = resolution.subbands[j];
  39733. var gainLog2 = SubbandsGainLog2[subband.type];
  39734. // calulate quantization coefficient (Section E.1.1.1)
  39735. var delta = (reversible ? 1 :
  39736. Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048));
  39737. var mb = (guardBits + epsilon - 1);
  39738. // In the first resolution level, copyCoefficients will fill the
  39739. // whole array with coefficients. In the succeding passes,
  39740. // copyCoefficients will consecutively fill in the values that belong
  39741. // to the interleaved positions of the HL, LH, and HH coefficients.
  39742. // The LL coefficients will then be interleaved in Transform.iterate().
  39743. copyCoefficients(coefficients, width, height, subband, delta, mb,
  39744. reversible, segmentationSymbolUsed);
  39745. }
  39746. subbandCoefficients.push({
  39747. width: width,
  39748. height: height,
  39749. items: coefficients
  39750. });
  39751. }
  39752. var result = transform.calculate(subbandCoefficients,
  39753. component.tcx0, component.tcy0);
  39754. return {
  39755. left: component.tcx0,
  39756. top: component.tcy0,
  39757. width: result.width,
  39758. height: result.height,
  39759. items: result.items
  39760. };
  39761. }
  39762. function transformComponents(context) {
  39763. var siz = context.SIZ;
  39764. var components = context.components;
  39765. var componentsCount = siz.Csiz;
  39766. var resultImages = [];
  39767. for (var i = 0, ii = context.tiles.length; i < ii; i++) {
  39768. var tile = context.tiles[i];
  39769. var transformedTiles = [];
  39770. var c;
  39771. for (c = 0; c < componentsCount; c++) {
  39772. transformedTiles[c] = transformTile(context, tile, c);
  39773. }
  39774. var tile0 = transformedTiles[0];
  39775. var out = new Uint8Array(tile0.items.length * componentsCount);
  39776. var result = {
  39777. left: tile0.left,
  39778. top: tile0.top,
  39779. width: tile0.width,
  39780. height: tile0.height,
  39781. items: out
  39782. };
  39783. // Section G.2.2 Inverse multi component transform
  39784. var shift, offset, max, min, maxK;
  39785. var pos = 0, j, jj, y0, y1, y2, r, g, b, k, val;
  39786. if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
  39787. var fourComponents = componentsCount === 4;
  39788. var y0items = transformedTiles[0].items;
  39789. var y1items = transformedTiles[1].items;
  39790. var y2items = transformedTiles[2].items;
  39791. var y3items = fourComponents ? transformedTiles[3].items : null;
  39792. // HACK: The multiple component transform formulas below assume that
  39793. // all components have the same precision. With this in mind, we
  39794. // compute shift and offset only once.
  39795. shift = components[0].precision - 8;
  39796. offset = (128 << shift) + 0.5;
  39797. max = 255 * (1 << shift);
  39798. maxK = max * 0.5;
  39799. min = -maxK;
  39800. var component0 = tile.components[0];
  39801. var alpha01 = componentsCount - 3;
  39802. jj = y0items.length;
  39803. if (!component0.codingStyleParameters.reversibleTransformation) {
  39804. // inverse irreversible multiple component transform
  39805. for (j = 0; j < jj; j++, pos += alpha01) {
  39806. y0 = y0items[j] + offset;
  39807. y1 = y1items[j];
  39808. y2 = y2items[j];
  39809. r = y0 + 1.402 * y2;
  39810. g = y0 - 0.34413 * y1 - 0.71414 * y2;
  39811. b = y0 + 1.772 * y1;
  39812. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  39813. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  39814. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  39815. }
  39816. } else {
  39817. // inverse reversible multiple component transform
  39818. for (j = 0; j < jj; j++, pos += alpha01) {
  39819. y0 = y0items[j] + offset;
  39820. y1 = y1items[j];
  39821. y2 = y2items[j];
  39822. g = y0 - ((y2 + y1) >> 2);
  39823. r = g + y2;
  39824. b = g + y1;
  39825. out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
  39826. out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
  39827. out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
  39828. }
  39829. }
  39830. if (fourComponents) {
  39831. for (j = 0, pos = 3; j < jj; j++, pos += 4) {
  39832. k = y3items[j];
  39833. out[pos] = k <= min ? 0 : k >= maxK ? 255 : (k + offset) >> shift;
  39834. }
  39835. }
  39836. } else { // no multi-component transform
  39837. for (c = 0; c < componentsCount; c++) {
  39838. var items = transformedTiles[c].items;
  39839. shift = components[c].precision - 8;
  39840. offset = (128 << shift) + 0.5;
  39841. max = (127.5 * (1 << shift));
  39842. min = -max;
  39843. for (pos = c, j = 0, jj = items.length; j < jj; j++) {
  39844. val = items[j];
  39845. out[pos] = val <= min ? 0 :
  39846. val >= max ? 255 : (val + offset) >> shift;
  39847. pos += componentsCount;
  39848. }
  39849. }
  39850. }
  39851. resultImages.push(result);
  39852. }
  39853. return resultImages;
  39854. }
  39855. function initializeTile(context, tileIndex) {
  39856. var siz = context.SIZ;
  39857. var componentsCount = siz.Csiz;
  39858. var tile = context.tiles[tileIndex];
  39859. for (var c = 0; c < componentsCount; c++) {
  39860. var component = tile.components[c];
  39861. var qcdOrQcc = (context.currentTile.QCC[c] !== undefined ?
  39862. context.currentTile.QCC[c] : context.currentTile.QCD);
  39863. component.quantizationParameters = qcdOrQcc;
  39864. var codOrCoc = (context.currentTile.COC[c] !== undefined ?
  39865. context.currentTile.COC[c] : context.currentTile.COD);
  39866. component.codingStyleParameters = codOrCoc;
  39867. }
  39868. tile.codingStyleDefaultParameters = context.currentTile.COD;
  39869. }
  39870. // Section B.10.2 Tag trees
  39871. var TagTree = (function TagTreeClosure() {
  39872. function TagTree(width, height) {
  39873. var levelsLength = log2(Math.max(width, height)) + 1;
  39874. this.levels = [];
  39875. for (var i = 0; i < levelsLength; i++) {
  39876. var level = {
  39877. width: width,
  39878. height: height,
  39879. items: []
  39880. };
  39881. this.levels.push(level);
  39882. width = Math.ceil(width / 2);
  39883. height = Math.ceil(height / 2);
  39884. }
  39885. }
  39886. TagTree.prototype = {
  39887. reset: function TagTree_reset(i, j) {
  39888. var currentLevel = 0, value = 0, level;
  39889. while (currentLevel < this.levels.length) {
  39890. level = this.levels[currentLevel];
  39891. var index = i + j * level.width;
  39892. if (level.items[index] !== undefined) {
  39893. value = level.items[index];
  39894. break;
  39895. }
  39896. level.index = index;
  39897. i >>= 1;
  39898. j >>= 1;
  39899. currentLevel++;
  39900. }
  39901. currentLevel--;
  39902. level = this.levels[currentLevel];
  39903. level.items[level.index] = value;
  39904. this.currentLevel = currentLevel;
  39905. delete this.value;
  39906. },
  39907. incrementValue: function TagTree_incrementValue() {
  39908. var level = this.levels[this.currentLevel];
  39909. level.items[level.index]++;
  39910. },
  39911. nextLevel: function TagTree_nextLevel() {
  39912. var currentLevel = this.currentLevel;
  39913. var level = this.levels[currentLevel];
  39914. var value = level.items[level.index];
  39915. currentLevel--;
  39916. if (currentLevel < 0) {
  39917. this.value = value;
  39918. return false;
  39919. }
  39920. this.currentLevel = currentLevel;
  39921. level = this.levels[currentLevel];
  39922. level.items[level.index] = value;
  39923. return true;
  39924. }
  39925. };
  39926. return TagTree;
  39927. })();
  39928. var InclusionTree = (function InclusionTreeClosure() {
  39929. function InclusionTree(width, height, defaultValue) {
  39930. var levelsLength = log2(Math.max(width, height)) + 1;
  39931. this.levels = [];
  39932. for (var i = 0; i < levelsLength; i++) {
  39933. var items = new Uint8Array(width * height);
  39934. for (var j = 0, jj = items.length; j < jj; j++) {
  39935. items[j] = defaultValue;
  39936. }
  39937. var level = {
  39938. width: width,
  39939. height: height,
  39940. items: items
  39941. };
  39942. this.levels.push(level);
  39943. width = Math.ceil(width / 2);
  39944. height = Math.ceil(height / 2);
  39945. }
  39946. }
  39947. InclusionTree.prototype = {
  39948. reset: function InclusionTree_reset(i, j, stopValue) {
  39949. var currentLevel = 0;
  39950. while (currentLevel < this.levels.length) {
  39951. var level = this.levels[currentLevel];
  39952. var index = i + j * level.width;
  39953. level.index = index;
  39954. var value = level.items[index];
  39955. if (value === 0xFF) {
  39956. break;
  39957. }
  39958. if (value > stopValue) {
  39959. this.currentLevel = currentLevel;
  39960. // already know about this one, propagating the value to top levels
  39961. this.propagateValues();
  39962. return false;
  39963. }
  39964. i >>= 1;
  39965. j >>= 1;
  39966. currentLevel++;
  39967. }
  39968. this.currentLevel = currentLevel - 1;
  39969. return true;
  39970. },
  39971. incrementValue: function InclusionTree_incrementValue(stopValue) {
  39972. var level = this.levels[this.currentLevel];
  39973. level.items[level.index] = stopValue + 1;
  39974. this.propagateValues();
  39975. },
  39976. propagateValues: function InclusionTree_propagateValues() {
  39977. var levelIndex = this.currentLevel;
  39978. var level = this.levels[levelIndex];
  39979. var currentValue = level.items[level.index];
  39980. while (--levelIndex >= 0) {
  39981. level = this.levels[levelIndex];
  39982. level.items[level.index] = currentValue;
  39983. }
  39984. },
  39985. nextLevel: function InclusionTree_nextLevel() {
  39986. var currentLevel = this.currentLevel;
  39987. var level = this.levels[currentLevel];
  39988. var value = level.items[level.index];
  39989. level.items[level.index] = 0xFF;
  39990. currentLevel--;
  39991. if (currentLevel < 0) {
  39992. return false;
  39993. }
  39994. this.currentLevel = currentLevel;
  39995. level = this.levels[currentLevel];
  39996. level.items[level.index] = value;
  39997. return true;
  39998. }
  39999. };
  40000. return InclusionTree;
  40001. })();
  40002. // Section D. Coefficient bit modeling
  40003. var BitModel = (function BitModelClosure() {
  40004. var UNIFORM_CONTEXT = 17;
  40005. var RUNLENGTH_CONTEXT = 18;
  40006. // Table D-1
  40007. // The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4),
  40008. // vv - sum of Vi (0..2), and hh - sum of Hi (0..2)
  40009. var LLAndLHContextsLabel = new Uint8Array([
  40010. 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,
  40011. 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,
  40012. 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
  40013. ]);
  40014. var HLContextLabel = new Uint8Array([
  40015. 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,
  40016. 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,
  40017. 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
  40018. ]);
  40019. var HHContextLabel = new Uint8Array([
  40020. 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,
  40021. 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,
  40022. 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
  40023. ]);
  40024. function BitModel(width, height, subband, zeroBitPlanes, mb) {
  40025. this.width = width;
  40026. this.height = height;
  40027. this.contextLabelTable = (subband === 'HH' ? HHContextLabel :
  40028. (subband === 'HL' ? HLContextLabel : LLAndLHContextsLabel));
  40029. var coefficientCount = width * height;
  40030. // coefficients outside the encoding region treated as insignificant
  40031. // add border state cells for significanceState
  40032. this.neighborsSignificance = new Uint8Array(coefficientCount);
  40033. this.coefficentsSign = new Uint8Array(coefficientCount);
  40034. this.coefficentsMagnitude = mb > 14 ? new Uint32Array(coefficientCount) :
  40035. mb > 6 ? new Uint16Array(coefficientCount) :
  40036. new Uint8Array(coefficientCount);
  40037. this.processingFlags = new Uint8Array(coefficientCount);
  40038. var bitsDecoded = new Uint8Array(coefficientCount);
  40039. if (zeroBitPlanes !== 0) {
  40040. for (var i = 0; i < coefficientCount; i++) {
  40041. bitsDecoded[i] = zeroBitPlanes;
  40042. }
  40043. }
  40044. this.bitsDecoded = bitsDecoded;
  40045. this.reset();
  40046. }
  40047. BitModel.prototype = {
  40048. setDecoder: function BitModel_setDecoder(decoder) {
  40049. this.decoder = decoder;
  40050. },
  40051. reset: function BitModel_reset() {
  40052. // We have 17 contexts that are accessed via context labels,
  40053. // plus the uniform and runlength context.
  40054. this.contexts = new Int8Array(19);
  40055. // Contexts are packed into 1 byte:
  40056. // highest 7 bits carry the index, lowest bit carries mps
  40057. this.contexts[0] = (4 << 1) | 0;
  40058. this.contexts[UNIFORM_CONTEXT] = (46 << 1) | 0;
  40059. this.contexts[RUNLENGTH_CONTEXT] = (3 << 1) | 0;
  40060. },
  40061. setNeighborsSignificance:
  40062. function BitModel_setNeighborsSignificance(row, column, index) {
  40063. var neighborsSignificance = this.neighborsSignificance;
  40064. var width = this.width, height = this.height;
  40065. var left = (column > 0);
  40066. var right = (column + 1 < width);
  40067. var i;
  40068. if (row > 0) {
  40069. i = index - width;
  40070. if (left) {
  40071. neighborsSignificance[i - 1] += 0x10;
  40072. }
  40073. if (right) {
  40074. neighborsSignificance[i + 1] += 0x10;
  40075. }
  40076. neighborsSignificance[i] += 0x04;
  40077. }
  40078. if (row + 1 < height) {
  40079. i = index + width;
  40080. if (left) {
  40081. neighborsSignificance[i - 1] += 0x10;
  40082. }
  40083. if (right) {
  40084. neighborsSignificance[i + 1] += 0x10;
  40085. }
  40086. neighborsSignificance[i] += 0x04;
  40087. }
  40088. if (left) {
  40089. neighborsSignificance[index - 1] += 0x01;
  40090. }
  40091. if (right) {
  40092. neighborsSignificance[index + 1] += 0x01;
  40093. }
  40094. neighborsSignificance[index] |= 0x80;
  40095. },
  40096. runSignificancePropogationPass:
  40097. function BitModel_runSignificancePropogationPass() {
  40098. var decoder = this.decoder;
  40099. var width = this.width, height = this.height;
  40100. var coefficentsMagnitude = this.coefficentsMagnitude;
  40101. var coefficentsSign = this.coefficentsSign;
  40102. var neighborsSignificance = this.neighborsSignificance;
  40103. var processingFlags = this.processingFlags;
  40104. var contexts = this.contexts;
  40105. var labels = this.contextLabelTable;
  40106. var bitsDecoded = this.bitsDecoded;
  40107. var processedInverseMask = ~1;
  40108. var processedMask = 1;
  40109. var firstMagnitudeBitMask = 2;
  40110. for (var i0 = 0; i0 < height; i0 += 4) {
  40111. for (var j = 0; j < width; j++) {
  40112. var index = i0 * width + j;
  40113. for (var i1 = 0; i1 < 4; i1++, index += width) {
  40114. var i = i0 + i1;
  40115. if (i >= height) {
  40116. break;
  40117. }
  40118. // clear processed flag first
  40119. processingFlags[index] &= processedInverseMask;
  40120. if (coefficentsMagnitude[index] ||
  40121. !neighborsSignificance[index]) {
  40122. continue;
  40123. }
  40124. var contextLabel = labels[neighborsSignificance[index]];
  40125. var decision = decoder.readBit(contexts, contextLabel);
  40126. if (decision) {
  40127. var sign = this.decodeSignBit(i, j, index);
  40128. coefficentsSign[index] = sign;
  40129. coefficentsMagnitude[index] = 1;
  40130. this.setNeighborsSignificance(i, j, index);
  40131. processingFlags[index] |= firstMagnitudeBitMask;
  40132. }
  40133. bitsDecoded[index]++;
  40134. processingFlags[index] |= processedMask;
  40135. }
  40136. }
  40137. }
  40138. },
  40139. decodeSignBit: function BitModel_decodeSignBit(row, column, index) {
  40140. var width = this.width, height = this.height;
  40141. var coefficentsMagnitude = this.coefficentsMagnitude;
  40142. var coefficentsSign = this.coefficentsSign;
  40143. var contribution, sign0, sign1, significance1;
  40144. var contextLabel, decoded;
  40145. // calculate horizontal contribution
  40146. significance1 = (column > 0 && coefficentsMagnitude[index - 1] !== 0);
  40147. if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
  40148. sign1 = coefficentsSign[index + 1];
  40149. if (significance1) {
  40150. sign0 = coefficentsSign[index - 1];
  40151. contribution = 1 - sign1 - sign0;
  40152. } else {
  40153. contribution = 1 - sign1 - sign1;
  40154. }
  40155. } else if (significance1) {
  40156. sign0 = coefficentsSign[index - 1];
  40157. contribution = 1 - sign0 - sign0;
  40158. } else {
  40159. contribution = 0;
  40160. }
  40161. var horizontalContribution = 3 * contribution;
  40162. // calculate vertical contribution and combine with the horizontal
  40163. significance1 = (row > 0 && coefficentsMagnitude[index - width] !== 0);
  40164. if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
  40165. sign1 = coefficentsSign[index + width];
  40166. if (significance1) {
  40167. sign0 = coefficentsSign[index - width];
  40168. contribution = 1 - sign1 - sign0 + horizontalContribution;
  40169. } else {
  40170. contribution = 1 - sign1 - sign1 + horizontalContribution;
  40171. }
  40172. } else if (significance1) {
  40173. sign0 = coefficentsSign[index - width];
  40174. contribution = 1 - sign0 - sign0 + horizontalContribution;
  40175. } else {
  40176. contribution = horizontalContribution;
  40177. }
  40178. if (contribution >= 0) {
  40179. contextLabel = 9 + contribution;
  40180. decoded = this.decoder.readBit(this.contexts, contextLabel);
  40181. } else {
  40182. contextLabel = 9 - contribution;
  40183. decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
  40184. }
  40185. return decoded;
  40186. },
  40187. runMagnitudeRefinementPass:
  40188. function BitModel_runMagnitudeRefinementPass() {
  40189. var decoder = this.decoder;
  40190. var width = this.width, height = this.height;
  40191. var coefficentsMagnitude = this.coefficentsMagnitude;
  40192. var neighborsSignificance = this.neighborsSignificance;
  40193. var contexts = this.contexts;
  40194. var bitsDecoded = this.bitsDecoded;
  40195. var processingFlags = this.processingFlags;
  40196. var processedMask = 1;
  40197. var firstMagnitudeBitMask = 2;
  40198. var length = width * height;
  40199. var width4 = width * 4;
  40200. for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {
  40201. indexNext = Math.min(length, index0 + width4);
  40202. for (var j = 0; j < width; j++) {
  40203. for (var index = index0 + j; index < indexNext; index += width) {
  40204. // significant but not those that have just become
  40205. if (!coefficentsMagnitude[index] ||
  40206. (processingFlags[index] & processedMask) !== 0) {
  40207. continue;
  40208. }
  40209. var contextLabel = 16;
  40210. if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
  40211. processingFlags[index] ^= firstMagnitudeBitMask;
  40212. // first refinement
  40213. var significance = neighborsSignificance[index] & 127;
  40214. contextLabel = significance === 0 ? 15 : 14;
  40215. }
  40216. var bit = decoder.readBit(contexts, contextLabel);
  40217. coefficentsMagnitude[index] =
  40218. (coefficentsMagnitude[index] << 1) | bit;
  40219. bitsDecoded[index]++;
  40220. processingFlags[index] |= processedMask;
  40221. }
  40222. }
  40223. }
  40224. },
  40225. runCleanupPass: function BitModel_runCleanupPass() {
  40226. var decoder = this.decoder;
  40227. var width = this.width, height = this.height;
  40228. var neighborsSignificance = this.neighborsSignificance;
  40229. var coefficentsMagnitude = this.coefficentsMagnitude;
  40230. var coefficentsSign = this.coefficentsSign;
  40231. var contexts = this.contexts;
  40232. var labels = this.contextLabelTable;
  40233. var bitsDecoded = this.bitsDecoded;
  40234. var processingFlags = this.processingFlags;
  40235. var processedMask = 1;
  40236. var firstMagnitudeBitMask = 2;
  40237. var oneRowDown = width;
  40238. var twoRowsDown = width * 2;
  40239. var threeRowsDown = width * 3;
  40240. var iNext;
  40241. for (var i0 = 0; i0 < height; i0 = iNext) {
  40242. iNext = Math.min(i0 + 4, height);
  40243. var indexBase = i0 * width;
  40244. var checkAllEmpty = i0 + 3 < height;
  40245. for (var j = 0; j < width; j++) {
  40246. var index0 = indexBase + j;
  40247. // using the property: labels[neighborsSignificance[index]] === 0
  40248. // when neighborsSignificance[index] === 0
  40249. var allEmpty = (checkAllEmpty &&
  40250. processingFlags[index0] === 0 &&
  40251. processingFlags[index0 + oneRowDown] === 0 &&
  40252. processingFlags[index0 + twoRowsDown] === 0 &&
  40253. processingFlags[index0 + threeRowsDown] === 0 &&
  40254. neighborsSignificance[index0] === 0 &&
  40255. neighborsSignificance[index0 + oneRowDown] === 0 &&
  40256. neighborsSignificance[index0 + twoRowsDown] === 0 &&
  40257. neighborsSignificance[index0 + threeRowsDown] === 0);
  40258. var i1 = 0, index = index0;
  40259. var i = i0, sign;
  40260. if (allEmpty) {
  40261. var hasSignificantCoefficent =
  40262. decoder.readBit(contexts, RUNLENGTH_CONTEXT);
  40263. if (!hasSignificantCoefficent) {
  40264. bitsDecoded[index0]++;
  40265. bitsDecoded[index0 + oneRowDown]++;
  40266. bitsDecoded[index0 + twoRowsDown]++;
  40267. bitsDecoded[index0 + threeRowsDown]++;
  40268. continue; // next column
  40269. }
  40270. i1 = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
  40271. decoder.readBit(contexts, UNIFORM_CONTEXT);
  40272. if (i1 !== 0) {
  40273. i = i0 + i1;
  40274. index += i1 * width;
  40275. }
  40276. sign = this.decodeSignBit(i, j, index);
  40277. coefficentsSign[index] = sign;
  40278. coefficentsMagnitude[index] = 1;
  40279. this.setNeighborsSignificance(i, j, index);
  40280. processingFlags[index] |= firstMagnitudeBitMask;
  40281. index = index0;
  40282. for (var i2 = i0; i2 <= i; i2++, index += width) {
  40283. bitsDecoded[index]++;
  40284. }
  40285. i1++;
  40286. }
  40287. for (i = i0 + i1; i < iNext; i++, index += width) {
  40288. if (coefficentsMagnitude[index] ||
  40289. (processingFlags[index] & processedMask) !== 0) {
  40290. continue;
  40291. }
  40292. var contextLabel = labels[neighborsSignificance[index]];
  40293. var decision = decoder.readBit(contexts, contextLabel);
  40294. if (decision === 1) {
  40295. sign = this.decodeSignBit(i, j, index);
  40296. coefficentsSign[index] = sign;
  40297. coefficentsMagnitude[index] = 1;
  40298. this.setNeighborsSignificance(i, j, index);
  40299. processingFlags[index] |= firstMagnitudeBitMask;
  40300. }
  40301. bitsDecoded[index]++;
  40302. }
  40303. }
  40304. }
  40305. },
  40306. checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {
  40307. var decoder = this.decoder;
  40308. var contexts = this.contexts;
  40309. var symbol = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 3) |
  40310. (decoder.readBit(contexts, UNIFORM_CONTEXT) << 2) |
  40311. (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
  40312. decoder.readBit(contexts, UNIFORM_CONTEXT);
  40313. if (symbol !== 0xA) {
  40314. throw new Error('JPX Error: Invalid segmentation symbol');
  40315. }
  40316. }
  40317. };
  40318. return BitModel;
  40319. })();
  40320. // Section F, Discrete wavelet transformation
  40321. var Transform = (function TransformClosure() {
  40322. function Transform() {}
  40323. Transform.prototype.calculate =
  40324. function transformCalculate(subbands, u0, v0) {
  40325. var ll = subbands[0];
  40326. for (var i = 1, ii = subbands.length; i < ii; i++) {
  40327. ll = this.iterate(ll, subbands[i], u0, v0);
  40328. }
  40329. return ll;
  40330. };
  40331. Transform.prototype.extend = function extend(buffer, offset, size) {
  40332. // Section F.3.7 extending... using max extension of 4
  40333. var i1 = offset - 1, j1 = offset + 1;
  40334. var i2 = offset + size - 2, j2 = offset + size;
  40335. buffer[i1--] = buffer[j1++];
  40336. buffer[j2++] = buffer[i2--];
  40337. buffer[i1--] = buffer[j1++];
  40338. buffer[j2++] = buffer[i2--];
  40339. buffer[i1--] = buffer[j1++];
  40340. buffer[j2++] = buffer[i2--];
  40341. buffer[i1] = buffer[j1];
  40342. buffer[j2] = buffer[i2];
  40343. };
  40344. Transform.prototype.iterate = function Transform_iterate(ll, hl_lh_hh,
  40345. u0, v0) {
  40346. var llWidth = ll.width, llHeight = ll.height, llItems = ll.items;
  40347. var width = hl_lh_hh.width;
  40348. var height = hl_lh_hh.height;
  40349. var items = hl_lh_hh.items;
  40350. var i, j, k, l, u, v;
  40351. // Interleave LL according to Section F.3.3
  40352. for (k = 0, i = 0; i < llHeight; i++) {
  40353. l = i * 2 * width;
  40354. for (j = 0; j < llWidth; j++, k++, l += 2) {
  40355. items[l] = llItems[k];
  40356. }
  40357. }
  40358. // The LL band is not needed anymore.
  40359. llItems = ll.items = null;
  40360. var bufferPadding = 4;
  40361. var rowBuffer = new Float32Array(width + 2 * bufferPadding);
  40362. // Section F.3.4 HOR_SR
  40363. if (width === 1) {
  40364. // if width = 1, when u0 even keep items as is, when odd divide by 2
  40365. if ((u0 & 1) !== 0) {
  40366. for (v = 0, k = 0; v < height; v++, k += width) {
  40367. items[k] *= 0.5;
  40368. }
  40369. }
  40370. } else {
  40371. for (v = 0, k = 0; v < height; v++, k += width) {
  40372. rowBuffer.set(items.subarray(k, k + width), bufferPadding);
  40373. this.extend(rowBuffer, bufferPadding, width);
  40374. this.filter(rowBuffer, bufferPadding, width);
  40375. items.set(
  40376. rowBuffer.subarray(bufferPadding, bufferPadding + width),
  40377. k);
  40378. }
  40379. }
  40380. // Accesses to the items array can take long, because it may not fit into
  40381. // CPU cache and has to be fetched from main memory. Since subsequent
  40382. // accesses to the items array are not local when reading columns, we
  40383. // have a cache miss every time. To reduce cache misses, get up to
  40384. // 'numBuffers' items at a time and store them into the individual
  40385. // buffers. The colBuffers should be small enough to fit into CPU cache.
  40386. var numBuffers = 16;
  40387. var colBuffers = [];
  40388. for (i = 0; i < numBuffers; i++) {
  40389. colBuffers.push(new Float32Array(height + 2 * bufferPadding));
  40390. }
  40391. var b, currentBuffer = 0;
  40392. ll = bufferPadding + height;
  40393. // Section F.3.5 VER_SR
  40394. if (height === 1) {
  40395. // if height = 1, when v0 even keep items as is, when odd divide by 2
  40396. if ((v0 & 1) !== 0) {
  40397. for (u = 0; u < width; u++) {
  40398. items[u] *= 0.5;
  40399. }
  40400. }
  40401. } else {
  40402. for (u = 0; u < width; u++) {
  40403. // if we ran out of buffers, copy several image columns at once
  40404. if (currentBuffer === 0) {
  40405. numBuffers = Math.min(width - u, numBuffers);
  40406. for (k = u, l = bufferPadding; l < ll; k += width, l++) {
  40407. for (b = 0; b < numBuffers; b++) {
  40408. colBuffers[b][l] = items[k + b];
  40409. }
  40410. }
  40411. currentBuffer = numBuffers;
  40412. }
  40413. currentBuffer--;
  40414. var buffer = colBuffers[currentBuffer];
  40415. this.extend(buffer, bufferPadding, height);
  40416. this.filter(buffer, bufferPadding, height);
  40417. // If this is last buffer in this group of buffers, flush all buffers.
  40418. if (currentBuffer === 0) {
  40419. k = u - numBuffers + 1;
  40420. for (l = bufferPadding; l < ll; k += width, l++) {
  40421. for (b = 0; b < numBuffers; b++) {
  40422. items[k + b] = colBuffers[b][l];
  40423. }
  40424. }
  40425. }
  40426. }
  40427. }
  40428. return {
  40429. width: width,
  40430. height: height,
  40431. items: items
  40432. };
  40433. };
  40434. return Transform;
  40435. })();
  40436. // Section 3.8.2 Irreversible 9-7 filter
  40437. var IrreversibleTransform = (function IrreversibleTransformClosure() {
  40438. function IrreversibleTransform() {
  40439. Transform.call(this);
  40440. }
  40441. IrreversibleTransform.prototype = Object.create(Transform.prototype);
  40442. IrreversibleTransform.prototype.filter =
  40443. function irreversibleTransformFilter(x, offset, length) {
  40444. var len = length >> 1;
  40445. offset = offset | 0;
  40446. var j, n, current, next;
  40447. var alpha = -1.586134342059924;
  40448. var beta = -0.052980118572961;
  40449. var gamma = 0.882911075530934;
  40450. var delta = 0.443506852043971;
  40451. var K = 1.230174104914001;
  40452. var K_ = 1 / K;
  40453. // step 1 is combined with step 3
  40454. // step 2
  40455. j = offset - 3;
  40456. for (n = len + 4; n--; j += 2) {
  40457. x[j] *= K_;
  40458. }
  40459. // step 1 & 3
  40460. j = offset - 2;
  40461. current = delta * x[j -1];
  40462. for (n = len + 3; n--; j += 2) {
  40463. next = delta * x[j + 1];
  40464. x[j] = K * x[j] - current - next;
  40465. if (n--) {
  40466. j += 2;
  40467. current = delta * x[j + 1];
  40468. x[j] = K * x[j] - current - next;
  40469. } else {
  40470. break;
  40471. }
  40472. }
  40473. // step 4
  40474. j = offset - 1;
  40475. current = gamma * x[j - 1];
  40476. for (n = len + 2; n--; j += 2) {
  40477. next = gamma * x[j + 1];
  40478. x[j] -= current + next;
  40479. if (n--) {
  40480. j += 2;
  40481. current = gamma * x[j + 1];
  40482. x[j] -= current + next;
  40483. } else {
  40484. break;
  40485. }
  40486. }
  40487. // step 5
  40488. j = offset;
  40489. current = beta * x[j - 1];
  40490. for (n = len + 1; n--; j += 2) {
  40491. next = beta * x[j + 1];
  40492. x[j] -= current + next;
  40493. if (n--) {
  40494. j += 2;
  40495. current = beta * x[j + 1];
  40496. x[j] -= current + next;
  40497. } else {
  40498. break;
  40499. }
  40500. }
  40501. // step 6
  40502. if (len !== 0) {
  40503. j = offset + 1;
  40504. current = alpha * x[j - 1];
  40505. for (n = len; n--; j += 2) {
  40506. next = alpha * x[j + 1];
  40507. x[j] -= current + next;
  40508. if (n--) {
  40509. j += 2;
  40510. current = alpha * x[j + 1];
  40511. x[j] -= current + next;
  40512. } else {
  40513. break;
  40514. }
  40515. }
  40516. }
  40517. };
  40518. return IrreversibleTransform;
  40519. })();
  40520. // Section 3.8.1 Reversible 5-3 filter
  40521. var ReversibleTransform = (function ReversibleTransformClosure() {
  40522. function ReversibleTransform() {
  40523. Transform.call(this);
  40524. }
  40525. ReversibleTransform.prototype = Object.create(Transform.prototype);
  40526. ReversibleTransform.prototype.filter =
  40527. function reversibleTransformFilter(x, offset, length) {
  40528. var len = length >> 1;
  40529. offset = offset | 0;
  40530. var j, n;
  40531. for (j = offset, n = len + 1; n--; j += 2) {
  40532. x[j] -= (x[j - 1] + x[j + 1] + 2) >> 2;
  40533. }
  40534. for (j = offset + 1, n = len; n--; j += 2) {
  40535. x[j] += (x[j - 1] + x[j + 1]) >> 1;
  40536. }
  40537. };
  40538. return ReversibleTransform;
  40539. })();
  40540. return JpxImage;
  40541. })();
  40542. var Jbig2Image = (function Jbig2ImageClosure() {
  40543. // Utility data structures
  40544. function ContextCache() {}
  40545. ContextCache.prototype = {
  40546. getContexts: function(id) {
  40547. if (id in this) {
  40548. return this[id];
  40549. }
  40550. return (this[id] = new Int8Array(1 << 16));
  40551. }
  40552. };
  40553. function DecodingContext(data, start, end) {
  40554. this.data = data;
  40555. this.start = start;
  40556. this.end = end;
  40557. }
  40558. DecodingContext.prototype = {
  40559. get decoder() {
  40560. var decoder = new ArithmeticDecoder(this.data, this.start, this.end);
  40561. return shadow(this, 'decoder', decoder);
  40562. },
  40563. get contextCache() {
  40564. var cache = new ContextCache();
  40565. return shadow(this, 'contextCache', cache);
  40566. }
  40567. };
  40568. // Annex A. Arithmetic Integer Decoding Procedure
  40569. // A.2 Procedure for decoding values
  40570. function decodeInteger(contextCache, procedure, decoder) {
  40571. var contexts = contextCache.getContexts(procedure);
  40572. var prev = 1;
  40573. function readBits(length) {
  40574. var v = 0;
  40575. for (var i = 0; i < length; i++) {
  40576. var bit = decoder.readBit(contexts, prev);
  40577. prev = (prev < 256 ? (prev << 1) | bit :
  40578. (((prev << 1) | bit) & 511) | 256);
  40579. v = (v << 1) | bit;
  40580. }
  40581. return v >>> 0;
  40582. }
  40583. var sign = readBits(1);
  40584. var value = readBits(1) ?
  40585. (readBits(1) ?
  40586. (readBits(1) ?
  40587. (readBits(1) ?
  40588. (readBits(1) ?
  40589. (readBits(32) + 4436) :
  40590. readBits(12) + 340) :
  40591. readBits(8) + 84) :
  40592. readBits(6) + 20) :
  40593. readBits(4) + 4) :
  40594. readBits(2);
  40595. return (sign === 0 ? value : (value > 0 ? -value : null));
  40596. }
  40597. // A.3 The IAID decoding procedure
  40598. function decodeIAID(contextCache, decoder, codeLength) {
  40599. var contexts = contextCache.getContexts('IAID');
  40600. var prev = 1;
  40601. for (var i = 0; i < codeLength; i++) {
  40602. var bit = decoder.readBit(contexts, prev);
  40603. prev = (prev << 1) | bit;
  40604. }
  40605. if (codeLength < 31) {
  40606. return prev & ((1 << codeLength) - 1);
  40607. }
  40608. return prev & 0x7FFFFFFF;
  40609. }
  40610. // 7.3 Segment types
  40611. var SegmentTypes = [
  40612. 'SymbolDictionary', null, null, null, 'IntermediateTextRegion', null,
  40613. 'ImmediateTextRegion', 'ImmediateLosslessTextRegion', null, null, null,
  40614. null, null, null, null, null, 'patternDictionary', null, null, null,
  40615. 'IntermediateHalftoneRegion', null, 'ImmediateHalftoneRegion',
  40616. 'ImmediateLosslessHalftoneRegion', null, null, null, null, null, null, null,
  40617. null, null, null, null, null, 'IntermediateGenericRegion', null,
  40618. 'ImmediateGenericRegion', 'ImmediateLosslessGenericRegion',
  40619. 'IntermediateGenericRefinementRegion', null,
  40620. 'ImmediateGenericRefinementRegion',
  40621. 'ImmediateLosslessGenericRefinementRegion', null, null, null, null,
  40622. 'PageInformation', 'EndOfPage', 'EndOfStripe', 'EndOfFile', 'Profiles',
  40623. 'Tables', null, null, null, null, null, null, null, null,
  40624. 'Extension'
  40625. ];
  40626. var CodingTemplates = [
  40627. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: -2, y: -1},
  40628. {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: 2, y: -1},
  40629. {x: -4, y: 0}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}],
  40630. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: 2, y: -2},
  40631. {x: -2, y: -1}, {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1},
  40632. {x: 2, y: -1}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}],
  40633. [{x: -1, y: -2}, {x: 0, y: -2}, {x: 1, y: -2}, {x: -2, y: -1},
  40634. {x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: -2, y: 0},
  40635. {x: -1, y: 0}],
  40636. [{x: -3, y: -1}, {x: -2, y: -1}, {x: -1, y: -1}, {x: 0, y: -1},
  40637. {x: 1, y: -1}, {x: -4, y: 0}, {x: -3, y: 0}, {x: -2, y: 0}, {x: -1, y: 0}]
  40638. ];
  40639. var RefinementTemplates = [
  40640. {
  40641. coding: [{x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}],
  40642. reference: [{x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}, {x: 0, y: 0},
  40643. {x: 1, y: 0}, {x: -1, y: 1}, {x: 0, y: 1}, {x: 1, y: 1}]
  40644. },
  40645. {
  40646. coding: [{x: -1, y: -1}, {x: 0, y: -1}, {x: 1, y: -1}, {x: -1, y: 0}],
  40647. reference: [{x: 0, y: -1}, {x: -1, y: 0}, {x: 0, y: 0}, {x: 1, y: 0},
  40648. {x: 0, y: 1}, {x: 1, y: 1}]
  40649. }
  40650. ];
  40651. // See 6.2.5.7 Decoding the bitmap.
  40652. var ReusedContexts = [
  40653. 0x9B25, // 10011 0110010 0101
  40654. 0x0795, // 0011 110010 101
  40655. 0x00E5, // 001 11001 01
  40656. 0x0195 // 011001 0101
  40657. ];
  40658. var RefinementReusedContexts = [
  40659. 0x0020, // '000' + '0' (coding) + '00010000' + '0' (reference)
  40660. 0x0008 // '0000' + '001000'
  40661. ];
  40662. function decodeBitmapTemplate0(width, height, decodingContext) {
  40663. var decoder = decodingContext.decoder;
  40664. var contexts = decodingContext.contextCache.getContexts('GB');
  40665. var contextLabel, i, j, pixel, row, row1, row2, bitmap = [];
  40666. // ...ooooo....
  40667. // ..ooooooo... Context template for current pixel (X)
  40668. // .ooooX...... (concatenate values of 'o'-pixels to get contextLabel)
  40669. var OLD_PIXEL_MASK = 0x7BF7; // 01111 0111111 0111
  40670. for (i = 0; i < height; i++) {
  40671. row = bitmap[i] = new Uint8Array(width);
  40672. row1 = (i < 1) ? row : bitmap[i - 1];
  40673. row2 = (i < 2) ? row : bitmap[i - 2];
  40674. // At the beginning of each row:
  40675. // Fill contextLabel with pixels that are above/right of (X)
  40676. contextLabel = (row2[0] << 13) | (row2[1] << 12) | (row2[2] << 11) |
  40677. (row1[0] << 7) | (row1[1] << 6) | (row1[2] << 5) |
  40678. (row1[3] << 4);
  40679. for (j = 0; j < width; j++) {
  40680. row[j] = pixel = decoder.readBit(contexts, contextLabel);
  40681. // At each pixel: Clear contextLabel pixels that are shifted
  40682. // out of the context, then add new ones.
  40683. // If j + n is out of range at the right image border, then
  40684. // the undefined value of bitmap[i - 2][j + n] is shifted to 0
  40685. contextLabel = ((contextLabel & OLD_PIXEL_MASK) << 1) |
  40686. (row2[j + 3] << 11) | (row1[j + 4] << 4) | pixel;
  40687. }
  40688. }
  40689. return bitmap;
  40690. }
  40691. // 6.2 Generic Region Decoding Procedure
  40692. function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at,
  40693. decodingContext) {
  40694. if (mmr) {
  40695. error('JBIG2 error: MMR encoding is not supported');
  40696. }
  40697. // Use optimized version for the most common case
  40698. if (templateIndex === 0 && !skip && !prediction && at.length === 4 &&
  40699. at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 &&
  40700. at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) {
  40701. return decodeBitmapTemplate0(width, height, decodingContext);
  40702. }
  40703. var useskip = !!skip;
  40704. var template = CodingTemplates[templateIndex].concat(at);
  40705. // Sorting is non-standard, and it is not required. But sorting increases
  40706. // the number of template bits that can be reused from the previous
  40707. // contextLabel in the main loop.
  40708. template.sort(function (a, b) {
  40709. return (a.y - b.y) || (a.x - b.x);
  40710. });
  40711. var templateLength = template.length;
  40712. var templateX = new Int8Array(templateLength);
  40713. var templateY = new Int8Array(templateLength);
  40714. var changingTemplateEntries = [];
  40715. var reuseMask = 0, minX = 0, maxX = 0, minY = 0;
  40716. var c, k;
  40717. for (k = 0; k < templateLength; k++) {
  40718. templateX[k] = template[k].x;
  40719. templateY[k] = template[k].y;
  40720. minX = Math.min(minX, template[k].x);
  40721. maxX = Math.max(maxX, template[k].x);
  40722. minY = Math.min(minY, template[k].y);
  40723. // Check if the template pixel appears in two consecutive context labels,
  40724. // so it can be reused. Otherwise, we add it to the list of changing
  40725. // template entries.
  40726. if (k < templateLength - 1 &&
  40727. template[k].y === template[k + 1].y &&
  40728. template[k].x === template[k + 1].x - 1) {
  40729. reuseMask |= 1 << (templateLength - 1 - k);
  40730. } else {
  40731. changingTemplateEntries.push(k);
  40732. }
  40733. }
  40734. var changingEntriesLength = changingTemplateEntries.length;
  40735. var changingTemplateX = new Int8Array(changingEntriesLength);
  40736. var changingTemplateY = new Int8Array(changingEntriesLength);
  40737. var changingTemplateBit = new Uint16Array(changingEntriesLength);
  40738. for (c = 0; c < changingEntriesLength; c++) {
  40739. k = changingTemplateEntries[c];
  40740. changingTemplateX[c] = template[k].x;
  40741. changingTemplateY[c] = template[k].y;
  40742. changingTemplateBit[c] = 1 << (templateLength - 1 - k);
  40743. }
  40744. // Get the safe bounding box edges from the width, height, minX, maxX, minY
  40745. var sbb_left = -minX;
  40746. var sbb_top = -minY;
  40747. var sbb_right = width - maxX;
  40748. var pseudoPixelContext = ReusedContexts[templateIndex];
  40749. var row = new Uint8Array(width);
  40750. var bitmap = [];
  40751. var decoder = decodingContext.decoder;
  40752. var contexts = decodingContext.contextCache.getContexts('GB');
  40753. var ltp = 0, j, i0, j0, contextLabel = 0, bit, shift;
  40754. for (var i = 0; i < height; i++) {
  40755. if (prediction) {
  40756. var sltp = decoder.readBit(contexts, pseudoPixelContext);
  40757. ltp ^= sltp;
  40758. if (ltp) {
  40759. bitmap.push(row); // duplicate previous row
  40760. continue;
  40761. }
  40762. }
  40763. row = new Uint8Array(row);
  40764. bitmap.push(row);
  40765. for (j = 0; j < width; j++) {
  40766. if (useskip && skip[i][j]) {
  40767. row[j] = 0;
  40768. continue;
  40769. }
  40770. // Are we in the middle of a scanline, so we can reuse contextLabel
  40771. // bits?
  40772. if (j >= sbb_left && j < sbb_right && i >= sbb_top) {
  40773. // If yes, we can just shift the bits that are reusable and only
  40774. // fetch the remaining ones.
  40775. contextLabel = (contextLabel << 1) & reuseMask;
  40776. for (k = 0; k < changingEntriesLength; k++) {
  40777. i0 = i + changingTemplateY[k];
  40778. j0 = j + changingTemplateX[k];
  40779. bit = bitmap[i0][j0];
  40780. if (bit) {
  40781. bit = changingTemplateBit[k];
  40782. contextLabel |= bit;
  40783. }
  40784. }
  40785. } else {
  40786. // compute the contextLabel from scratch
  40787. contextLabel = 0;
  40788. shift = templateLength - 1;
  40789. for (k = 0; k < templateLength; k++, shift--) {
  40790. j0 = j + templateX[k];
  40791. if (j0 >= 0 && j0 < width) {
  40792. i0 = i + templateY[k];
  40793. if (i0 >= 0) {
  40794. bit = bitmap[i0][j0];
  40795. if (bit) {
  40796. contextLabel |= bit << shift;
  40797. }
  40798. }
  40799. }
  40800. }
  40801. }
  40802. var pixel = decoder.readBit(contexts, contextLabel);
  40803. row[j] = pixel;
  40804. }
  40805. }
  40806. return bitmap;
  40807. }
  40808. // 6.3.2 Generic Refinement Region Decoding Procedure
  40809. function decodeRefinement(width, height, templateIndex, referenceBitmap,
  40810. offsetX, offsetY, prediction, at,
  40811. decodingContext) {
  40812. var codingTemplate = RefinementTemplates[templateIndex].coding;
  40813. if (templateIndex === 0) {
  40814. codingTemplate = codingTemplate.concat([at[0]]);
  40815. }
  40816. var codingTemplateLength = codingTemplate.length;
  40817. var codingTemplateX = new Int32Array(codingTemplateLength);
  40818. var codingTemplateY = new Int32Array(codingTemplateLength);
  40819. var k;
  40820. for (k = 0; k < codingTemplateLength; k++) {
  40821. codingTemplateX[k] = codingTemplate[k].x;
  40822. codingTemplateY[k] = codingTemplate[k].y;
  40823. }
  40824. var referenceTemplate = RefinementTemplates[templateIndex].reference;
  40825. if (templateIndex === 0) {
  40826. referenceTemplate = referenceTemplate.concat([at[1]]);
  40827. }
  40828. var referenceTemplateLength = referenceTemplate.length;
  40829. var referenceTemplateX = new Int32Array(referenceTemplateLength);
  40830. var referenceTemplateY = new Int32Array(referenceTemplateLength);
  40831. for (k = 0; k < referenceTemplateLength; k++) {
  40832. referenceTemplateX[k] = referenceTemplate[k].x;
  40833. referenceTemplateY[k] = referenceTemplate[k].y;
  40834. }
  40835. var referenceWidth = referenceBitmap[0].length;
  40836. var referenceHeight = referenceBitmap.length;
  40837. var pseudoPixelContext = RefinementReusedContexts[templateIndex];
  40838. var bitmap = [];
  40839. var decoder = decodingContext.decoder;
  40840. var contexts = decodingContext.contextCache.getContexts('GR');
  40841. var ltp = 0;
  40842. for (var i = 0; i < height; i++) {
  40843. if (prediction) {
  40844. var sltp = decoder.readBit(contexts, pseudoPixelContext);
  40845. ltp ^= sltp;
  40846. if (ltp) {
  40847. error('JBIG2 error: prediction is not supported');
  40848. }
  40849. }
  40850. var row = new Uint8Array(width);
  40851. bitmap.push(row);
  40852. for (var j = 0; j < width; j++) {
  40853. var i0, j0;
  40854. var contextLabel = 0;
  40855. for (k = 0; k < codingTemplateLength; k++) {
  40856. i0 = i + codingTemplateY[k];
  40857. j0 = j + codingTemplateX[k];
  40858. if (i0 < 0 || j0 < 0 || j0 >= width) {
  40859. contextLabel <<= 1; // out of bound pixel
  40860. } else {
  40861. contextLabel = (contextLabel << 1) | bitmap[i0][j0];
  40862. }
  40863. }
  40864. for (k = 0; k < referenceTemplateLength; k++) {
  40865. i0 = i + referenceTemplateY[k] + offsetY;
  40866. j0 = j + referenceTemplateX[k] + offsetX;
  40867. if (i0 < 0 || i0 >= referenceHeight || j0 < 0 ||
  40868. j0 >= referenceWidth) {
  40869. contextLabel <<= 1; // out of bound pixel
  40870. } else {
  40871. contextLabel = (contextLabel << 1) | referenceBitmap[i0][j0];
  40872. }
  40873. }
  40874. var pixel = decoder.readBit(contexts, contextLabel);
  40875. row[j] = pixel;
  40876. }
  40877. }
  40878. return bitmap;
  40879. }
  40880. // 6.5.5 Decoding the symbol dictionary
  40881. function decodeSymbolDictionary(huffman, refinement, symbols,
  40882. numberOfNewSymbols, numberOfExportedSymbols,
  40883. huffmanTables, templateIndex, at,
  40884. refinementTemplateIndex, refinementAt,
  40885. decodingContext) {
  40886. if (huffman) {
  40887. error('JBIG2 error: huffman is not supported');
  40888. }
  40889. var newSymbols = [];
  40890. var currentHeight = 0;
  40891. var symbolCodeLength = log2(symbols.length + numberOfNewSymbols);
  40892. var decoder = decodingContext.decoder;
  40893. var contextCache = decodingContext.contextCache;
  40894. while (newSymbols.length < numberOfNewSymbols) {
  40895. var deltaHeight = decodeInteger(contextCache, 'IADH', decoder); // 6.5.6
  40896. currentHeight += deltaHeight;
  40897. var currentWidth = 0;
  40898. var totalWidth = 0;
  40899. while (true) {
  40900. var deltaWidth = decodeInteger(contextCache, 'IADW', decoder); // 6.5.7
  40901. if (deltaWidth === null) {
  40902. break; // OOB
  40903. }
  40904. currentWidth += deltaWidth;
  40905. totalWidth += currentWidth;
  40906. var bitmap;
  40907. if (refinement) {
  40908. // 6.5.8.2 Refinement/aggregate-coded symbol bitmap
  40909. var numberOfInstances = decodeInteger(contextCache, 'IAAI', decoder);
  40910. if (numberOfInstances > 1) {
  40911. bitmap = decodeTextRegion(huffman, refinement,
  40912. currentWidth, currentHeight, 0,
  40913. numberOfInstances, 1, //strip size
  40914. symbols.concat(newSymbols),
  40915. symbolCodeLength,
  40916. 0, //transposed
  40917. 0, //ds offset
  40918. 1, //top left 7.4.3.1.1
  40919. 0, //OR operator
  40920. huffmanTables,
  40921. refinementTemplateIndex, refinementAt,
  40922. decodingContext);
  40923. } else {
  40924. var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  40925. var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3
  40926. var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4
  40927. var symbol = (symbolId < symbols.length ? symbols[symbolId] :
  40928. newSymbols[symbolId - symbols.length]);
  40929. bitmap = decodeRefinement(currentWidth, currentHeight,
  40930. refinementTemplateIndex, symbol, rdx, rdy, false, refinementAt,
  40931. decodingContext);
  40932. }
  40933. } else {
  40934. // 6.5.8.1 Direct-coded symbol bitmap
  40935. bitmap = decodeBitmap(false, currentWidth, currentHeight,
  40936. templateIndex, false, null, at, decodingContext);
  40937. }
  40938. newSymbols.push(bitmap);
  40939. }
  40940. }
  40941. // 6.5.10 Exported symbols
  40942. var exportedSymbols = [];
  40943. var flags = [], currentFlag = false;
  40944. var totalSymbolsLength = symbols.length + numberOfNewSymbols;
  40945. while (flags.length < totalSymbolsLength) {
  40946. var runLength = decodeInteger(contextCache, 'IAEX', decoder);
  40947. while (runLength--) {
  40948. flags.push(currentFlag);
  40949. }
  40950. currentFlag = !currentFlag;
  40951. }
  40952. for (var i = 0, ii = symbols.length; i < ii; i++) {
  40953. if (flags[i]) {
  40954. exportedSymbols.push(symbols[i]);
  40955. }
  40956. }
  40957. for (var j = 0; j < numberOfNewSymbols; i++, j++) {
  40958. if (flags[i]) {
  40959. exportedSymbols.push(newSymbols[j]);
  40960. }
  40961. }
  40962. return exportedSymbols;
  40963. }
  40964. function decodeTextRegion(huffman, refinement, width, height,
  40965. defaultPixelValue, numberOfSymbolInstances,
  40966. stripSize, inputSymbols, symbolCodeLength,
  40967. transposed, dsOffset, referenceCorner,
  40968. combinationOperator, huffmanTables,
  40969. refinementTemplateIndex, refinementAt,
  40970. decodingContext) {
  40971. if (huffman) {
  40972. error('JBIG2 error: huffman is not supported');
  40973. }
  40974. // Prepare bitmap
  40975. var bitmap = [];
  40976. var i, row;
  40977. for (i = 0; i < height; i++) {
  40978. row = new Uint8Array(width);
  40979. if (defaultPixelValue) {
  40980. for (var j = 0; j < width; j++) {
  40981. row[j] = defaultPixelValue;
  40982. }
  40983. }
  40984. bitmap.push(row);
  40985. }
  40986. var decoder = decodingContext.decoder;
  40987. var contextCache = decodingContext.contextCache;
  40988. var stripT = -decodeInteger(contextCache, 'IADT', decoder); // 6.4.6
  40989. var firstS = 0;
  40990. i = 0;
  40991. while (i < numberOfSymbolInstances) {
  40992. var deltaT = decodeInteger(contextCache, 'IADT', decoder); // 6.4.6
  40993. stripT += deltaT;
  40994. var deltaFirstS = decodeInteger(contextCache, 'IAFS', decoder); // 6.4.7
  40995. firstS += deltaFirstS;
  40996. var currentS = firstS;
  40997. do {
  40998. var currentT = (stripSize === 1 ? 0 :
  40999. decodeInteger(contextCache, 'IAIT', decoder)); // 6.4.9
  41000. var t = stripSize * stripT + currentT;
  41001. var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
  41002. var applyRefinement = (refinement &&
  41003. decodeInteger(contextCache, 'IARI', decoder));
  41004. var symbolBitmap = inputSymbols[symbolId];
  41005. var symbolWidth = symbolBitmap[0].length;
  41006. var symbolHeight = symbolBitmap.length;
  41007. if (applyRefinement) {
  41008. var rdw = decodeInteger(contextCache, 'IARDW', decoder); // 6.4.11.1
  41009. var rdh = decodeInteger(contextCache, 'IARDH', decoder); // 6.4.11.2
  41010. var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3
  41011. var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4
  41012. symbolWidth += rdw;
  41013. symbolHeight += rdh;
  41014. symbolBitmap = decodeRefinement(symbolWidth, symbolHeight,
  41015. refinementTemplateIndex, symbolBitmap, (rdw >> 1) + rdx,
  41016. (rdh >> 1) + rdy, false, refinementAt,
  41017. decodingContext);
  41018. }
  41019. var offsetT = t - ((referenceCorner & 1) ? 0 : symbolHeight);
  41020. var offsetS = currentS - ((referenceCorner & 2) ? symbolWidth : 0);
  41021. var s2, t2, symbolRow;
  41022. if (transposed) {
  41023. // Place Symbol Bitmap from T1,S1
  41024. for (s2 = 0; s2 < symbolHeight; s2++) {
  41025. row = bitmap[offsetS + s2];
  41026. if (!row) {
  41027. continue;
  41028. }
  41029. symbolRow = symbolBitmap[s2];
  41030. // To ignore Parts of Symbol bitmap which goes
  41031. // outside bitmap region
  41032. var maxWidth = Math.min(width - offsetT, symbolWidth);
  41033. switch (combinationOperator) {
  41034. case 0: // OR
  41035. for (t2 = 0; t2 < maxWidth; t2++) {
  41036. row[offsetT + t2] |= symbolRow[t2];
  41037. }
  41038. break;
  41039. case 2: // XOR
  41040. for (t2 = 0; t2 < maxWidth; t2++) {
  41041. row[offsetT + t2] ^= symbolRow[t2];
  41042. }
  41043. break;
  41044. default:
  41045. error('JBIG2 error: operator ' + combinationOperator +
  41046. ' is not supported');
  41047. }
  41048. }
  41049. currentS += symbolHeight - 1;
  41050. } else {
  41051. for (t2 = 0; t2 < symbolHeight; t2++) {
  41052. row = bitmap[offsetT + t2];
  41053. if (!row) {
  41054. continue;
  41055. }
  41056. symbolRow = symbolBitmap[t2];
  41057. switch (combinationOperator) {
  41058. case 0: // OR
  41059. for (s2 = 0; s2 < symbolWidth; s2++) {
  41060. row[offsetS + s2] |= symbolRow[s2];
  41061. }
  41062. break;
  41063. case 2: // XOR
  41064. for (s2 = 0; s2 < symbolWidth; s2++) {
  41065. row[offsetS + s2] ^= symbolRow[s2];
  41066. }
  41067. break;
  41068. default:
  41069. error('JBIG2 error: operator ' + combinationOperator +
  41070. ' is not supported');
  41071. }
  41072. }
  41073. currentS += symbolWidth - 1;
  41074. }
  41075. i++;
  41076. var deltaS = decodeInteger(contextCache, 'IADS', decoder); // 6.4.8
  41077. if (deltaS === null) {
  41078. break; // OOB
  41079. }
  41080. currentS += deltaS + dsOffset;
  41081. } while (true);
  41082. }
  41083. return bitmap;
  41084. }
  41085. function readSegmentHeader(data, start) {
  41086. var segmentHeader = {};
  41087. segmentHeader.number = readUint32(data, start);
  41088. var flags = data[start + 4];
  41089. var segmentType = flags & 0x3F;
  41090. if (!SegmentTypes[segmentType]) {
  41091. error('JBIG2 error: invalid segment type: ' + segmentType);
  41092. }
  41093. segmentHeader.type = segmentType;
  41094. segmentHeader.typeName = SegmentTypes[segmentType];
  41095. segmentHeader.deferredNonRetain = !!(flags & 0x80);
  41096. var pageAssociationFieldSize = !!(flags & 0x40);
  41097. var referredFlags = data[start + 5];
  41098. var referredToCount = (referredFlags >> 5) & 7;
  41099. var retainBits = [referredFlags & 31];
  41100. var position = start + 6;
  41101. if (referredFlags === 7) {
  41102. referredToCount = readUint32(data, position - 1) & 0x1FFFFFFF;
  41103. position += 3;
  41104. var bytes = (referredToCount + 7) >> 3;
  41105. retainBits[0] = data[position++];
  41106. while (--bytes > 0) {
  41107. retainBits.push(data[position++]);
  41108. }
  41109. } else if (referredFlags === 5 || referredFlags === 6) {
  41110. error('JBIG2 error: invalid referred-to flags');
  41111. }
  41112. segmentHeader.retainBits = retainBits;
  41113. var referredToSegmentNumberSize = (segmentHeader.number <= 256 ? 1 :
  41114. (segmentHeader.number <= 65536 ? 2 : 4));
  41115. var referredTo = [];
  41116. var i, ii;
  41117. for (i = 0; i < referredToCount; i++) {
  41118. var number = (referredToSegmentNumberSize === 1 ? data[position] :
  41119. (referredToSegmentNumberSize === 2 ? readUint16(data, position) :
  41120. readUint32(data, position)));
  41121. referredTo.push(number);
  41122. position += referredToSegmentNumberSize;
  41123. }
  41124. segmentHeader.referredTo = referredTo;
  41125. if (!pageAssociationFieldSize) {
  41126. segmentHeader.pageAssociation = data[position++];
  41127. } else {
  41128. segmentHeader.pageAssociation = readUint32(data, position);
  41129. position += 4;
  41130. }
  41131. segmentHeader.length = readUint32(data, position);
  41132. position += 4;
  41133. if (segmentHeader.length === 0xFFFFFFFF) {
  41134. // 7.2.7 Segment data length, unknown segment length
  41135. if (segmentType === 38) { // ImmediateGenericRegion
  41136. var genericRegionInfo = readRegionSegmentInformation(data, position);
  41137. var genericRegionSegmentFlags = data[position +
  41138. RegionSegmentInformationFieldLength];
  41139. var genericRegionMmr = !!(genericRegionSegmentFlags & 1);
  41140. // searching for the segment end
  41141. var searchPatternLength = 6;
  41142. var searchPattern = new Uint8Array(searchPatternLength);
  41143. if (!genericRegionMmr) {
  41144. searchPattern[0] = 0xFF;
  41145. searchPattern[1] = 0xAC;
  41146. }
  41147. searchPattern[2] = (genericRegionInfo.height >>> 24) & 0xFF;
  41148. searchPattern[3] = (genericRegionInfo.height >> 16) & 0xFF;
  41149. searchPattern[4] = (genericRegionInfo.height >> 8) & 0xFF;
  41150. searchPattern[5] = genericRegionInfo.height & 0xFF;
  41151. for (i = position, ii = data.length; i < ii; i++) {
  41152. var j = 0;
  41153. while (j < searchPatternLength && searchPattern[j] === data[i + j]) {
  41154. j++;
  41155. }
  41156. if (j === searchPatternLength) {
  41157. segmentHeader.length = i + searchPatternLength;
  41158. break;
  41159. }
  41160. }
  41161. if (segmentHeader.length === 0xFFFFFFFF) {
  41162. error('JBIG2 error: segment end was not found');
  41163. }
  41164. } else {
  41165. error('JBIG2 error: invalid unknown segment length');
  41166. }
  41167. }
  41168. segmentHeader.headerEnd = position;
  41169. return segmentHeader;
  41170. }
  41171. function readSegments(header, data, start, end) {
  41172. var segments = [];
  41173. var position = start;
  41174. while (position < end) {
  41175. var segmentHeader = readSegmentHeader(data, position);
  41176. position = segmentHeader.headerEnd;
  41177. var segment = {
  41178. header: segmentHeader,
  41179. data: data
  41180. };
  41181. if (!header.randomAccess) {
  41182. segment.start = position;
  41183. position += segmentHeader.length;
  41184. segment.end = position;
  41185. }
  41186. segments.push(segment);
  41187. if (segmentHeader.type === 51) {
  41188. break; // end of file is found
  41189. }
  41190. }
  41191. if (header.randomAccess) {
  41192. for (var i = 0, ii = segments.length; i < ii; i++) {
  41193. segments[i].start = position;
  41194. position += segments[i].header.length;
  41195. segments[i].end = position;
  41196. }
  41197. }
  41198. return segments;
  41199. }
  41200. // 7.4.1 Region segment information field
  41201. function readRegionSegmentInformation(data, start) {
  41202. return {
  41203. width: readUint32(data, start),
  41204. height: readUint32(data, start + 4),
  41205. x: readUint32(data, start + 8),
  41206. y: readUint32(data, start + 12),
  41207. combinationOperator: data[start + 16] & 7
  41208. };
  41209. }
  41210. var RegionSegmentInformationFieldLength = 17;
  41211. function processSegment(segment, visitor) {
  41212. var header = segment.header;
  41213. var data = segment.data, position = segment.start, end = segment.end;
  41214. var args, at, i, atLength;
  41215. switch (header.type) {
  41216. case 0: // SymbolDictionary
  41217. // 7.4.2 Symbol dictionary segment syntax
  41218. var dictionary = {};
  41219. var dictionaryFlags = readUint16(data, position); // 7.4.2.1.1
  41220. dictionary.huffman = !!(dictionaryFlags & 1);
  41221. dictionary.refinement = !!(dictionaryFlags & 2);
  41222. dictionary.huffmanDHSelector = (dictionaryFlags >> 2) & 3;
  41223. dictionary.huffmanDWSelector = (dictionaryFlags >> 4) & 3;
  41224. dictionary.bitmapSizeSelector = (dictionaryFlags >> 6) & 1;
  41225. dictionary.aggregationInstancesSelector = (dictionaryFlags >> 7) & 1;
  41226. dictionary.bitmapCodingContextUsed = !!(dictionaryFlags & 256);
  41227. dictionary.bitmapCodingContextRetained = !!(dictionaryFlags & 512);
  41228. dictionary.template = (dictionaryFlags >> 10) & 3;
  41229. dictionary.refinementTemplate = (dictionaryFlags >> 12) & 1;
  41230. position += 2;
  41231. if (!dictionary.huffman) {
  41232. atLength = dictionary.template === 0 ? 4 : 1;
  41233. at = [];
  41234. for (i = 0; i < atLength; i++) {
  41235. at.push({
  41236. x: readInt8(data, position),
  41237. y: readInt8(data, position + 1)
  41238. });
  41239. position += 2;
  41240. }
  41241. dictionary.at = at;
  41242. }
  41243. if (dictionary.refinement && !dictionary.refinementTemplate) {
  41244. at = [];
  41245. for (i = 0; i < 2; i++) {
  41246. at.push({
  41247. x: readInt8(data, position),
  41248. y: readInt8(data, position + 1)
  41249. });
  41250. position += 2;
  41251. }
  41252. dictionary.refinementAt = at;
  41253. }
  41254. dictionary.numberOfExportedSymbols = readUint32(data, position);
  41255. position += 4;
  41256. dictionary.numberOfNewSymbols = readUint32(data, position);
  41257. position += 4;
  41258. args = [dictionary, header.number, header.referredTo,
  41259. data, position, end];
  41260. break;
  41261. case 6: // ImmediateTextRegion
  41262. case 7: // ImmediateLosslessTextRegion
  41263. var textRegion = {};
  41264. textRegion.info = readRegionSegmentInformation(data, position);
  41265. position += RegionSegmentInformationFieldLength;
  41266. var textRegionSegmentFlags = readUint16(data, position);
  41267. position += 2;
  41268. textRegion.huffman = !!(textRegionSegmentFlags & 1);
  41269. textRegion.refinement = !!(textRegionSegmentFlags & 2);
  41270. textRegion.stripSize = 1 << ((textRegionSegmentFlags >> 2) & 3);
  41271. textRegion.referenceCorner = (textRegionSegmentFlags >> 4) & 3;
  41272. textRegion.transposed = !!(textRegionSegmentFlags & 64);
  41273. textRegion.combinationOperator = (textRegionSegmentFlags >> 7) & 3;
  41274. textRegion.defaultPixelValue = (textRegionSegmentFlags >> 9) & 1;
  41275. textRegion.dsOffset = (textRegionSegmentFlags << 17) >> 27;
  41276. textRegion.refinementTemplate = (textRegionSegmentFlags >> 15) & 1;
  41277. if (textRegion.huffman) {
  41278. var textRegionHuffmanFlags = readUint16(data, position);
  41279. position += 2;
  41280. textRegion.huffmanFS = (textRegionHuffmanFlags) & 3;
  41281. textRegion.huffmanDS = (textRegionHuffmanFlags >> 2) & 3;
  41282. textRegion.huffmanDT = (textRegionHuffmanFlags >> 4) & 3;
  41283. textRegion.huffmanRefinementDW = (textRegionHuffmanFlags >> 6) & 3;
  41284. textRegion.huffmanRefinementDH = (textRegionHuffmanFlags >> 8) & 3;
  41285. textRegion.huffmanRefinementDX = (textRegionHuffmanFlags >> 10) & 3;
  41286. textRegion.huffmanRefinementDY = (textRegionHuffmanFlags >> 12) & 3;
  41287. textRegion.huffmanRefinementSizeSelector =
  41288. !!(textRegionHuffmanFlags & 14);
  41289. }
  41290. if (textRegion.refinement && !textRegion.refinementTemplate) {
  41291. at = [];
  41292. for (i = 0; i < 2; i++) {
  41293. at.push({
  41294. x: readInt8(data, position),
  41295. y: readInt8(data, position + 1)
  41296. });
  41297. position += 2;
  41298. }
  41299. textRegion.refinementAt = at;
  41300. }
  41301. textRegion.numberOfSymbolInstances = readUint32(data, position);
  41302. position += 4;
  41303. // TODO 7.4.3.1.7 Symbol ID Huffman table decoding
  41304. if (textRegion.huffman) {
  41305. error('JBIG2 error: huffman is not supported');
  41306. }
  41307. args = [textRegion, header.referredTo, data, position, end];
  41308. break;
  41309. case 38: // ImmediateGenericRegion
  41310. case 39: // ImmediateLosslessGenericRegion
  41311. var genericRegion = {};
  41312. genericRegion.info = readRegionSegmentInformation(data, position);
  41313. position += RegionSegmentInformationFieldLength;
  41314. var genericRegionSegmentFlags = data[position++];
  41315. genericRegion.mmr = !!(genericRegionSegmentFlags & 1);
  41316. genericRegion.template = (genericRegionSegmentFlags >> 1) & 3;
  41317. genericRegion.prediction = !!(genericRegionSegmentFlags & 8);
  41318. if (!genericRegion.mmr) {
  41319. atLength = genericRegion.template === 0 ? 4 : 1;
  41320. at = [];
  41321. for (i = 0; i < atLength; i++) {
  41322. at.push({
  41323. x: readInt8(data, position),
  41324. y: readInt8(data, position + 1)
  41325. });
  41326. position += 2;
  41327. }
  41328. genericRegion.at = at;
  41329. }
  41330. args = [genericRegion, data, position, end];
  41331. break;
  41332. case 48: // PageInformation
  41333. var pageInfo = {
  41334. width: readUint32(data, position),
  41335. height: readUint32(data, position + 4),
  41336. resolutionX: readUint32(data, position + 8),
  41337. resolutionY: readUint32(data, position + 12)
  41338. };
  41339. if (pageInfo.height === 0xFFFFFFFF) {
  41340. delete pageInfo.height;
  41341. }
  41342. var pageSegmentFlags = data[position + 16];
  41343. var pageStripingInformatiom = readUint16(data, position + 17);
  41344. pageInfo.lossless = !!(pageSegmentFlags & 1);
  41345. pageInfo.refinement = !!(pageSegmentFlags & 2);
  41346. pageInfo.defaultPixelValue = (pageSegmentFlags >> 2) & 1;
  41347. pageInfo.combinationOperator = (pageSegmentFlags >> 3) & 3;
  41348. pageInfo.requiresBuffer = !!(pageSegmentFlags & 32);
  41349. pageInfo.combinationOperatorOverride = !!(pageSegmentFlags & 64);
  41350. args = [pageInfo];
  41351. break;
  41352. case 49: // EndOfPage
  41353. break;
  41354. case 50: // EndOfStripe
  41355. break;
  41356. case 51: // EndOfFile
  41357. break;
  41358. case 62: // 7.4.15 defines 2 extension types which
  41359. // are comments and can be ignored.
  41360. break;
  41361. default:
  41362. error('JBIG2 error: segment type ' + header.typeName + '(' +
  41363. header.type + ') is not implemented');
  41364. }
  41365. var callbackName = 'on' + header.typeName;
  41366. if (callbackName in visitor) {
  41367. visitor[callbackName].apply(visitor, args);
  41368. }
  41369. }
  41370. function processSegments(segments, visitor) {
  41371. for (var i = 0, ii = segments.length; i < ii; i++) {
  41372. processSegment(segments[i], visitor);
  41373. }
  41374. }
  41375. function parseJbig2(data, start, end) {
  41376. var position = start;
  41377. if (data[position] !== 0x97 || data[position + 1] !== 0x4A ||
  41378. data[position + 2] !== 0x42 || data[position + 3] !== 0x32 ||
  41379. data[position + 4] !== 0x0D || data[position + 5] !== 0x0A ||
  41380. data[position + 6] !== 0x1A || data[position + 7] !== 0x0A) {
  41381. error('JBIG2 error: invalid header');
  41382. }
  41383. var header = {};
  41384. position += 8;
  41385. var flags = data[position++];
  41386. header.randomAccess = !(flags & 1);
  41387. if (!(flags & 2)) {
  41388. header.numberOfPages = readUint32(data, position);
  41389. position += 4;
  41390. }
  41391. var segments = readSegments(header, data, position, end);
  41392. error('Not implemented');
  41393. // processSegments(segments, new SimpleSegmentVisitor());
  41394. }
  41395. function parseJbig2Chunks(chunks) {
  41396. var visitor = new SimpleSegmentVisitor();
  41397. for (var i = 0, ii = chunks.length; i < ii; i++) {
  41398. var chunk = chunks[i];
  41399. var segments = readSegments({}, chunk.data, chunk.start, chunk.end);
  41400. processSegments(segments, visitor);
  41401. }
  41402. return visitor.buffer;
  41403. }
  41404. function SimpleSegmentVisitor() {}
  41405. SimpleSegmentVisitor.prototype = {
  41406. onPageInformation: function SimpleSegmentVisitor_onPageInformation(info) {
  41407. this.currentPageInfo = info;
  41408. var rowSize = (info.width + 7) >> 3;
  41409. var buffer = new Uint8Array(rowSize * info.height);
  41410. // The contents of ArrayBuffers are initialized to 0.
  41411. // Fill the buffer with 0xFF only if info.defaultPixelValue is set
  41412. if (info.defaultPixelValue) {
  41413. for (var i = 0, ii = buffer.length; i < ii; i++) {
  41414. buffer[i] = 0xFF;
  41415. }
  41416. }
  41417. this.buffer = buffer;
  41418. },
  41419. drawBitmap: function SimpleSegmentVisitor_drawBitmap(regionInfo, bitmap) {
  41420. var pageInfo = this.currentPageInfo;
  41421. var width = regionInfo.width, height = regionInfo.height;
  41422. var rowSize = (pageInfo.width + 7) >> 3;
  41423. var combinationOperator = pageInfo.combinationOperatorOverride ?
  41424. regionInfo.combinationOperator : pageInfo.combinationOperator;
  41425. var buffer = this.buffer;
  41426. var mask0 = 128 >> (regionInfo.x & 7);
  41427. var offset0 = regionInfo.y * rowSize + (regionInfo.x >> 3);
  41428. var i, j, mask, offset;
  41429. switch (combinationOperator) {
  41430. case 0: // OR
  41431. for (i = 0; i < height; i++) {
  41432. mask = mask0;
  41433. offset = offset0;
  41434. for (j = 0; j < width; j++) {
  41435. if (bitmap[i][j]) {
  41436. buffer[offset] |= mask;
  41437. }
  41438. mask >>= 1;
  41439. if (!mask) {
  41440. mask = 128;
  41441. offset++;
  41442. }
  41443. }
  41444. offset0 += rowSize;
  41445. }
  41446. break;
  41447. case 2: // XOR
  41448. for (i = 0; i < height; i++) {
  41449. mask = mask0;
  41450. offset = offset0;
  41451. for (j = 0; j < width; j++) {
  41452. if (bitmap[i][j]) {
  41453. buffer[offset] ^= mask;
  41454. }
  41455. mask >>= 1;
  41456. if (!mask) {
  41457. mask = 128;
  41458. offset++;
  41459. }
  41460. }
  41461. offset0 += rowSize;
  41462. }
  41463. break;
  41464. default:
  41465. error('JBIG2 error: operator ' + combinationOperator +
  41466. ' is not supported');
  41467. }
  41468. },
  41469. onImmediateGenericRegion:
  41470. function SimpleSegmentVisitor_onImmediateGenericRegion(region, data,
  41471. start, end) {
  41472. var regionInfo = region.info;
  41473. var decodingContext = new DecodingContext(data, start, end);
  41474. var bitmap = decodeBitmap(region.mmr, regionInfo.width, regionInfo.height,
  41475. region.template, region.prediction, null,
  41476. region.at, decodingContext);
  41477. this.drawBitmap(regionInfo, bitmap);
  41478. },
  41479. onImmediateLosslessGenericRegion:
  41480. function SimpleSegmentVisitor_onImmediateLosslessGenericRegion() {
  41481. this.onImmediateGenericRegion.apply(this, arguments);
  41482. },
  41483. onSymbolDictionary:
  41484. function SimpleSegmentVisitor_onSymbolDictionary(dictionary,
  41485. currentSegment,
  41486. referredSegments,
  41487. data, start, end) {
  41488. var huffmanTables;
  41489. if (dictionary.huffman) {
  41490. error('JBIG2 error: huffman is not supported');
  41491. }
  41492. // Combines exported symbols from all referred segments
  41493. var symbols = this.symbols;
  41494. if (!symbols) {
  41495. this.symbols = symbols = {};
  41496. }
  41497. var inputSymbols = [];
  41498. for (var i = 0, ii = referredSegments.length; i < ii; i++) {
  41499. inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
  41500. }
  41501. var decodingContext = new DecodingContext(data, start, end);
  41502. symbols[currentSegment] = decodeSymbolDictionary(dictionary.huffman,
  41503. dictionary.refinement, inputSymbols, dictionary.numberOfNewSymbols,
  41504. dictionary.numberOfExportedSymbols, huffmanTables,
  41505. dictionary.template, dictionary.at,
  41506. dictionary.refinementTemplate, dictionary.refinementAt,
  41507. decodingContext);
  41508. },
  41509. onImmediateTextRegion:
  41510. function SimpleSegmentVisitor_onImmediateTextRegion(region,
  41511. referredSegments,
  41512. data, start, end) {
  41513. var regionInfo = region.info;
  41514. var huffmanTables;
  41515. // Combines exported symbols from all referred segments
  41516. var symbols = this.symbols;
  41517. var inputSymbols = [];
  41518. for (var i = 0, ii = referredSegments.length; i < ii; i++) {
  41519. inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
  41520. }
  41521. var symbolCodeLength = log2(inputSymbols.length);
  41522. var decodingContext = new DecodingContext(data, start, end);
  41523. var bitmap = decodeTextRegion(region.huffman, region.refinement,
  41524. regionInfo.width, regionInfo.height, region.defaultPixelValue,
  41525. region.numberOfSymbolInstances, region.stripSize, inputSymbols,
  41526. symbolCodeLength, region.transposed, region.dsOffset,
  41527. region.referenceCorner, region.combinationOperator, huffmanTables,
  41528. region.refinementTemplate, region.refinementAt, decodingContext);
  41529. this.drawBitmap(regionInfo, bitmap);
  41530. },
  41531. onImmediateLosslessTextRegion:
  41532. function SimpleSegmentVisitor_onImmediateLosslessTextRegion() {
  41533. this.onImmediateTextRegion.apply(this, arguments);
  41534. }
  41535. };
  41536. function Jbig2Image() {}
  41537. Jbig2Image.prototype = {
  41538. parseChunks: function Jbig2Image_parseChunks(chunks) {
  41539. return parseJbig2Chunks(chunks);
  41540. }
  41541. };
  41542. return Jbig2Image;
  41543. })();
  41544. var bidi = PDFJS.bidi = (function bidiClosure() {
  41545. // Character types for symbols from 0000 to 00FF.
  41546. var baseTypes = [
  41547. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS',
  41548. 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  41549. 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON',
  41550. 'ON', 'ON', 'ON', 'ON', 'ON', 'CS', 'ON', 'CS', 'ON', 'EN', 'EN', 'EN',
  41551. 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'ON', 'ON', 'ON', 'ON', 'ON',
  41552. 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  41553. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON',
  41554. 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  41555. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  41556. 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN',
  41557. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  41558. 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
  41559. 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON',
  41560. 'ON', 'ON', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON',
  41561. 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  41562. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  41563. 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  41564. 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
  41565. 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'
  41566. ];
  41567. // Character types for symbols from 0600 to 06FF
  41568. var arabicTypes = [
  41569. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41570. 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL',
  41571. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41572. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41573. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41574. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41575. 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
  41576. 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL',
  41577. 'AL', 'AL', 'AL', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN',
  41578. 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL',
  41579. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41580. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41581. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41582. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41583. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41584. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41585. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41586. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41587. 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
  41588. 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'ON', 'NSM',
  41589. 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
  41590. 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL'
  41591. ];
  41592. function isOdd(i) {
  41593. return (i & 1) !== 0;
  41594. }
  41595. function isEven(i) {
  41596. return (i & 1) === 0;
  41597. }
  41598. function findUnequal(arr, start, value) {
  41599. for (var j = start, jj = arr.length; j < jj; ++j) {
  41600. if (arr[j] !== value) {
  41601. return j;
  41602. }
  41603. }
  41604. return j;
  41605. }
  41606. function setValues(arr, start, end, value) {
  41607. for (var j = start; j < end; ++j) {
  41608. arr[j] = value;
  41609. }
  41610. }
  41611. function reverseValues(arr, start, end) {
  41612. for (var i = start, j = end - 1; i < j; ++i, --j) {
  41613. var temp = arr[i];
  41614. arr[i] = arr[j];
  41615. arr[j] = temp;
  41616. }
  41617. }
  41618. function createBidiText(str, isLTR, vertical) {
  41619. return {
  41620. str: str,
  41621. dir: (vertical ? 'ttb' : (isLTR ? 'ltr' : 'rtl'))
  41622. };
  41623. }
  41624. // These are used in bidi(), which is called frequently. We re-use them on
  41625. // each call to avoid unnecessary allocations.
  41626. var chars = [];
  41627. var types = [];
  41628. function bidi(str, startLevel, vertical) {
  41629. var isLTR = true;
  41630. var strLength = str.length;
  41631. if (strLength === 0 || vertical) {
  41632. return createBidiText(str, isLTR, vertical);
  41633. }
  41634. // Get types and fill arrays
  41635. chars.length = strLength;
  41636. types.length = strLength;
  41637. var numBidi = 0;
  41638. var i, ii;
  41639. for (i = 0; i < strLength; ++i) {
  41640. chars[i] = str.charAt(i);
  41641. var charCode = str.charCodeAt(i);
  41642. var charType = 'L';
  41643. if (charCode <= 0x00ff) {
  41644. charType = baseTypes[charCode];
  41645. } else if (0x0590 <= charCode && charCode <= 0x05f4) {
  41646. charType = 'R';
  41647. } else if (0x0600 <= charCode && charCode <= 0x06ff) {
  41648. charType = arabicTypes[charCode & 0xff];
  41649. } else if (0x0700 <= charCode && charCode <= 0x08AC) {
  41650. charType = 'AL';
  41651. }
  41652. if (charType === 'R' || charType === 'AL' || charType === 'AN') {
  41653. numBidi++;
  41654. }
  41655. types[i] = charType;
  41656. }
  41657. // Detect the bidi method
  41658. // - If there are no rtl characters then no bidi needed
  41659. // - If less than 30% chars are rtl then string is primarily ltr
  41660. // - If more than 30% chars are rtl then string is primarily rtl
  41661. if (numBidi === 0) {
  41662. isLTR = true;
  41663. return createBidiText(str, isLTR);
  41664. }
  41665. if (startLevel === -1) {
  41666. if ((strLength / numBidi) < 0.3) {
  41667. isLTR = true;
  41668. startLevel = 0;
  41669. } else {
  41670. isLTR = false;
  41671. startLevel = 1;
  41672. }
  41673. }
  41674. var levels = [];
  41675. for (i = 0; i < strLength; ++i) {
  41676. levels[i] = startLevel;
  41677. }
  41678. /*
  41679. X1-X10: skip most of this, since we are NOT doing the embeddings.
  41680. */
  41681. var e = (isOdd(startLevel) ? 'R' : 'L');
  41682. var sor = e;
  41683. var eor = sor;
  41684. /*
  41685. W1. Examine each non-spacing mark (NSM) in the level run, and change the
  41686. type of the NSM to the type of the previous character. If the NSM is at the
  41687. start of the level run, it will get the type of sor.
  41688. */
  41689. var lastType = sor;
  41690. for (i = 0; i < strLength; ++i) {
  41691. if (types[i] === 'NSM') {
  41692. types[i] = lastType;
  41693. } else {
  41694. lastType = types[i];
  41695. }
  41696. }
  41697. /*
  41698. W2. Search backwards from each instance of a European number until the
  41699. first strong type (R, L, AL, or sor) is found. If an AL is found, change
  41700. the type of the European number to Arabic number.
  41701. */
  41702. lastType = sor;
  41703. var t;
  41704. for (i = 0; i < strLength; ++i) {
  41705. t = types[i];
  41706. if (t === 'EN') {
  41707. types[i] = (lastType === 'AL') ? 'AN' : 'EN';
  41708. } else if (t === 'R' || t === 'L' || t === 'AL') {
  41709. lastType = t;
  41710. }
  41711. }
  41712. /*
  41713. W3. Change all ALs to R.
  41714. */
  41715. for (i = 0; i < strLength; ++i) {
  41716. t = types[i];
  41717. if (t === 'AL') {
  41718. types[i] = 'R';
  41719. }
  41720. }
  41721. /*
  41722. W4. A single European separator between two European numbers changes to a
  41723. European number. A single common separator between two numbers of the same
  41724. type changes to that type:
  41725. */
  41726. for (i = 1; i < strLength - 1; ++i) {
  41727. if (types[i] === 'ES' && types[i - 1] === 'EN' && types[i + 1] === 'EN') {
  41728. types[i] = 'EN';
  41729. }
  41730. if (types[i] === 'CS' &&
  41731. (types[i - 1] === 'EN' || types[i - 1] === 'AN') &&
  41732. types[i + 1] === types[i - 1]) {
  41733. types[i] = types[i - 1];
  41734. }
  41735. }
  41736. /*
  41737. W5. A sequence of European terminators adjacent to European numbers changes
  41738. to all European numbers:
  41739. */
  41740. for (i = 0; i < strLength; ++i) {
  41741. if (types[i] === 'EN') {
  41742. // do before
  41743. var j;
  41744. for (j = i - 1; j >= 0; --j) {
  41745. if (types[j] !== 'ET') {
  41746. break;
  41747. }
  41748. types[j] = 'EN';
  41749. }
  41750. // do after
  41751. for (j = i + 1; j < strLength; --j) {
  41752. if (types[j] !== 'ET') {
  41753. break;
  41754. }
  41755. types[j] = 'EN';
  41756. }
  41757. }
  41758. }
  41759. /*
  41760. W6. Otherwise, separators and terminators change to Other Neutral:
  41761. */
  41762. for (i = 0; i < strLength; ++i) {
  41763. t = types[i];
  41764. if (t === 'WS' || t === 'ES' || t === 'ET' || t === 'CS') {
  41765. types[i] = 'ON';
  41766. }
  41767. }
  41768. /*
  41769. W7. Search backwards from each instance of a European number until the
  41770. first strong type (R, L, or sor) is found. If an L is found, then change
  41771. the type of the European number to L.
  41772. */
  41773. lastType = sor;
  41774. for (i = 0; i < strLength; ++i) {
  41775. t = types[i];
  41776. if (t === 'EN') {
  41777. types[i] = ((lastType === 'L') ? 'L' : 'EN');
  41778. } else if (t === 'R' || t === 'L') {
  41779. lastType = t;
  41780. }
  41781. }
  41782. /*
  41783. N1. A sequence of neutrals takes the direction of the surrounding strong
  41784. text if the text on both sides has the same direction. European and Arabic
  41785. numbers are treated as though they were R. Start-of-level-run (sor) and
  41786. end-of-level-run (eor) are used at level run boundaries.
  41787. */
  41788. for (i = 0; i < strLength; ++i) {
  41789. if (types[i] === 'ON') {
  41790. var end = findUnequal(types, i + 1, 'ON');
  41791. var before = sor;
  41792. if (i > 0) {
  41793. before = types[i - 1];
  41794. }
  41795. var after = eor;
  41796. if (end + 1 < strLength) {
  41797. after = types[end + 1];
  41798. }
  41799. if (before !== 'L') {
  41800. before = 'R';
  41801. }
  41802. if (after !== 'L') {
  41803. after = 'R';
  41804. }
  41805. if (before === after) {
  41806. setValues(types, i, end, before);
  41807. }
  41808. i = end - 1; // reset to end (-1 so next iteration is ok)
  41809. }
  41810. }
  41811. /*
  41812. N2. Any remaining neutrals take the embedding direction.
  41813. */
  41814. for (i = 0; i < strLength; ++i) {
  41815. if (types[i] === 'ON') {
  41816. types[i] = e;
  41817. }
  41818. }
  41819. /*
  41820. I1. For all characters with an even (left-to-right) embedding direction,
  41821. those of type R go up one level and those of type AN or EN go up two
  41822. levels.
  41823. I2. For all characters with an odd (right-to-left) embedding direction,
  41824. those of type L, EN or AN go up one level.
  41825. */
  41826. for (i = 0; i < strLength; ++i) {
  41827. t = types[i];
  41828. if (isEven(levels[i])) {
  41829. if (t === 'R') {
  41830. levels[i] += 1;
  41831. } else if (t === 'AN' || t === 'EN') {
  41832. levels[i] += 2;
  41833. }
  41834. } else { // isOdd
  41835. if (t === 'L' || t === 'AN' || t === 'EN') {
  41836. levels[i] += 1;
  41837. }
  41838. }
  41839. }
  41840. /*
  41841. L1. On each line, reset the embedding level of the following characters to
  41842. the paragraph embedding level:
  41843. segment separators,
  41844. paragraph separators,
  41845. any sequence of whitespace characters preceding a segment separator or
  41846. paragraph separator, and any sequence of white space characters at the end
  41847. of the line.
  41848. */
  41849. // don't bother as text is only single line
  41850. /*
  41851. L2. From the highest level found in the text to the lowest odd level on
  41852. each line, reverse any contiguous sequence of characters that are at that
  41853. level or higher.
  41854. */
  41855. // find highest level & lowest odd level
  41856. var highestLevel = -1;
  41857. var lowestOddLevel = 99;
  41858. var level;
  41859. for (i = 0, ii = levels.length; i < ii; ++i) {
  41860. level = levels[i];
  41861. if (highestLevel < level) {
  41862. highestLevel = level;
  41863. }
  41864. if (lowestOddLevel > level && isOdd(level)) {
  41865. lowestOddLevel = level;
  41866. }
  41867. }
  41868. // now reverse between those limits
  41869. for (level = highestLevel; level >= lowestOddLevel; --level) {
  41870. // find segments to reverse
  41871. var start = -1;
  41872. for (i = 0, ii = levels.length; i < ii; ++i) {
  41873. if (levels[i] < level) {
  41874. if (start >= 0) {
  41875. reverseValues(chars, start, i);
  41876. start = -1;
  41877. }
  41878. } else if (start < 0) {
  41879. start = i;
  41880. }
  41881. }
  41882. if (start >= 0) {
  41883. reverseValues(chars, start, levels.length);
  41884. }
  41885. }
  41886. /*
  41887. L3. Combining marks applied to a right-to-left base character will at this
  41888. point precede their base character. If the rendering engine expects them to
  41889. follow the base characters in the final display process, then the ordering
  41890. of the marks and the base character must be reversed.
  41891. */
  41892. // don't bother for now
  41893. /*
  41894. L4. A character that possesses the mirrored property as specified by
  41895. Section 4.7, Mirrored, must be depicted by a mirrored glyph if the resolved
  41896. directionality of that character is R.
  41897. */
  41898. // don't mirror as characters are already mirrored in the pdf
  41899. // Finally, return string
  41900. var result = '';
  41901. for (i = 0, ii = chars.length; i < ii; ++i) {
  41902. var ch = chars[i];
  41903. if (ch !== '<' && ch !== '>') {
  41904. result += ch;
  41905. }
  41906. }
  41907. return createBidiText(result, isLTR);
  41908. }
  41909. return bidi;
  41910. })();
  41911. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  41912. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  41913. /* Copyright 2014 Opera Software ASA
  41914. *
  41915. * Licensed under the Apache License, Version 2.0 (the "License");
  41916. * you may not use this file except in compliance with the License.
  41917. * You may obtain a copy of the License at
  41918. *
  41919. * http://www.apache.org/licenses/LICENSE-2.0
  41920. *
  41921. * Unless required by applicable law or agreed to in writing, software
  41922. * distributed under the License is distributed on an "AS IS" BASIS,
  41923. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41924. * See the License for the specific language governing permissions and
  41925. * limitations under the License.
  41926. *
  41927. *
  41928. * Based on https://code.google.com/p/smhasher/wiki/MurmurHash3.
  41929. * Hashes roughly 100 KB per millisecond on i7 3.4 GHz.
  41930. */
  41931. /* globals Uint32ArrayView */
  41932. 'use strict';
  41933. var MurmurHash3_64 = (function MurmurHash3_64Closure (seed) {
  41934. // Workaround for missing math precison in JS.
  41935. var MASK_HIGH = 0xffff0000;
  41936. var MASK_LOW = 0xffff;
  41937. function MurmurHash3_64 (seed) {
  41938. var SEED = 0xc3d2e1f0;
  41939. this.h1 = seed ? seed & 0xffffffff : SEED;
  41940. this.h2 = seed ? seed & 0xffffffff : SEED;
  41941. }
  41942. var alwaysUseUint32ArrayView = false;
  41943. // old webkits have issues with non-aligned arrays
  41944. try {
  41945. new Uint32Array(new Uint8Array(5).buffer, 0, 1);
  41946. } catch (e) {
  41947. alwaysUseUint32ArrayView = true;
  41948. }
  41949. MurmurHash3_64.prototype = {
  41950. update: function MurmurHash3_64_update(input) {
  41951. var useUint32ArrayView = alwaysUseUint32ArrayView;
  41952. var i;
  41953. if (typeof input === 'string') {
  41954. var data = new Uint8Array(input.length * 2);
  41955. var length = 0;
  41956. for (i = 0; i < input.length; i++) {
  41957. var code = input.charCodeAt(i);
  41958. if (code <= 0xff) {
  41959. data[length++] = code;
  41960. }
  41961. else {
  41962. data[length++] = code >>> 8;
  41963. data[length++] = code & 0xff;
  41964. }
  41965. }
  41966. } else if (input instanceof Uint8Array) {
  41967. data = input;
  41968. length = data.length;
  41969. } else if (typeof input === 'object' && ('length' in input)) {
  41970. // processing regular arrays as well, e.g. for IE9
  41971. data = input;
  41972. length = data.length;
  41973. useUint32ArrayView = true;
  41974. } else {
  41975. throw new Error('Wrong data format in MurmurHash3_64_update. ' +
  41976. 'Input must be a string or array.');
  41977. }
  41978. var blockCounts = length >> 2;
  41979. var tailLength = length - blockCounts * 4;
  41980. // we don't care about endianness here
  41981. var dataUint32 = useUint32ArrayView ?
  41982. new Uint32ArrayView(data, blockCounts) :
  41983. new Uint32Array(data.buffer, 0, blockCounts);
  41984. var k1 = 0;
  41985. var k2 = 0;
  41986. var h1 = this.h1;
  41987. var h2 = this.h2;
  41988. var C1 = 0xcc9e2d51;
  41989. var C2 = 0x1b873593;
  41990. var C1_LOW = C1 & MASK_LOW;
  41991. var C2_LOW = C2 & MASK_LOW;
  41992. for (i = 0; i < blockCounts; i++) {
  41993. if (i & 1) {
  41994. k1 = dataUint32[i];
  41995. k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);
  41996. k1 = k1 << 15 | k1 >>> 17;
  41997. k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);
  41998. h1 ^= k1;
  41999. h1 = h1 << 13 | h1 >>> 19;
  42000. h1 = h1 * 5 + 0xe6546b64;
  42001. } else {
  42002. k2 = dataUint32[i];
  42003. k2 = (k2 * C1 & MASK_HIGH) | (k2 * C1_LOW & MASK_LOW);
  42004. k2 = k2 << 15 | k2 >>> 17;
  42005. k2 = (k2 * C2 & MASK_HIGH) | (k2 * C2_LOW & MASK_LOW);
  42006. h2 ^= k2;
  42007. h2 = h2 << 13 | h2 >>> 19;
  42008. h2 = h2 * 5 + 0xe6546b64;
  42009. }
  42010. }
  42011. k1 = 0;
  42012. switch (tailLength) {
  42013. case 3:
  42014. k1 ^= data[blockCounts * 4 + 2] << 16;
  42015. /* falls through */
  42016. case 2:
  42017. k1 ^= data[blockCounts * 4 + 1] << 8;
  42018. /* falls through */
  42019. case 1:
  42020. k1 ^= data[blockCounts * 4];
  42021. /* falls through */
  42022. k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);
  42023. k1 = k1 << 15 | k1 >>> 17;
  42024. k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);
  42025. if (blockCounts & 1) {
  42026. h1 ^= k1;
  42027. } else {
  42028. h2 ^= k1;
  42029. }
  42030. }
  42031. this.h1 = h1;
  42032. this.h2 = h2;
  42033. return this;
  42034. },
  42035. hexdigest: function MurmurHash3_64_hexdigest () {
  42036. var h1 = this.h1;
  42037. var h2 = this.h2;
  42038. h1 ^= h2 >>> 1;
  42039. h1 = (h1 * 0xed558ccd & MASK_HIGH) | (h1 * 0x8ccd & MASK_LOW);
  42040. h2 = (h2 * 0xff51afd7 & MASK_HIGH) |
  42041. (((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16);
  42042. h1 ^= h2 >>> 1;
  42043. h1 = (h1 * 0x1a85ec53 & MASK_HIGH) | (h1 * 0xec53 & MASK_LOW);
  42044. h2 = (h2 * 0xc4ceb9fe & MASK_HIGH) |
  42045. (((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16);
  42046. h1 ^= h2 >>> 1;
  42047. for (var i = 0, arr = [h1, h2], str = ''; i < arr.length; i++) {
  42048. var hex = (arr[i] >>> 0).toString(16);
  42049. while (hex.length < 8) {
  42050. hex = '0' + hex;
  42051. }
  42052. str += hex;
  42053. }
  42054. return str;
  42055. }
  42056. };
  42057. return MurmurHash3_64;
  42058. })();
  42059. }).call((typeof window === 'undefined') ? this : window);
  42060. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  42061. // workerSrc is not set -- using last script url to define default location
  42062. PDFJS.workerSrc = (function () {
  42063. 'use strict';
  42064. var scriptTagContainer = document.body ||
  42065. document.getElementsByTagName('head')[0];
  42066. var pdfjsSrc = scriptTagContainer.lastChild.src;
  42067. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  42068. })();
  42069. }